Debian Codegraph @

valkey/commands/search/suggestion.py

raw
1 from typing import Optional
2
3 from ._util import to_string
4
5
6 class Suggestion:
7 """
8 Represents a single suggestion being sent or returned from the
9 autocomplete server
10 """
11
12 def __init__(
13 self, string: str, score: float = 1.0, payload: Optional[str] = None
14 ) -> None:
15 self.string = to_string(string)
16 self.payload = to_string(payload)
17 self.score = score
18
19 def __repr__(self) -> str:
20 return self.string
21
22
23 class SuggestionParser:
24 """
25 Internal class used to parse results from the `SUGGET` command.
26 This needs to consume either 1, 2, or 3 values at a time from
27 the return value depending on what objects were requested
28 """
29
30 def __init__(self, with_scores: bool, with_payloads: bool, ret) -> None:
31 self.with_scores = with_scores
32 self.with_payloads = with_payloads
33
34 if with_scores and with_payloads:
35 self.sugsize = 3
36 self._scoreidx = 1
37 self._payloadidx = 2
38 elif with_scores:
39 self.sugsize = 2
40 self._scoreidx = 1
41 elif with_payloads:
42 self.sugsize = 2
43 self._payloadidx = 1
44 else:
45 self.sugsize = 1
46 self._scoreidx = -1
47
48 self._sugs = ret
49
50 def __iter__(self):
51 for i in range(0, len(self._sugs), self.sugsize):
52 ss = self._sugs[i]
53 score = float(self._sugs[i + self._scoreidx]) if self.with_scores else 1.0
54 payload = self._sugs[i + self._payloadidx] if self.with_payloads else None
55 yield Suggestion(ss, score, payload)