-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquery_builder.py
More file actions
331 lines (285 loc) · 9.8 KB
/
Copy pathquery_builder.py
File metadata and controls
331 lines (285 loc) · 9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""RediSearch query builder - generates query syntax from analyzed queries."""
from __future__ import annotations
import warnings
# Redis default stopwords - these are not indexed by default
# See: https://redis.io/docs/latest/develop/ai/search-and-query/advanced-concepts/stopwords/
REDIS_DEFAULT_STOPWORDS = frozenset(
{
"a",
"is",
"the",
"an",
"and",
"are",
"as",
"at",
"be",
"but",
"by",
"for",
"if",
"in",
"into",
"it",
"no",
"not",
"of",
"on",
"or",
"such",
"that",
"their",
"then",
"there",
"these",
"they",
"this",
"to",
"was",
"will",
"with",
}
)
class QueryBuilder:
"""Builds RediSearch query syntax from conditions."""
# Characters that need escaping in TAG values
TAG_SPECIAL_CHARS = r".,<>{}[]\"':;!@#$%^&*()-+=~"
def build_text_condition(
self,
field: str | list[str],
operator: str,
value: str,
negated: bool = False,
) -> str:
"""Build query syntax for TEXT field conditions.
Args:
field: Field name or list of field names for multi-field search.
operator: One of =, MATCH, LIKE, FUZZY.
value: The search term or pattern.
negated: If True, prefix with - for negation.
Returns:
RediSearch query syntax like @field:term or @field:"phrase".
"""
prefix = "-" if negated else ""
# Handle multi-field search
if isinstance(field, list):
field_str = "|".join(field)
return f"(@{field_str}:{value})"
# Handle different operators
if operator == "LIKE":
# Convert SQL LIKE pattern (%) to RediSearch prefix (*)
search_value = value.replace("%", "*")
elif operator == "FUZZY":
# Wrap with % for fuzzy matching
search_value = f"%{value}%"
elif " " in value:
# Phrase search - filter stopwords and wrap in quotes
words = value.split()
removed_stopwords = [
w for w in words if w.lower() in REDIS_DEFAULT_STOPWORDS
]
filtered_words = [
w for w in words if w.lower() not in REDIS_DEFAULT_STOPWORDS
]
if removed_stopwords:
warnings.warn(
f"Stopwords {removed_stopwords} were removed from phrase search '{value}'. "
"By default, Redis does not index stopwords. "
"To include stopwords in your index, create it with STOPWORDS 0.",
UserWarning,
stacklevel=2,
)
# Use filtered phrase, or original if all words were stopwords
phrase = " ".join(filtered_words) if filtered_words else value
search_value = f'"{phrase}"'
else:
search_value = value
return f"{prefix}@{field}:{search_value}"
def _escape_tag_value(self, value: str) -> str:
"""Escape special characters in TAG values."""
result = []
for char in value:
if char in self.TAG_SPECIAL_CHARS:
result.append(f"\\{char}")
else:
result.append(char)
return "".join(result)
def build_tag_condition(
self,
field: str,
operator: str,
value: str | list[str],
) -> str:
"""Build query syntax for TAG field conditions.
Args:
field: Field name.
operator: One of =, !=, IN.
value: Tag value or list of values for IN.
Returns:
RediSearch query syntax like @field:{value} or @field:{v1|v2}.
"""
prefix = "-" if operator == "!=" else ""
if isinstance(value, list):
# IN clause - join with |
escaped_values = [self._escape_tag_value(v) for v in value]
tag_str = "|".join(escaped_values)
else:
tag_str = self._escape_tag_value(value)
return f"{prefix}@{field}:{{{tag_str}}}"
def build_numeric_condition(
self,
field: str,
operator: str,
value: int | float | tuple[int | float, int | float],
) -> str:
"""Build query syntax for NUMERIC field conditions.
Args:
field: Field name.
operator: One of =, !=, <, <=, >, >=, BETWEEN.
value: Numeric value or (min, max) tuple for BETWEEN.
Returns:
RediSearch query syntax like @field:[min max].
"""
prefix = "-" if operator == "!=" else ""
if operator == "BETWEEN":
if isinstance(value, tuple):
min_val, max_val = value
return f"{prefix}@{field}:[{min_val} {max_val}]"
raise ValueError("BETWEEN operator requires a tuple (min, max)")
elif operator == "=":
return f"@{field}:[{value} {value}]"
elif operator == "!=":
return f"-@{field}:[{value} {value}]"
elif operator == ">":
return f"@{field}:[({value} +inf]"
elif operator == ">=":
return f"@{field}:[{value} +inf]"
elif operator == "<":
return f"@{field}:[-inf ({value}]"
elif operator == "<=":
return f"@{field}:[-inf {value}]"
else:
raise ValueError(f"Unknown numeric operator: {operator}")
def build_vector_condition(
self,
field: str,
k: int,
alias: str,
prefilter: str | None = None,
) -> str:
"""Build query syntax for VECTOR KNN search.
Args:
field: Vector field name.
k: Number of nearest neighbors.
alias: Alias for the distance score.
prefilter: Optional pre-filter query string.
Returns:
RediSearch query syntax like =>[KNN k @field $BLOB AS alias].
"""
knn_part = f"=>[KNN {k} @{field} $BLOB AS {alias}]"
if prefilter:
return f"({prefilter}){knn_part}"
return knn_part
def build_geo_filter(
self,
field: str,
lon: float,
lat: float,
radius: float,
unit: str = "km",
) -> str:
"""Build GEOFILTER clause for GEO fields.
Args:
field: GEO field name.
lon: Longitude.
lat: Latitude.
radius: Search radius.
unit: Distance unit (km, m, mi, ft).
Returns:
GEOFILTER clause like "GEOFILTER field lon lat radius unit".
"""
return f"GEOFILTER {field} {lon} {lat} {radius} {unit}"
def build_geo_distance_apply(
self,
field: str,
lon: float,
lat: float,
alias: str,
unit: str = "m",
) -> str:
"""Build APPLY geodistance expression.
Args:
field: GEO field name.
lon: Longitude.
lat: Latitude.
alias: Alias for the distance result.
unit: Distance unit for conversion.
Returns:
APPLY clause like 'APPLY "geodistance(@field, lon, lat)" AS alias'.
"""
base_expr = f"geodistance(@{field}, {lon}, {lat})"
# geodistance returns meters - convert if needed
if unit == "km":
expr = f"({base_expr}/1000)"
elif unit == "mi":
expr = f"({base_expr}/1609.34)"
elif unit == "ft":
expr = f"({base_expr}*3.28084)"
else:
expr = base_expr
return f'APPLY "{expr}" AS {alias}'
def combine_conditions(
self,
conditions: list[str],
operator: str = "AND",
) -> str:
"""Combine multiple condition strings with boolean operator.
Args:
conditions: List of query condition strings.
operator: Boolean operator (AND, OR).
Returns:
Combined query string.
"""
if not conditions:
return "*"
if len(conditions) == 1:
return conditions[0]
if operator == "OR":
# OR uses pipe separator - each condition needs parentheses
parenthesized = [
f"({c})" if not c.startswith("(") else c for c in conditions
]
return "(" + "|".join(parenthesized) + ")"
else:
# AND uses space separator
return " ".join(conditions)
def build_query_string(
self,
text_conditions: list[tuple] | None = None,
numeric_conditions: list[tuple] | None = None,
tag_conditions: list[tuple] | None = None,
field_types: dict[str, str] | None = None,
) -> str:
"""Build complete query string from conditions.
Args:
text_conditions: List of (field, operator, value) tuples.
numeric_conditions: List of (field, operator, value) tuples.
tag_conditions: List of (field, operator, value) tuples.
field_types: Dict mapping field names to types.
Returns:
Complete RediSearch query string.
"""
parts = []
# Build text conditions
if text_conditions:
for field, operator, value in text_conditions:
parts.append(self.build_text_condition(field, operator, value))
# Build numeric conditions
if numeric_conditions:
for field, operator, value in numeric_conditions:
parts.append(self.build_numeric_condition(field, operator, value))
# Build tag conditions
if tag_conditions:
for field, operator, value in tag_conditions:
parts.append(self.build_tag_condition(field, operator, value))
return self.combine_conditions(parts, "AND")