result.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from ._util import to_string
  2. from .document import Document
  3. class Result:
  4. """
  5. Represents the result of a search query, and has an array of Document
  6. objects
  7. """
  8. def __init__(
  9. self, res, hascontent, duration=0, has_payload=False, with_scores=False
  10. ):
  11. """
  12. - **snippets**: An optional dictionary of the form
  13. {field: snippet_size} for snippet formatting
  14. """
  15. self.total = res[0]
  16. self.duration = duration
  17. self.docs = []
  18. step = 1
  19. if hascontent:
  20. step = step + 1
  21. if has_payload:
  22. step = step + 1
  23. if with_scores:
  24. step = step + 1
  25. offset = 2 if with_scores else 1
  26. for i in range(1, len(res), step):
  27. id = to_string(res[i])
  28. payload = to_string(res[i + offset]) if has_payload else None
  29. # fields_offset = 2 if has_payload else 1
  30. fields_offset = offset + 1 if has_payload else offset
  31. score = float(res[i + 1]) if with_scores else None
  32. fields = {}
  33. if hascontent and res[i + fields_offset] is not None:
  34. fields = (
  35. dict(
  36. dict(
  37. zip(
  38. map(to_string, res[i + fields_offset][::2]),
  39. map(to_string, res[i + fields_offset][1::2]),
  40. )
  41. )
  42. )
  43. if hascontent
  44. else {}
  45. )
  46. try:
  47. del fields["id"]
  48. except KeyError:
  49. pass
  50. try:
  51. fields["json"] = fields["$"]
  52. del fields["$"]
  53. except KeyError:
  54. pass
  55. doc = (
  56. Document(id, score=score, payload=payload, **fields)
  57. if with_scores
  58. else Document(id, payload=payload, **fields)
  59. )
  60. self.docs.append(doc)
  61. def __repr__(self) -> str:
  62. return f"Result{{{self.total} total, docs: {self.docs}}}"