图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.6 KiB

  1. from typing import Optional
  2. from ._util import to_string
  3. from .document import Document
  4. class Result:
  5. """
  6. Represents the result of a search query, and has an array of Document
  7. objects
  8. """
  9. def __init__(
  10. self,
  11. res,
  12. hascontent,
  13. duration=0,
  14. has_payload=False,
  15. with_scores=False,
  16. field_encodings: Optional[dict] = None,
  17. ):
  18. """
  19. - duration: the execution time of the query
  20. - has_payload: whether the query has payloads
  21. - with_scores: whether the query has scores
  22. - field_encodings: a dictionary of field encodings if any is provided
  23. """
  24. self.total = res[0]
  25. self.duration = duration
  26. self.docs = []
  27. step = 1
  28. if hascontent:
  29. step = step + 1
  30. if has_payload:
  31. step = step + 1
  32. if with_scores:
  33. step = step + 1
  34. offset = 2 if with_scores else 1
  35. for i in range(1, len(res), step):
  36. id = to_string(res[i])
  37. payload = to_string(res[i + offset]) if has_payload else None
  38. # fields_offset = 2 if has_payload else 1
  39. fields_offset = offset + 1 if has_payload else offset
  40. score = float(res[i + 1]) if with_scores else None
  41. fields = {}
  42. if hascontent and res[i + fields_offset] is not None:
  43. keys = map(to_string, res[i + fields_offset][::2])
  44. values = res[i + fields_offset][1::2]
  45. for key, value in zip(keys, values):
  46. if field_encodings is None or key not in field_encodings:
  47. fields[key] = to_string(value)
  48. continue
  49. encoding = field_encodings[key]
  50. # If the encoding is None, we don't need to decode the value
  51. if encoding is None:
  52. fields[key] = value
  53. else:
  54. fields[key] = to_string(value, encoding=encoding)
  55. try:
  56. del fields["id"]
  57. except KeyError:
  58. pass
  59. try:
  60. fields["json"] = fields["$"]
  61. del fields["$"]
  62. except KeyError:
  63. pass
  64. doc = (
  65. Document(id, score=score, payload=payload, **fields)
  66. if with_scores
  67. else Document(id, payload=payload, **fields)
  68. )
  69. self.docs.append(doc)
  70. def __repr__(self) -> str:
  71. return f"Result{{{self.total} total, docs: {self.docs}}}"