-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathmodel.py
2142 lines (1857 loc) · 77.2 KB
/
model.py
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import abc
import dataclasses
import decimal
import json
import logging
import operator
from copy import copy
from enum import Enum
from functools import reduce
from typing import (
AbstractSet,
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
)
from typing import get_args as typing_get_args
from typing import no_type_check
from more_itertools import ichunked
from redis.commands.json.path import Path
from redis.exceptions import ResponseError
from typing_extensions import Protocol, get_args, get_origin
from ulid import ULID
from .. import redis
from .._compat import BaseModel
from .._compat import FieldInfo as PydanticFieldInfo
from .._compat import (
ModelField,
ModelMetaclass,
NoArgAnyCallable,
Representation,
Undefined,
UndefinedType,
validate_model,
validator,
)
from ..checks import has_redis_json, has_redisearch
from ..connections import get_redis_connection
from ..util import ASYNC_MODE
from .encoders import jsonable_encoder
from .render_tree import render_tree
from .token_escaper import TokenEscaper
model_registry = {}
_T = TypeVar("_T")
Model = TypeVar("Model", bound="RedisModel")
log = logging.getLogger(__name__)
escaper = TokenEscaper()
# For basic exact-match field types like an indexed string, we create a TAG
# field in the RediSearch index. TAG is designed for multi-value fields
# separated by a "separator" character. We're using the field for single values
# (multi-value TAGs will be exposed as a separate field type), and we use the
# pipe character (|) as the separator. There is no way to escape this character
# in hash fields or JSON objects, so if someone indexes a value that includes
# the pipe, we'll warn but allow, and then warn again if they try to query for
# values that contain this separator.
SINGLE_VALUE_TAG_FIELD_SEPARATOR = "|"
# This is the default field separator in RediSearch. We need it to determine if
# someone has accidentally passed in the field separator with string value of a
# multi-value field lookup, like a IN or NOT_IN.
DEFAULT_REDISEARCH_FIELD_SEPARATOR = ","
ERRORS_URL = "https://github.com/redis/redis-om-python/blob/main/docs/errors.md"
def get_outer_type(field):
if hasattr(field, "outer_type_"):
return field.outer_type_
elif isinstance(field.annotation, type) or is_supported_container_type(
field.annotation
):
return field.annotation
else:
return field.annotation.__args__[0]
class RedisModelError(Exception):
"""Raised when a problem exists in the definition of a RedisModel."""
class QuerySyntaxError(Exception):
"""Raised when a query is constructed improperly."""
class NotFoundError(Exception):
"""Raised when a query found no results."""
class Operators(Enum):
EQ = 1
NE = 2
LT = 3
LE = 4
GT = 5
GE = 6
OR = 7
AND = 8
NOT = 9
IN = 10
NOT_IN = 11
LIKE = 12
ALL = 13
STARTSWITH = 14
ENDSWITH = 15
CONTAINS = 16
def __str__(self):
return str(self.name)
ExpressionOrModelField = Union[
"Expression", "NegatedExpression", ModelField, PydanticFieldInfo
]
def embedded(cls):
"""
Mark a model as embedded to avoid creating multiple indexes if the model is
only ever used embedded within other models.
"""
setattr(cls.Meta, "embedded", True)
def is_supported_container_type(typ: Optional[type]) -> bool:
# TODO: Wait, why don't we support indexing sets?
if typ == list or typ == tuple:
return True
unwrapped = get_origin(typ)
return unwrapped == list or unwrapped == tuple
def validate_model_fields(model: Type["RedisModel"], field_values: Dict[str, Any]):
for field_name in field_values.keys():
if "__" in field_name:
obj = model
for sub_field in field_name.split("__"):
if not isinstance(obj, ModelMeta) and hasattr(obj, "field"):
obj = getattr(obj, "field").annotation
if not hasattr(obj, sub_field):
raise QuerySyntaxError(
f"The update path {field_name} contains a field that does not "
f"exist on {model.__name__}. The field is: {sub_field}"
)
obj = getattr(obj, sub_field)
return
if field_name not in model.__fields__: # type: ignore
raise QuerySyntaxError(
f"The field {field_name} does not exist on the model {model.__name__}"
)
def decode_redis_value(
obj: Union[List[bytes], Dict[bytes, bytes], bytes], encoding: str
) -> Union[List[str], Dict[str, str], str]:
"""Decode a binary-encoded Redis hash into the specified encoding."""
if isinstance(obj, list):
return [v.decode(encoding) for v in obj]
if isinstance(obj, dict):
return {
key.decode(encoding): value.decode(encoding) for key, value in obj.items()
}
elif isinstance(obj, bytes):
return obj.decode(encoding)
# TODO: replace with `str.removeprefix()` when only Python 3.9+ is supported
def remove_prefix(value: str, prefix: str) -> str:
"""Remove a prefix from a string."""
if value.startswith(prefix):
value = value[len(prefix) :] # noqa: E203
return value
class PipelineError(Exception):
"""A Redis pipeline error."""
def verify_pipeline_response(
response: List[Union[bytes, str]], expected_responses: int = 0
):
# TODO: More generic pipeline verification here (what else is possible?),
# plus hash and JSON-specific verifications in separate functions.
actual_responses = len(response)
if actual_responses != expected_responses:
raise PipelineError(
f"We expected {expected_responses}, but the Redis "
f"pipeline returned {actual_responses} responses."
)
@dataclasses.dataclass
class NegatedExpression:
"""A negated Expression object.
For now, this is a separate dataclass from Expression that acts as a facade
around an Expression, indicating to model code (specifically, code
responsible for querying) to negate the logic in the wrapped Expression. A
better design is probably possible, maybe at least an ExpressionProtocol?
"""
expression: "Expression"
def __invert__(self):
return self.expression
def __and__(self, other):
return Expression(
left=self, op=Operators.AND, right=other, parents=self.expression.parents
)
def __or__(self, other):
return Expression(
left=self, op=Operators.OR, right=other, parents=self.expression.parents
)
@property
def left(self):
return self.expression.left
@property
def right(self):
return self.expression.right
@property
def op(self):
return self.expression.op
@property
def name(self):
if self.expression.op is Operators.EQ:
return f"NOT {self.expression.name}"
else:
return f"{self.expression.name} NOT"
@property
def tree(self):
return render_tree(self)
@dataclasses.dataclass
class Expression:
op: Operators
left: Optional[ExpressionOrModelField]
right: Optional[ExpressionOrModelField]
parents: List[Tuple[str, "RedisModel"]]
def __invert__(self):
return NegatedExpression(self)
def __and__(self, other: ExpressionOrModelField):
return Expression(
left=self, op=Operators.AND, right=other, parents=self.parents
)
def __or__(self, other: ExpressionOrModelField):
return Expression(left=self, op=Operators.OR, right=other, parents=self.parents)
@property
def name(self):
return str(self.op)
@property
def tree(self):
return render_tree(self)
@dataclasses.dataclass
class KNNExpression:
k: int
vector_field: ModelField
reference_vector: bytes
def __str__(self):
return f"KNN $K @{self.vector_field.name} $knn_ref_vector"
@property
def query_params(self) -> Dict[str, Union[str, bytes]]:
return {"K": str(self.k), "knn_ref_vector": self.reference_vector}
@property
def score_field(self) -> str:
return f"__{self.vector_field.name}_score"
ExpressionOrNegated = Union[Expression, NegatedExpression]
class ExpressionProxy:
def __init__(self, field: ModelField, parents: List[Tuple[str, "RedisModel"]]):
self.field = field
self.parents = parents
def __eq__(self, other: Any) -> Expression: # type: ignore[override]
return Expression(
left=self.field, op=Operators.EQ, right=other, parents=self.parents
)
def __ne__(self, other: Any) -> Expression: # type: ignore[override]
return Expression(
left=self.field, op=Operators.NE, right=other, parents=self.parents
)
def __lt__(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.LT, right=other, parents=self.parents
)
def __le__(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.LE, right=other, parents=self.parents
)
def __gt__(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.GT, right=other, parents=self.parents
)
def __ge__(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.GE, right=other, parents=self.parents
)
def __mod__(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.LIKE, right=other, parents=self.parents
)
def __lshift__(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.IN, right=other, parents=self.parents
)
def __rshift__(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.NOT_IN, right=other, parents=self.parents
)
def startswith(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.STARTSWITH, right=other, parents=self.parents
)
def endswith(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.ENDSWITH, right=other, parents=self.parents
)
def contains(self, other: Any) -> Expression:
return Expression(
left=self.field, op=Operators.CONTAINS, right=other, parents=self.parents
)
def __getattr__(self, item):
if item.startswith("__"):
raise AttributeError("cannot invoke __getattr__ with reserved field")
outer_type = outer_type_or_annotation(self.field)
if is_supported_container_type(outer_type):
embedded_cls = get_args(outer_type)
if not embedded_cls:
raise QuerySyntaxError(
"In order to query on a list field, you must define "
"the contents of the list with a type annotation, like: "
f"orders: List[Order]. Docs: {ERRORS_URL}#E1"
)
embedded_cls = embedded_cls[0]
attr = getattr(embedded_cls, item)
else:
attr = getattr(outer_type, item)
if isinstance(attr, self.__class__):
new_parent = (self.field.alias, outer_type)
if new_parent not in attr.parents:
attr.parents.append(new_parent)
new_parents = list(set(self.parents) - set(attr.parents))
if new_parents:
attr.parents = new_parents + attr.parents
return attr
class QueryNotSupportedError(Exception):
"""The attempted query is not supported."""
class RediSearchFieldTypes(Enum):
TEXT = "TEXT"
TAG = "TAG"
NUMERIC = "NUMERIC"
GEO = "GEO"
# TODO: How to handle Geo fields?
NUMERIC_TYPES = (float, int, decimal.Decimal)
DEFAULT_PAGE_SIZE = 1000
class FindQuery:
def __init__(
self,
expressions: Sequence[ExpressionOrNegated],
model: Type["RedisModel"],
knn: Optional[KNNExpression] = None,
offset: int = 0,
limit: Optional[int] = None,
page_size: int = DEFAULT_PAGE_SIZE,
sort_fields: Optional[List[str]] = None,
nocontent: bool = False,
):
if not has_redisearch(model.db()):
raise RedisModelError(
"Your Redis instance does not have either the RediSearch module "
"or RedisJSON module installed. Querying requires that your Redis "
"instance has one of these modules installed."
)
self.expressions = expressions
self.model = model
self.knn = knn
self.offset = offset
self.limit = limit or (self.knn.k if self.knn else DEFAULT_PAGE_SIZE)
self.page_size = page_size
self.nocontent = nocontent
if sort_fields:
self.sort_fields = self.validate_sort_fields(sort_fields)
elif self.knn:
self.sort_fields = [self.knn.score_field]
else:
self.sort_fields = []
self._expression = None
self._query: Optional[str] = None
self._pagination: List[str] = []
self._model_cache: List[RedisModel] = []
def dict(self) -> Dict[str, Any]:
return dict(
model=self.model,
offset=self.offset,
page_size=self.page_size,
limit=self.limit,
expressions=copy(self.expressions),
sort_fields=copy(self.sort_fields),
nocontent=self.nocontent,
)
def copy(self, **kwargs):
original = self.dict()
original.update(**kwargs)
return FindQuery(**original)
@property
def pagination(self):
if self._pagination:
return self._pagination
self._pagination = self.resolve_redisearch_pagination()
return self._pagination
@property
def expression(self):
if self._expression:
return self._expression
if self.expressions:
self._expression = reduce(operator.and_, self.expressions)
else:
self._expression = Expression(
left=None, right=None, op=Operators.ALL, parents=[]
)
return self._expression
@property
def query(self):
"""
Resolve and return the RediSearch query for this FindQuery.
NOTE: We cache the resolved query string after generating it. This should be OK
because all mutations of FindQuery through public APIs return a new FindQuery instance.
"""
if self._query:
return self._query
self._query = self.resolve_redisearch_query(self.expression)
if self.knn:
self._query = (
self._query
if self._query.startswith("(") or self._query == "*"
else f"({self._query})"
) + f"=>[{self.knn}]"
return self._query
@property
def query_params(self):
params: List[Union[str, bytes]] = []
if self.knn:
params += [attr for kv in self.knn.query_params.items() for attr in kv]
return params
def validate_sort_fields(self, sort_fields: List[str]):
for sort_field in sort_fields:
field_name = sort_field.lstrip("-")
if self.knn and field_name == self.knn.score_field:
continue
if field_name not in self.model.__fields__: # type: ignore
raise QueryNotSupportedError(
f"You tried sort by {field_name}, but that field "
f"does not exist on the model {self.model}"
)
field_proxy = getattr(self.model, field_name)
if isinstance(field_proxy.field, FieldInfo) or isinstance(
field_proxy.field, PydanticFieldInfo
):
field_info = field_proxy.field
else:
field_info = field_proxy.field.field_info
if not getattr(field_info, "sortable", False):
raise QueryNotSupportedError(
f"You tried sort by {field_name}, but {self.model} does "
f"not define that field as sortable. Docs: {ERRORS_URL}#E2"
)
return sort_fields
@staticmethod
def resolve_field_type(
field: Union[ModelField, PydanticFieldInfo], op: Operators
) -> RediSearchFieldTypes:
field_info: Union[FieldInfo, ModelField, PydanticFieldInfo]
if not hasattr(field, "field_info"):
field_info = field
else:
field_info = field.field_info
if getattr(field_info, "primary_key", None) is True:
return RediSearchFieldTypes.TAG
elif op is Operators.LIKE:
fts = getattr(field_info, "full_text_search", None)
if fts is not True: # Could be PydanticUndefined
raise QuerySyntaxError(
f"You tried to do a full-text search on the field '{field.alias}', "
f"but the field is not indexed for full-text search. Use the "
f"full_text_search=True option. Docs: {ERRORS_URL}#E3"
)
return RediSearchFieldTypes.TEXT
field_type = outer_type_or_annotation(field)
if not isinstance(field_type, type):
field_type = field_type.__origin__
# TODO: GEO fields
container_type = get_origin(field_type)
if is_supported_container_type(container_type):
# NOTE: A list of strings, like:
#
# tarot_cards: List[str] = field(index=True)
#
# becomes a TAG field, which means that users can run equality and
# membership queries on values.
#
# Meanwhile, a list of RedisModels, like:
#
# friends: List[Friend] = field(index=True)
#
# is not itself directly indexed, but instead, we index any fields
# within the model inside the list marked as `index=True`.
return RediSearchFieldTypes.TAG
elif container_type is not None:
raise QuerySyntaxError(
"Only lists and tuples are supported for multi-value fields. "
f"Docs: {ERRORS_URL}#E4"
)
elif any(issubclass(field_type, t) for t in NUMERIC_TYPES):
# Index numeric Python types as NUMERIC fields, so we can support
# range queries.
return RediSearchFieldTypes.NUMERIC
else:
# TAG fields are the default field type and support equality and
# membership queries, though membership (and the multi-value nature
# of the field) are hidden from users unless they explicitly index
# multiple values, with either a list or tuple,
# e.g.,
# favorite_foods: List[str] = field(index=True)
return RediSearchFieldTypes.TAG
@staticmethod
def expand_tag_value(value):
if isinstance(value, str):
return escaper.escape(value)
if isinstance(value, bytes):
# TODO: We don't decode bytes objects passed as input. Should we?
# TODO: TAG indexes fail on JSON arrays of numbers -- only strings
# are allowed -- what happens if we save an array of bytes?
return value
try:
return "|".join([escaper.escape(str(v)) for v in value])
except TypeError:
log.debug(
"Escaping single non-iterable value used for an IN or "
"NOT_IN query: %s",
value,
)
return escaper.escape(str(value))
@classmethod
def resolve_value(
cls,
field_name: str,
field_type: RediSearchFieldTypes,
field_info: PydanticFieldInfo,
op: Operators,
value: Any,
parents: List[Tuple[str, "RedisModel"]],
) -> str:
if parents:
prefix = "_".join([p[0] for p in parents])
field_name = f"{prefix}_{field_name}"
result = ""
if field_type is RediSearchFieldTypes.TEXT:
result = f"@{field_name}_fts:"
if op is Operators.EQ:
result += f'"{value}"'
elif op is Operators.NE:
result = f'-({result}"{value}")'
elif op is Operators.LIKE:
result += value
else:
raise QueryNotSupportedError(
"Only equals (=), not-equals (!=), and like() "
"comparisons are supported for TEXT fields. "
f"Docs: {ERRORS_URL}#E5"
)
elif field_type is RediSearchFieldTypes.NUMERIC:
if op is Operators.EQ:
result += f"@{field_name}:[{value} {value}]"
elif op is Operators.NE:
result += f"-(@{field_name}:[{value} {value}])"
elif op is Operators.GT:
result += f"@{field_name}:[({value} +inf]"
elif op is Operators.LT:
result += f"@{field_name}:[-inf ({value}]"
elif op is Operators.GE:
result += f"@{field_name}:[{value} +inf]"
elif op is Operators.LE:
result += f"@{field_name}:[-inf {value}]"
# TODO: How will we know the difference between a multi-value use of a TAG
# field and our hidden use of TAG for exact-match queries?
elif field_type is RediSearchFieldTypes.TAG:
if op is Operators.EQ:
separator_char = getattr(
field_info, "separator", SINGLE_VALUE_TAG_FIELD_SEPARATOR
)
if value == separator_char:
# The value is ONLY the TAG field separator character --
# this is not going to work.
log.warning(
"Your query against the field %s is for a single character, %s, "
"that is used internally by redis-om-python. We must ignore "
"this portion of the query. Please review your query to find "
"an alternative query that uses a string containing more than "
"just the character %s.",
field_name,
separator_char,
separator_char,
)
return ""
if isinstance(value, int):
# This if will hit only if the field is a primary key of type int
result = f"@{field_name}:[{value} {value}]"
elif separator_char in value:
# The value contains the TAG field separator. We can work
# around this by breaking apart the values and unioning them
# with multiple field:{} queries.
values: filter = filter(None, value.split(separator_char))
for value in values:
value = escaper.escape(value)
result += "@{field_name}:{{{value}}}".format(
field_name=field_name, value=value
)
else:
value = escaper.escape(value)
result += "@{field_name}:{{{value}}}".format(
field_name=field_name, value=value
)
elif op is Operators.NE:
value = escaper.escape(value)
result += "-(@{field_name}:{{{value}}})".format(
field_name=field_name, value=value
)
elif op is Operators.IN:
expanded_value = cls.expand_tag_value(value)
result += "(@{field_name}:{{{expanded_value}}})".format(
field_name=field_name, expanded_value=expanded_value
)
elif op is Operators.NOT_IN:
# TODO: Implement NOT_IN, test this...
expanded_value = cls.expand_tag_value(value)
result += "-(@{field_name}:{{{expanded_value}}})".format(
field_name=field_name, expanded_value=expanded_value
)
elif op is Operators.STARTSWITH:
expanded_value = cls.expand_tag_value(value)
result += "(@{field_name}:{{{expanded_value}*}})".format(
field_name=field_name, expanded_value=expanded_value
)
elif op is Operators.ENDSWITH:
expanded_value = cls.expand_tag_value(value)
result += "(@{field_name}:{{*{expanded_value}}})".format(
field_name=field_name, expanded_value=expanded_value
)
elif op is Operators.CONTAINS:
expanded_value = cls.expand_tag_value(value)
result += "(@{field_name}:{{*{expanded_value}*}})".format(
field_name=field_name, expanded_value=expanded_value
)
return result
def resolve_redisearch_pagination(self):
"""Resolve pagination options for a query."""
return ["LIMIT", self.offset, self.limit]
def resolve_redisearch_sort_fields(self):
"""Resolve sort options for a query."""
if not self.sort_fields:
return
fields = []
for f in self.sort_fields:
direction = "desc" if f.startswith("-") else "asc"
fields.extend([f.lstrip("-"), direction])
if self.sort_fields:
return ["SORTBY", *fields]
@classmethod
def resolve_redisearch_query(cls, expression: ExpressionOrNegated) -> str:
"""
Resolve an arbitrarily deep expression into a single RediSearch query string.
This method is complex. Note the following:
1. This method makes a recursive call to itself when it finds that
either the left or right operand contains another expression.
2. An expression might be in a "negated" form, which means that the user
gave us an expression like ~(Member.age == 30), or in other words,
"Members whose age is NOT 30." Thus, a negated expression is one in
which the meaning of an expression is inverted. If we find a negated
expression, we need to add the appropriate "NOT" syntax but can
otherwise use the resolved RediSearch query for the expression as-is.
3. The final resolution of an expression should be a left operand that's
a ModelField, an operator, and a right operand that's NOT a ModelField.
With an IN or NOT_IN operator, the right operand can be a sequence
type, but otherwise, sequence types are converted to strings.
TODO: When the operator is not IN or NOT_IN, detect a sequence type (other
than strings, which are allowed) and raise an exception.
"""
field_type = None
field_name = None
field_info = None
encompassing_expression_is_negated = False
result = ""
if isinstance(expression, NegatedExpression):
encompassing_expression_is_negated = True
expression = expression.expression
if expression.op is Operators.ALL:
if encompassing_expression_is_negated:
# TODO: Is there a use case for this, perhaps for dynamic
# scoring purposes with full-text search?
raise QueryNotSupportedError(
"You cannot negate a query for all results."
)
return "*"
if isinstance(expression.left, Expression) or isinstance(
expression.left, NegatedExpression
):
result += f"({cls.resolve_redisearch_query(expression.left)})"
elif isinstance(expression.left, ModelField):
field_type = cls.resolve_field_type(expression.left, expression.op)
field_name = expression.left.name
field_info = expression.left.field_info
if not field_info or not getattr(field_info, "index", None):
raise QueryNotSupportedError(
f"You tried to query by a field ({field_name}) "
f"that isn't indexed. Docs: {ERRORS_URL}#E6"
)
elif isinstance(expression.left, FieldInfo):
field_type = cls.resolve_field_type(expression.left, expression.op)
field_name = expression.left.alias
field_info = expression.left
if not field_info or not getattr(field_info, "index", None):
raise QueryNotSupportedError(
f"You tried to query by a field ({field_name}) "
f"that isn't indexed. Docs: {ERRORS_URL}#E6"
)
else:
raise QueryNotSupportedError(
"A query expression should start with either a field "
f"or an expression enclosed in parentheses. Docs: {ERRORS_URL}#E7"
)
right = expression.right
if isinstance(right, Expression) or isinstance(right, NegatedExpression):
if expression.op == Operators.AND:
result += " "
elif expression.op == Operators.OR:
result += "| "
else:
raise QueryNotSupportedError(
"You can only combine two query expressions with"
f"AND (&) or OR (|). Docs: {ERRORS_URL}#E8"
)
if isinstance(right, NegatedExpression):
result += "-"
# We're handling the RediSearch operator in this call ("-"), so resolve the
# inner expression instead of the NegatedExpression.
right = right.expression
result += f"({cls.resolve_redisearch_query(right)})"
else:
if not field_name:
raise QuerySyntaxError("Could not resolve field name. See docs: TODO")
elif not field_type:
raise QuerySyntaxError("Could not resolve field type. See docs: TODO")
elif not field_info:
raise QuerySyntaxError("Could not resolve field info. See docs: TODO")
elif isinstance(right, ModelField):
raise QueryNotSupportedError(
"Comparing fields is not supported. See docs: TODO"
)
else:
result += cls.resolve_value(
field_name,
field_type,
field_info,
expression.op,
right,
expression.parents,
)
if encompassing_expression_is_negated:
result = f"-({result})"
return result
async def execute(self, exhaust_results=True, return_raw_result=False):
args: List[Union[str, bytes]] = [
"FT.SEARCH",
self.model.Meta.index_name,
self.query,
*self.pagination,
]
if self.sort_fields:
args += self.resolve_redisearch_sort_fields()
if self.query_params:
args += ["PARAMS", str(len(self.query_params))] + self.query_params
if self.knn:
# Ensure DIALECT is at least 2
if "DIALECT" not in args:
args += ["DIALECT", "2"]
else:
i_dialect = args.index("DIALECT") + 1
if int(args[i_dialect]) < 2:
args[i_dialect] = "2"
if self.nocontent:
args.append("NOCONTENT")
# Reset the cache if we're executing from offset 0.
if self.offset == 0:
self._model_cache.clear()
# If the offset is greater than 0, we're paginating through a result set,
# so append the new results to results already in the cache.
raw_result = await self.model.db().execute_command(*args)
if return_raw_result:
return raw_result
count = raw_result[0]
results = self.model.from_redis(raw_result)
self._model_cache += results
if not exhaust_results:
return self._model_cache
# The query returned all results, so we have no more work to do.
if count <= len(results):
return self._model_cache
# Transparently (to the user) make subsequent requests to paginate
# through the results and finally return them all.
query = self
while True:
# Make a query for each pass of the loop, with a new offset equal to the
# current offset plus `page_size`, until we stop getting results back.
query = query.copy(offset=query.offset + query.page_size)
_results = await query.execute(exhaust_results=False)
if not _results:
break
self._model_cache += _results
return self._model_cache
async def first(self):
query = self.copy(offset=0, limit=1, sort_fields=self.sort_fields)
results = await query.execute(exhaust_results=False)
if not results:
raise NotFoundError()
return results[0]
async def count(self):
query = self.copy(offset=0, limit=0, nocontent=True)
result = await query.execute(exhaust_results=True, return_raw_result=True)
return result[0]
async def all(self, batch_size=DEFAULT_PAGE_SIZE):
if batch_size != self.page_size:
query = self.copy(page_size=batch_size, limit=batch_size)
return await query.execute()
return await self.execute()
async def page(self, offset=0, limit=10):
return await self.copy(offset=offset, limit=limit).execute()
def sort_by(self, *fields: str):
if not fields:
return self
return self.copy(sort_fields=list(fields))
async def update(self, use_transaction=True, **field_values):
"""
Update models that match this query to the given field-value pairs.
Keys and values given as keyword arguments are interpreted as fields
on the target model and the values as the values to which to set the
given fields.
"""
validate_model_fields(self.model, field_values)
pipeline = await self.model.db().pipeline() if use_transaction else None
# TODO: async for here?
for model in await self.all():
for field, value in field_values.items():
setattr(model, field, value)
# TODO: In the non-transaction case, can we do more to detect
# failure responses from Redis?
await model.save(pipeline=pipeline)
if pipeline:
# TODO: Response type?
# TODO: Better error detection for transactions.
await pipeline.execute()
async def delete(self):
"""Delete all matching records in this query."""
# TODO: Better response type, error detection
try:
return await self.model.db().delete(*[m.key() for m in await self.all()])
except ResponseError:
return 0
async def __aiter__(self):
if self._model_cache:
for m in self._model_cache:
yield m
else:
for m in await self.execute():
yield m
def __getitem__(self, item: int):
"""
Given this code:
Model.find()[1000]
We should return only the 1000th result.
1. If the result is loaded in the query cache for this query,
we can return it directly from the cache.
2. If the query cache does not have enough elements to return
that result, then we should clone the current query and
give it a new offset and limit: offset=n, limit=1.