Debian Codegraph @

valkey/commands/search/result.py

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