Debian Codegraph @

valkey/commands/search/querystring.py

raw
1 def tags(*t):
2 """
3 Indicate that the values should be matched to a tag field
4
5 ### Parameters
6
7 - **t**: Tags to search for
8 """
9 if not t:
10 raise ValueError("At least one tag must be specified")
11 return TagValue(*t)
12
13
14 def between(a, b, inclusive_min=True, inclusive_max=True):
15 """
16 Indicate that value is a numeric range
17 """
18 return RangeValue(a, b, inclusive_min=inclusive_min, inclusive_max=inclusive_max)
19
20
21 def equal(n):
22 """
23 Match a numeric value
24 """
25 return between(n, n)
26
27
28 def lt(n):
29 """
30 Match any value less than n
31 """
32 return between(None, n, inclusive_max=False)
33
34
35 def le(n):
36 """
37 Match any value less or equal to n
38 """
39 return between(None, n, inclusive_max=True)
40
41
42 def gt(n):
43 """
44 Match any value greater than n
45 """
46 return between(n, None, inclusive_min=False)
47
48
49 def ge(n):
50 """
51 Match any value greater or equal to n
52 """
53 return between(n, None, inclusive_min=True)
54
55
56 def geo(lat, lon, radius, unit="km"):
57 """
58 Indicate that value is a geo region
59 """
60 return GeoValue(lat, lon, radius, unit)
61
62
63 class Value:
64 @property
65 def combinable(self):
66 """
67 Whether this type of value may be combined with other values
68 for the same field. This makes the filter potentially more efficient
69 """
70 return False
71
72 @staticmethod
73 def make_value(v):
74 """
75 Convert an object to a value, if it is not a value already
76 """
77 if isinstance(v, Value):
78 return v
79 return ScalarValue(v)
80
81 def to_string(self):
82 raise NotImplementedError()
83
84 def __str__(self):
85 return self.to_string()
86
87
88 class RangeValue(Value):
89 combinable = False
90
91 def __init__(self, a, b, inclusive_min=False, inclusive_max=False):
92 if a is None:
93 a = "-inf"
94 if b is None:
95 b = "inf"
96 self.range = [str(a), str(b)]
97 self.inclusive_min = inclusive_min
98 self.inclusive_max = inclusive_max
99
100 def to_string(self):
101 return "[{1}{0[0]} {2}{0[1]}]".format(
102 self.range,
103 "(" if not self.inclusive_min else "",
104 "(" if not self.inclusive_max else "",
105 )
106
107
108 class ScalarValue(Value):
109 combinable = True
110
111 def __init__(self, v):
112 self.v = str(v)
113
114 def to_string(self):
115 return self.v
116
117
118 class TagValue(Value):
119 combinable = False
120
121 def __init__(self, *tags):
122 self.tags = tags
123
124 def to_string(self):
125 return "{" + " | ".join(str(t) for t in self.tags) + "}"
126
127
128 class GeoValue(Value):
129 def __init__(self, lon, lat, radius, unit="km"):
130 self.lon = lon
131 self.lat = lat
132 self.radius = radius
133 self.unit = unit
134
135 def to_string(self):
136 return f"[{self.lon} {self.lat} {self.radius} {self.unit}]"
137
138
139 class Node:
140 def __init__(self, *children, **kwparams):
141 """
142 Create a node
143
144 ### Parameters
145
146 - **children**: One or more sub-conditions. These can be additional
147 `intersect`, `disjunct`, `union`, `optional`, or any other `Node`
148 type.
149
150 The semantics of multiple conditions are dependent on the type of
151 query. For an `intersection` node, this amounts to a logical AND,
152 for a `union` node, this amounts to a logical `OR`.
153
154 - **kwparams**: key-value parameters. Each key is the name of a field,
155 and the value should be a field value. This can be one of the
156 following:
157
158 - Simple string (for text field matches)
159 - value returned by one of the helper functions
160 - list of either a string or a value
161
162
163 ### Examples
164
165 Field `num` should be between 1 and 10
166 ```
167 intersect(num=between(1, 10)
168 ```
169
170 Name can either be `bob` or `john`
171
172 ```
173 union(name=("bob", "john"))
174 ```
175
176 Don't select countries in Israel, Japan, or US
177
178 ```
179 disjunct_union(country=("il", "jp", "us"))
180 ```
181 """
182
183 self.params = []
184
185 kvparams = {}
186 for k, v in kwparams.items():
187 curvals = kvparams.setdefault(k, [])
188 if isinstance(v, (str, int, float)):
189 curvals.append(Value.make_value(v))
190 elif isinstance(v, Value):
191 curvals.append(v)
192 else:
193 curvals.extend(Value.make_value(subv) for subv in v)
194
195 self.params += [Node.to_node(p) for p in children]
196
197 for k, v in kvparams.items():
198 self.params.extend(self.join_fields(k, v))
199
200 def join_fields(self, key, vals):
201 if len(vals) == 1:
202 return [BaseNode(f"@{key}:{vals[0].to_string()}")]
203 if not vals[0].combinable:
204 return [BaseNode(f"@{key}:{v.to_string()}") for v in vals]
205 s = BaseNode(f"@{key}:({self.JOINSTR.join(v.to_string() for v in vals)})")
206 return [s]
207
208 @classmethod
209 def to_node(cls, obj): # noqa
210 if isinstance(obj, Node):
211 return obj
212 return BaseNode(obj)
213
214 @property
215 def JOINSTR(self):
216 raise NotImplementedError()
217
218 def to_string(self, with_parens=None):
219 with_parens = self._should_use_paren(with_parens)
220 pre, post = ("(", ")") if with_parens else ("", "")
221 return f"{pre}{self.JOINSTR.join(n.to_string() for n in self.params)}{post}"
222
223 def _should_use_paren(self, optval):
224 if optval is not None:
225 return optval
226 return len(self.params) > 1
227
228 def __str__(self):
229 return self.to_string()
230
231
232 class BaseNode(Node):
233 def __init__(self, s):
234 super().__init__()
235 self.s = str(s)
236
237 def to_string(self, with_parens=None):
238 return self.s
239
240
241 class IntersectNode(Node):
242 """
243 Create an intersection node. All children need to be satisfied in order for
244 this node to evaluate as true
245 """
246
247 JOINSTR = " "
248
249
250 class UnionNode(Node):
251 """
252 Create a union node. Any of the children need to be satisfied in order for
253 this node to evaluate as true
254 """
255
256 JOINSTR = "|"
257
258
259 class DisjunctNode(IntersectNode):
260 """
261 Create a disjunct node. In order for this node to be true, all of its
262 children must evaluate to false
263 """
264
265 def to_string(self, with_parens=None):
266 with_parens = self._should_use_paren(with_parens)
267 ret = super().to_string(with_parens=False)
268 if with_parens:
269 return "(-" + ret + ")"
270 else:
271 return "-" + ret
272
273
274 class DisjunctUnion(DisjunctNode):
275 """
276 This node is true if *all* of its children are false. This is equivalent to
277 ```
278 disjunct(union(...))
279 ```
280 """
281
282 JOINSTR = "|"
283
284
285 class OptionalNode(IntersectNode):
286 """
287 Create an optional node. If this nodes evaluates to true, then the document
288 will be rated higher in score/rank.
289 """
290
291 def to_string(self, with_parens=None):
292 with_parens = self._should_use_paren(with_parens)
293 ret = super().to_string(with_parens=False)
294 if with_parens:
295 return "(~" + ret + ")"
296 else:
297 return "~" + ret
298
299
300 def intersect(*args, **kwargs):
301 return IntersectNode(*args, **kwargs)
302
303
304 def union(*args, **kwargs):
305 return UnionNode(*args, **kwargs)
306
307
308 def disjunct(*args, **kwargs):
309 return DisjunctNode(*args, **kwargs)
310
311
312 def disjunct_union(*args, **kwargs):
313 return DisjunctUnion(*args, **kwargs)
314
315
316 def querystring(*args, **kwargs):
317 return intersect(*args, **kwargs).to_string()