-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathpipeline_expressions.py
More file actions
2978 lines (2383 loc) · 105 KB
/
pipeline_expressions.py
File metadata and controls
2978 lines (2383 loc) · 105 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
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
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
.. warning::
**Preview API**: Firestore Pipelines is currently in preview and is
subject to potential breaking changes in future releases.
"""
from __future__ import annotations
import datetime
from abc import ABC, abstractmethod
from enum import Enum
from typing import (
Any,
Generic,
Sequence,
TypeVar,
)
from google.cloud.firestore_v1._helpers import GeoPoint, decode_value, encode_value
from google.cloud.firestore_v1.types.document import Value
from google.cloud.firestore_v1.types.query import StructuredQuery as Query_pb
from google.cloud.firestore_v1.vector import Vector
CONSTANT_TYPE = TypeVar(
"CONSTANT_TYPE",
str,
int,
float,
bool,
datetime.datetime,
bytes,
GeoPoint,
Vector,
None,
)
class TimeUnit(str, Enum):
"""Enumeration of the different time units supported by the Firestore backend."""
MICROSECOND = "microsecond"
MILLISECOND = "millisecond"
SECOND = "second"
MINUTE = "minute"
HOUR = "hour"
DAY = "day"
class TimeGranularity(str, Enum):
"""Enumeration of the different time granularities supported by the Firestore backend."""
# Inherit from TimeUnit
MICROSECOND = TimeUnit.MICROSECOND.value
MILLISECOND = TimeUnit.MILLISECOND.value
SECOND = TimeUnit.SECOND.value
MINUTE = TimeUnit.MINUTE.value
HOUR = TimeUnit.HOUR.value
DAY = TimeUnit.DAY.value
# Additional granularities
WEEK = "week"
WEEK_MONDAY = "week(monday)"
WEEK_TUESDAY = "week(tuesday)"
WEEK_WEDNESDAY = "week(wednesday)"
WEEK_THURSDAY = "week(thursday)"
WEEK_FRIDAY = "week(friday)"
WEEK_SATURDAY = "week(saturday)"
WEEK_SUNDAY = "week(sunday)"
ISOWEEK = "isoweek"
MONTH = "month"
QUARTER = "quarter"
YEAR = "year"
ISOYEAR = "isoyear"
class TimePart(str, Enum):
"""Enumeration of the different time parts supported by the Firestore backend."""
# Inherit from TimeUnit
MICROSECOND = TimeUnit.MICROSECOND.value
MILLISECOND = TimeUnit.MILLISECOND.value
SECOND = TimeUnit.SECOND.value
MINUTE = TimeUnit.MINUTE.value
HOUR = TimeUnit.HOUR.value
DAY = TimeUnit.DAY.value
# Inherit from TimeGranularity
WEEK = TimeGranularity.WEEK.value
WEEK_MONDAY = TimeGranularity.WEEK_MONDAY.value
WEEK_TUESDAY = TimeGranularity.WEEK_TUESDAY.value
WEEK_WEDNESDAY = TimeGranularity.WEEK_WEDNESDAY.value
WEEK_THURSDAY = TimeGranularity.WEEK_THURSDAY.value
WEEK_FRIDAY = TimeGranularity.WEEK_FRIDAY.value
WEEK_SATURDAY = TimeGranularity.WEEK_SATURDAY.value
WEEK_SUNDAY = TimeGranularity.WEEK_SUNDAY.value
ISOWEEK = TimeGranularity.ISOWEEK.value
MONTH = TimeGranularity.MONTH.value
QUARTER = TimeGranularity.QUARTER.value
YEAR = TimeGranularity.YEAR.value
ISOYEAR = TimeGranularity.ISOYEAR.value
# Additional parts
DAY_OF_WEEK = "dayofweek"
DAY_OF_YEAR = "dayofyear"
class Ordering:
"""Represents the direction for sorting results in a pipeline."""
class Direction(Enum):
ASCENDING = "ascending"
DESCENDING = "descending"
def __init__(self, expr, order_dir: Direction | str = Direction.ASCENDING):
"""
Initializes an Ordering instance
Args:
expr (Expression | str): The expression or field path string to sort by.
If a string is provided, it's treated as a field path.
order_dir (Direction | str): The direction to sort in.
Defaults to ascending
"""
self.expr = expr if isinstance(expr, Expression) else Field.of(expr)
self.order_dir = (
Ordering.Direction[order_dir.upper()]
if isinstance(order_dir, str)
else order_dir
)
def __repr__(self):
if self.order_dir is Ordering.Direction.ASCENDING:
order_str = ".ascending()"
else:
order_str = ".descending()"
return f"{self.expr!r}{order_str}"
def _to_pb(self) -> Value:
return Value(
map_value={
"fields": {
"direction": Value(string_value=self.order_dir.value),
"expression": self.expr._to_pb(),
}
}
)
class Type(str, Enum):
"""Enumeration of the different types generated by the Firestore backend."""
NULL = "null"
ARRAY = "array"
BOOLEAN = "boolean"
BYTES = "bytes"
TIMESTAMP = "timestamp"
GEO_POINT = "geo_point"
NUMBER = "number"
INT32 = "int32"
INT64 = "int64"
FLOAT64 = "float64"
DECIMAL128 = "decimal128"
MAP = "map"
REFERENCE = "reference"
STRING = "string"
VECTOR = "vector"
MAX_KEY = "max_key"
MIN_KEY = "min_key"
OBJECT_ID = "object_id"
REGEX = "regex"
REQUEST_TIMESTAMP = "request_timestamp"
class Expression(ABC):
"""Represents an expression that can be evaluated to a value within the
execution of a pipeline.
Expressionessions are the building blocks for creating complex queries and
transformations in Firestore pipelines. They can represent:
- **Field references:** Access values from document fields.
- **Literals:** Represent constant values (strings, numbers, booleans).
- **FunctionExpression calls:** Apply functions to one or more expressions.
- **Aggregations:** Calculate aggregate values (e.g., sum, average) over a set of documents.
The `Expression` class provides a fluent API for building expressions. You can chain
together method calls to create complex expressions.
"""
def __repr__(self):
return f"{self.__class__.__name__}()"
@abstractmethod
def _to_pb(self) -> Value:
raise NotImplementedError
@staticmethod
def _cast_to_expr_or_convert_to_constant(
o: Any, include_vector=False
) -> "Expression":
"""Convert arbitrary object to an Expression."""
if isinstance(o, Expression):
return o
if isinstance(o, Enum):
o = o.value
if isinstance(o, dict):
return Map(o)
if isinstance(o, list):
if include_vector and all([isinstance(i, (float, int)) for i in o]):
return Constant(Vector(o))
else:
return Array(o)
return Constant(o)
class expose_as_static:
"""
Decorator to mark instance methods to be exposed as static methods as well as instance
methods.
When called statically, the first argument is converted to a Field expression if needed.
Example:
>>> Field.of("test").add(5)
>>> FunctionExpression.add("test", 5)
"""
def __init__(self, instance_func):
self.instance_func = instance_func
def static_func(self, first_arg, *other_args, **kwargs):
if not isinstance(first_arg, (Expression, str)):
raise TypeError(
f"'{self.instance_func.__name__}' must be called on an Expression or a string representing a field. got {type(first_arg)}."
)
first_expr = (
Field.of(first_arg)
if not isinstance(first_arg, Expression)
else first_arg
)
return self.instance_func(first_expr, *other_args, **kwargs)
def __get__(self, instance, owner):
if instance is None:
return self.static_func
else:
return self.instance_func.__get__(instance, owner)
@expose_as_static
def add(self, other: Expression | float) -> "Expression":
"""Creates an expression that adds this expression to another expression or constant.
Example:
>>> # Add the value of the 'quantity' field and the 'reserve' field.
>>> Field.of("quantity").add(Field.of("reserve"))
>>> # Add 5 to the value of the 'age' field
>>> Field.of("age").add(5)
Args:
other: The expression or constant value to add to this expression.
Returns:
A new `Expression` representing the addition operation.
"""
return FunctionExpression(
"add", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def subtract(self, other: Expression | float) -> "Expression":
"""Creates an expression that subtracts another expression or constant from this expression.
Example:
>>> # Subtract the 'discount' field from the 'price' field
>>> Field.of("price").subtract(Field.of("discount"))
>>> # Subtract 20 from the value of the 'total' field
>>> Field.of("total").subtract(20)
Args:
other: The expression or constant value to subtract from this expression.
Returns:
A new `Expression` representing the subtraction operation.
"""
return FunctionExpression(
"subtract", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def multiply(self, other: Expression | float) -> "Expression":
"""Creates an expression that multiplies this expression by another expression or constant.
Example:
>>> # Multiply the 'quantity' field by the 'price' field
>>> Field.of("quantity").multiply(Field.of("price"))
>>> # Multiply the 'value' field by 2
>>> Field.of("value").multiply(2)
Args:
other: The expression or constant value to multiply by.
Returns:
A new `Expression` representing the multiplication operation.
"""
return FunctionExpression(
"multiply", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def divide(self, other: Expression | float) -> "Expression":
"""Creates an expression that divides this expression by another expression or constant.
Example:
>>> # Divide the 'total' field by the 'count' field
>>> Field.of("total").divide(Field.of("count"))
>>> # Divide the 'value' field by 10
>>> Field.of("value").divide(10)
Args:
other: The expression or constant value to divide by.
Returns:
A new `Expression` representing the division operation.
"""
return FunctionExpression(
"divide", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def mod(self, other: Expression | float) -> "Expression":
"""Creates an expression that calculates the modulo (remainder) to another expression or constant.
Example:
>>> # Calculate the remainder of dividing the 'value' field by field 'divisor'.
>>> Field.of("value").mod(Field.of("divisor"))
>>> # Calculate the remainder of dividing the 'value' field by 5.
>>> Field.of("value").mod(5)
Args:
other: The divisor expression or constant.
Returns:
A new `Expression` representing the modulo operation.
"""
return FunctionExpression(
"mod", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def abs(self) -> "Expression":
"""Creates an expression that calculates the absolute value of this expression.
Example:
>>> # Get the absolute value of the 'change' field.
>>> Field.of("change").abs()
Returns:
A new `Expression` representing the absolute value.
"""
return FunctionExpression("abs", [self])
@expose_as_static
def ceil(self) -> "Expression":
"""Creates an expression that calculates the ceiling of this expression.
Example:
>>> # Get the ceiling of the 'value' field.
>>> Field.of("value").ceil()
Returns:
A new `Expression` representing the ceiling value.
"""
return FunctionExpression("ceil", [self])
@expose_as_static
def exp(self) -> "Expression":
"""Creates an expression that computes e to the power of this expression.
Example:
>>> # Compute e to the power of the 'value' field
>>> Field.of("value").exp()
Returns:
A new `Expression` representing the exponential value.
"""
return FunctionExpression("exp", [self])
@expose_as_static
def floor(self) -> "Expression":
"""Creates an expression that calculates the floor of this expression.
Example:
>>> # Get the floor of the 'value' field.
>>> Field.of("value").floor()
Returns:
A new `Expression` representing the floor value.
"""
return FunctionExpression("floor", [self])
@expose_as_static
def ln(self) -> "Expression":
"""Creates an expression that calculates the natural logarithm of this expression.
Example:
>>> # Get the natural logarithm of the 'value' field.
>>> Field.of("value").ln()
Returns:
A new `Expression` representing the natural logarithm.
"""
return FunctionExpression("ln", [self])
@expose_as_static
def log(self, base: Expression | float) -> "Expression":
"""Creates an expression that calculates the logarithm of this expression with a given base.
Example:
>>> # Get the logarithm of 'value' with base 2.
>>> Field.of("value").log(2)
>>> # Get the logarithm of 'value' with base from 'base_field'.
>>> Field.of("value").log(Field.of("base_field"))
Args:
base: The base of the logarithm.
Returns:
A new `Expression` representing the logarithm.
"""
return FunctionExpression(
"log", [self, self._cast_to_expr_or_convert_to_constant(base)]
)
@expose_as_static
def log10(self) -> "Expression":
"""Creates an expression that calculates the base 10 logarithm of this expression.
Example:
>>> Field.of("value").log10()
Returns:
A new `Expression` representing the logarithm.
"""
return FunctionExpression("log10", [self])
@expose_as_static
def pow(self, exponent: Expression | float) -> "Expression":
"""Creates an expression that calculates this expression raised to the power of the exponent.
Example:
>>> # Raise 'base_val' to the power of 2.
>>> Field.of("base_val").pow(2)
>>> # Raise 'base_val' to the power of 'exponent_val'.
>>> Field.of("base_val").pow(Field.of("exponent_val"))
Args:
exponent: The exponent.
Returns:
A new `Expression` representing the power operation.
"""
return FunctionExpression(
"pow", [self, self._cast_to_expr_or_convert_to_constant(exponent)]
)
@expose_as_static
def round(self) -> "Expression":
"""Creates an expression that rounds this expression to the nearest integer.
Example:
>>> # Round the 'value' field.
>>> Field.of("value").round()
Returns:
A new `Expression` representing the rounded value.
"""
return FunctionExpression("round", [self])
@expose_as_static
def sqrt(self) -> "Expression":
"""Creates an expression that calculates the square root of this expression.
Example:
>>> # Get the square root of the 'area' field.
>>> Field.of("area").sqrt()
Returns:
A new `Expression` representing the square root.
"""
return FunctionExpression("sqrt", [self])
@expose_as_static
def trunc(self, places: Expression | int | None = None) -> "Expression":
"""Creates an expression that truncates the numeric value. If places is None,
truncates to an integer. Otherwise, truncates the numeric value to the
specified number of decimal places.
Example:
>>> # Truncate the 'value' field to 2 decimal places.
>>> Field.of("value").trunc(PipelineSource.literals(2))
Returns:
A new `Expression` representing the truncated value.
"""
params = (
[self, self._cast_to_expr_or_convert_to_constant(places)]
if places is not None
else [self]
)
return FunctionExpression("trunc", params)
@expose_as_static
def logical_maximum(self, *others: Expression | CONSTANT_TYPE) -> "Expression":
"""Creates an expression that returns the larger value between this expression
and another expression or constant, based on Firestore's value type ordering.
Firestore's value type ordering is described here:
https://cloud.google.com/firestore/docs/concepts/data-types#value_type_ordering
Example:
>>> # Returns the larger value between the 'discount' field and the 'cap' field.
>>> Field.of("discount").logical_maximum(Field.of("cap"))
>>> # Returns the larger value between the 'value' field and some ints
>>> Field.of("value").logical_maximum(10, 20, 30)
Args:
others: The other expression or constant values to compare with.
Returns:
A new `Expression` representing the logical maximum operation.
"""
return FunctionExpression(
"maximum",
[self] + [self._cast_to_expr_or_convert_to_constant(o) for o in others],
infix_name_override="logical_maximum",
)
@expose_as_static
def logical_minimum(self, *others: Expression | CONSTANT_TYPE) -> "Expression":
"""Creates an expression that returns the smaller value between this expression
and another expression or constant, based on Firestore's value type ordering.
Firestore's value type ordering is described here:
https://cloud.google.com/firestore/docs/concepts/data-types#value_type_ordering
Example:
>>> # Returns the smaller value between the 'discount' field and the 'floor' field.
>>> Field.of("discount").logical_minimum(Field.of("floor"))
>>> # Returns the smaller value between the 'value' field and some ints
>>> Field.of("value").logical_minimum(10, 20, 30)
Args:
others: The other expression or constant values to compare with.
Returns:
A new `Expression` representing the logical minimum operation.
"""
return FunctionExpression(
"minimum",
[self] + [self._cast_to_expr_or_convert_to_constant(o) for o in others],
infix_name_override="logical_minimum",
)
@expose_as_static
def equal(self, other: Expression | CONSTANT_TYPE) -> "BooleanExpression":
"""Creates an expression that checks if this expression is equal to another
expression or constant value.
Example:
>>> # Check if the 'age' field is equal to 21
>>> Field.of("age").equal(21)
>>> # Check if the 'city' field is equal to "London"
>>> Field.of("city").equal("London")
Args:
other: The expression or constant value to compare for equality.
Returns:
A new `Expression` representing the equality comparison.
"""
return BooleanExpression(
"equal", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def not_equal(self, other: Expression | CONSTANT_TYPE) -> "BooleanExpression":
"""Creates an expression that checks if this expression is not equal to another
expression or constant value.
Example:
>>> # Check if the 'status' field is not equal to "completed"
>>> Field.of("status").not_equal("completed")
>>> # Check if the 'country' field is not equal to "USA"
>>> Field.of("country").not_equal("USA")
Args:
other: The expression or constant value to compare for inequality.
Returns:
A new `Expression` representing the inequality comparison.
"""
return BooleanExpression(
"not_equal", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def greater_than(self, other: Expression | CONSTANT_TYPE) -> "BooleanExpression":
"""Creates an expression that checks if this expression is greater than another
expression or constant value.
Example:
>>> # Check if the 'age' field is greater than the 'limit' field
>>> Field.of("age").greater_than(Field.of("limit"))
>>> # Check if the 'price' field is greater than 100
>>> Field.of("price").greater_than(100)
Args:
other: The expression or constant value to compare for greater than.
Returns:
A new `Expression` representing the greater than comparison.
"""
return BooleanExpression(
"greater_than", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def greater_than_or_equal(
self, other: Expression | CONSTANT_TYPE
) -> "BooleanExpression":
"""Creates an expression that checks if this expression is greater than or equal
to another expression or constant value.
Example:
>>> # Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1
>>> Field.of("quantity").greater_than_or_equal(Field.of('requirement').add(1))
>>> # Check if the 'score' field is greater than or equal to 80
>>> Field.of("score").greater_than_or_equal(80)
Args:
other: The expression or constant value to compare for greater than or equal to.
Returns:
A new `Expression` representing the greater than or equal to comparison.
"""
return BooleanExpression(
"greater_than_or_equal",
[self, self._cast_to_expr_or_convert_to_constant(other)],
)
@expose_as_static
def less_than(self, other: Expression | CONSTANT_TYPE) -> "BooleanExpression":
"""Creates an expression that checks if this expression is less than another
expression or constant value.
Example:
>>> # Check if the 'age' field is less than 'limit'
>>> Field.of("age").less_than(Field.of('limit'))
>>> # Check if the 'price' field is less than 50
>>> Field.of("price").less_than(50)
Args:
other: The expression or constant value to compare for less than.
Returns:
A new `Expression` representing the less than comparison.
"""
return BooleanExpression(
"less_than", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def less_than_or_equal(
self, other: Expression | CONSTANT_TYPE
) -> "BooleanExpression":
"""Creates an expression that checks if this expression is less than or equal to
another expression or constant value.
Example:
>>> # Check if the 'quantity' field is less than or equal to 20
>>> Field.of("quantity").less_than_or_equal(Constant.of(20))
>>> # Check if the 'score' field is less than or equal to 70
>>> Field.of("score").less_than_or_equal(70)
Args:
other: The expression or constant value to compare for less than or equal to.
Returns:
A new `Expression` representing the less than or equal to comparison.
"""
return BooleanExpression(
"less_than_or_equal",
[self, self._cast_to_expr_or_convert_to_constant(other)],
)
@expose_as_static
def between(
self, lower: Expression | float, upper: Expression | float
) -> "BooleanExpression":
"""Evaluates if the result of this expression is between
the lower bound (inclusive) and upper bound (inclusive).
This is functionally equivalent to performing an `And` operation with
`greater_than_or_equal` and `less_than_or_equal`.
Example:
>>> # Check if the 'age' field is between 18 and 65
>>> Field.of("age").between(18, 65)
Args:
lower: Lower bound (inclusive) of the range.
upper: Upper bound (inclusive) of the range.
Returns:
A new `BooleanExpression` representing the between comparison.
"""
return And(
self.greater_than_or_equal(lower),
self.less_than_or_equal(upper),
)
@expose_as_static
def geo_distance(self, other: Expression | GeoPoint) -> "FunctionExpression":
"""Evaluates to the distance in meters between the location in the specified
field and the query location.
Note: This Expression can only be used within a `Search` stage.
Example:
>>> # Calculate distance between the 'location' field and a target GeoPoint
>>> Field.of("location").geo_distance(target_point)
Args:
other: Compute distance to this GeoPoint expression or constant value.
Returns:
A new `FunctionExpression` representing the distance.
"""
return FunctionExpression(
"geo_distance", [self, self._cast_to_expr_or_convert_to_constant(other)]
)
@expose_as_static
def equal_any(
self, array: Array | Sequence[Expression | CONSTANT_TYPE] | Expression
) -> "BooleanExpression":
"""Creates an expression that checks if this expression is equal to any of the
provided values or expressions.
Example:
>>> # Check if the 'category' field is either "Electronics" or value of field 'primaryType'
>>> Field.of("category").equal_any(["Electronics", Field.of("primaryType")])
Args:
array: The values or expressions to check against.
Returns:
A new `Expression` representing the 'IN' comparison.
"""
return BooleanExpression(
"equal_any",
[
self,
self._cast_to_expr_or_convert_to_constant(array),
],
)
@expose_as_static
def not_equal_any(
self, array: Array | list[Expression | CONSTANT_TYPE] | Expression
) -> "BooleanExpression":
"""Creates an expression that checks if this expression is not equal to any of the
provided values or expressions.
Example:
>>> # Check if the 'status' field is neither "pending" nor "cancelled"
>>> Field.of("status").not_equal_any(["pending", "cancelled"])
Args:
array: The values or expressions to check against.
Returns:
A new `Expression` representing the 'NOT IN' comparison.
"""
return BooleanExpression(
"not_equal_any",
[
self,
self._cast_to_expr_or_convert_to_constant(array),
],
)
@expose_as_static
def array_get(self, offset: Expression | int) -> "FunctionExpression":
"""
Creates an expression that indexes into an array from the beginning or end and returns the
element. A negative offset starts from the end.
Example:
>>> Array([1,2,3]).array_get(0)
Args:
offset: the index of the element to return
Returns:
A new `Expression` representing the `array_get` operation.
"""
return FunctionExpression(
"array_get", [self, self._cast_to_expr_or_convert_to_constant(offset)]
)
@expose_as_static
def array_contains(
self, element: Expression | CONSTANT_TYPE
) -> "BooleanExpression":
"""Creates an expression that checks if an array contains a specific element or value.
Example:
>>> # Check if the 'sizes' array contains the value from the 'selectedSize' field
>>> Field.of("sizes").array_contains(Field.of("selectedSize"))
>>> # Check if the 'colors' array contains "red"
>>> Field.of("colors").array_contains("red")
Args:
element: The element (expression or constant) to search for in the array.
Returns:
A new `Expression` representing the 'array_contains' comparison.
"""
return BooleanExpression(
"array_contains", [self, self._cast_to_expr_or_convert_to_constant(element)]
)
@expose_as_static
def array_contains_all(
self,
elements: Array | list[Expression | CONSTANT_TYPE] | Expression,
) -> "BooleanExpression":
"""Creates an expression that checks if an array contains all the specified elements.
Example:
>>> # Check if the 'tags' array contains both "news" and "sports"
>>> Field.of("tags").array_contains_all(["news", "sports"])
>>> # Check if the 'tags' array contains both of the values from field 'tag1' and "tag2"
>>> Field.of("tags").array_contains_all([Field.of("tag1"), "tag2"])
Args:
elements: The list of elements (expressions or constants) to check for in the array.
Returns:
A new `Expression` representing the 'array_contains_all' comparison.
"""
return BooleanExpression(
"array_contains_all",
[
self,
self._cast_to_expr_or_convert_to_constant(elements),
],
)
@expose_as_static
def array_contains_any(
self,
elements: Array | list[Expression | CONSTANT_TYPE] | Expression,
) -> "BooleanExpression":
"""Creates an expression that checks if an array contains any of the specified elements.
Example:
>>> # Check if the 'categories' array contains either values from field "cate1" or "cate2"
>>> Field.of("categories").array_contains_any([Field.of("cate1"), Field.of("cate2")])
>>> # Check if the 'groups' array contains either the value from the 'userGroup' field
>>> # or the value "guest"
>>> Field.of("groups").array_contains_any([Field.of("userGroup"), "guest"])
Args:
elements: The list of elements (expressions or constants) to check for in the array.
Returns:
A new `Expression` representing the 'array_contains_any' comparison.
"""
return BooleanExpression(
"array_contains_any",
[
self,
self._cast_to_expr_or_convert_to_constant(elements),
],
)
@expose_as_static
def array_length(self) -> "Expression":
"""Creates an expression that calculates the length of an array.
Example:
>>> # Get the number of items in the 'cart' array
>>> Field.of("cart").array_length()
Returns:
A new `Expression` representing the length of the array.
"""
return FunctionExpression("array_length", [self])
@expose_as_static
def array_reverse(self) -> "Expression":
"""Creates an expression that returns the reversed content of an array.
Example:
>>> # Get the 'preferences' array in reversed order.
>>> Field.of("preferences").array_reverse()
Returns:
A new `Expression` representing the reversed array.
"""
return FunctionExpression("array_reverse", [self])
@expose_as_static
def array_concat(
self, *other_arrays: Array | list[Expression | CONSTANT_TYPE] | Expression
) -> "Expression":
"""Creates an expression that concatenates an array expression with another array.
Example:
>>> # Combine the 'tags' array with a new array and an array field
>>> Field.of("tags").array_concat(["newTag1", "newTag2", Field.of("otherTag")])
Args:
array: The list of constants or expressions to concat with.
Returns:
A new `Expression` representing the concatenated array.
"""
return FunctionExpression(
"array_concat",
[self]
+ [self._cast_to_expr_or_convert_to_constant(arr) for arr in other_arrays],
)
@expose_as_static
def concat(self, *others: Expression | CONSTANT_TYPE) -> "Expression":
"""Creates an expression that concatenates expressions together
Args:
*others: The expressions to concatenate.
Returns:
A new `Expression` representing the concatenated value.
"""
return FunctionExpression(
"concat",
[self] + [self._cast_to_expr_or_convert_to_constant(o) for o in others],
)
@expose_as_static
def length(self) -> "Expression":
"""
Creates an expression that calculates the length of the expression if it is a string, array, map, or blob.
Example:
>>> # Get the length of the 'name' field.
>>> Field.of("name").length()
Returns:
A new `Expression` representing the length of the expression.
"""
return FunctionExpression("length", [self])
@expose_as_static
def is_absent(self) -> "BooleanExpression":
"""Creates an expression that returns true if a value is absent. Otherwise, returns false even if
the value is null.
Example:
>>> # Check if the 'email' field is absent.
>>> Field.of("email").is_absent()
Returns:
A new `BooleanExpressionession` representing the isAbsent operation.
"""
return BooleanExpression("is_absent", [self])
@expose_as_static
def if_absent(self, default_value: Expression | CONSTANT_TYPE) -> "Expression":
"""Creates an expression that returns a default value if an expression evaluates to an absent value.
Example:
>>> # Return the value of the 'email' field, or "N/A" if it's absent.
>>> Field.of("email").if_absent("N/A")
Args: