forked from elastic/elasticsearch-dsl-py
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathquery.py
2799 lines (2446 loc) · 101 KB
/
query.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
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you 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.
import collections.abc
from copy import deepcopy
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
List,
Literal,
Mapping,
MutableMapping,
Optional,
Protocol,
Sequence,
TypeVar,
Union,
cast,
overload,
)
from elastic_transport.client_utils import DEFAULT
# 'SF' looks unused but the test suite assumes it's available
# from this module so others are liable to do so as well.
from .function import SF # noqa: F401
from .function import ScoreFunction
from .utils import DslBase
if TYPE_CHECKING:
from elastic_transport.client_utils import DefaultType
from elasticsearch_dsl import types, wrappers
from .document_base import InstrumentedField
_T = TypeVar("_T")
_M = TypeVar("_M", bound=Mapping[str, Any])
class QProxiedProtocol(Protocol[_T]):
_proxied: _T
@overload
def Q(name_or_query: MutableMapping[str, _M]) -> "Query": ...
@overload
def Q(name_or_query: "Query") -> "Query": ...
@overload
def Q(name_or_query: QProxiedProtocol[_T]) -> _T: ...
@overload
def Q(name_or_query: str = "match_all", **params: Any) -> "Query": ...
def Q(
name_or_query: Union[
str,
"Query",
QProxiedProtocol[_T],
MutableMapping[str, _M],
] = "match_all",
**params: Any,
) -> Union["Query", _T]:
# {"match": {"title": "python"}}
if isinstance(name_or_query, collections.abc.MutableMapping):
if params:
raise ValueError("Q() cannot accept parameters when passing in a dict.")
if len(name_or_query) != 1:
raise ValueError(
'Q() can only accept dict with a single query ({"match": {...}}). '
"Instead it got (%r)" % name_or_query
)
name, q_params = deepcopy(name_or_query).popitem()
return Query.get_dsl_class(name)(_expand__to_dot=False, **q_params)
# MatchAll()
if isinstance(name_or_query, Query):
if params:
raise ValueError(
"Q() cannot accept parameters when passing in a Query object."
)
return name_or_query
# s.query = Q('filtered', query=s.query)
if hasattr(name_or_query, "_proxied"):
return cast(QProxiedProtocol[_T], name_or_query)._proxied
# "match", title="python"
return Query.get_dsl_class(name_or_query)(**params)
class Query(DslBase):
_type_name = "query"
_type_shortcut = staticmethod(Q)
name: ClassVar[Optional[str]] = None
# Add type annotations for methods not defined in every subclass
__ror__: ClassVar[Callable[["Query", "Query"], "Query"]]
__radd__: ClassVar[Callable[["Query", "Query"], "Query"]]
__rand__: ClassVar[Callable[["Query", "Query"], "Query"]]
def __add__(self, other: "Query") -> "Query":
# make sure we give queries that know how to combine themselves
# preference
if hasattr(other, "__radd__"):
return other.__radd__(self)
return Bool(must=[self, other])
def __invert__(self) -> "Query":
return Bool(must_not=[self])
def __or__(self, other: "Query") -> "Query":
# make sure we give queries that know how to combine themselves
# preference
if hasattr(other, "__ror__"):
return other.__ror__(self)
return Bool(should=[self, other])
def __and__(self, other: "Query") -> "Query":
# make sure we give queries that know how to combine themselves
# preference
if hasattr(other, "__rand__"):
return other.__rand__(self)
return Bool(must=[self, other])
class Bool(Query):
"""
matches documents matching boolean combinations of other queries.
:arg filter: The clause (query) must appear in matching documents.
However, unlike `must`, the score of the query will be ignored.
:arg minimum_should_match: Specifies the number or percentage of
`should` clauses returned documents must match.
:arg must: The clause (query) must appear in matching documents and
will contribute to the score.
:arg must_not: The clause (query) must not appear in the matching
documents. Because scoring is ignored, a score of `0` is returned
for all documents.
:arg should: The clause (query) should appear in the matching
document.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "bool"
_param_defs = {
"filter": {"type": "query", "multi": True},
"must": {"type": "query", "multi": True},
"must_not": {"type": "query", "multi": True},
"should": {"type": "query", "multi": True},
}
def __init__(
self,
*,
filter: Union[Query, Sequence[Query], "DefaultType"] = DEFAULT,
minimum_should_match: Union[int, str, "DefaultType"] = DEFAULT,
must: Union[Query, Sequence[Query], "DefaultType"] = DEFAULT,
must_not: Union[Query, Sequence[Query], "DefaultType"] = DEFAULT,
should: Union[Query, Sequence[Query], "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
super().__init__(
filter=filter,
minimum_should_match=minimum_should_match,
must=must,
must_not=must_not,
should=should,
boost=boost,
_name=_name,
**kwargs,
)
def __add__(self, other: Query) -> "Bool":
q = self._clone()
if isinstance(other, Bool):
q.must += other.must
q.should += other.should
q.must_not += other.must_not
q.filter += other.filter
else:
q.must.append(other)
return q
__radd__ = __add__
def __or__(self, other: Query) -> Query:
for q in (self, other):
if isinstance(q, Bool) and not any(
(q.must, q.must_not, q.filter, getattr(q, "minimum_should_match", None))
):
other = self if q is other else other
q = q._clone()
if isinstance(other, Bool) and not any(
(
other.must,
other.must_not,
other.filter,
getattr(other, "minimum_should_match", None),
)
):
q.should.extend(other.should)
else:
q.should.append(other)
return q
return Bool(should=[self, other])
__ror__ = __or__
@property
def _min_should_match(self) -> int:
return getattr(
self,
"minimum_should_match",
0 if not self.should or (self.must or self.filter) else 1,
)
def __invert__(self) -> Query:
# Because an empty Bool query is treated like
# MatchAll the inverse should be MatchNone
if not any(chain(self.must, self.filter, self.should, self.must_not)):
return MatchNone()
negations: List[Query] = []
for q in chain(self.must, self.filter):
negations.append(~q)
for q in self.must_not:
negations.append(q)
if self.should and self._min_should_match:
negations.append(Bool(must_not=self.should[:]))
if len(negations) == 1:
return negations[0]
return Bool(should=negations)
def __and__(self, other: Query) -> Query:
q = self._clone()
if isinstance(other, Bool):
q.must += other.must
q.must_not += other.must_not
q.filter += other.filter
q.should = []
# reset minimum_should_match as it will get calculated below
if "minimum_should_match" in q._params:
del q._params["minimum_should_match"]
for qx in (self, other):
min_should_match = qx._min_should_match
# TODO: percentages or negative numbers will fail here
# for now we report an error
if not isinstance(min_should_match, int) or min_should_match < 0:
raise ValueError(
"Can only combine queries with positive integer values for minimum_should_match"
)
# all subqueries are required
if len(qx.should) <= min_should_match:
q.must.extend(qx.should)
# not all of them are required, use it and remember min_should_match
elif not q.should:
q.minimum_should_match = min_should_match
q.should = qx.should
# all queries are optional, just extend should
elif q._min_should_match == 0 and min_should_match == 0:
q.should.extend(qx.should)
# not all are required, add a should list to the must with proper min_should_match
else:
q.must.append(
Bool(should=qx.should, minimum_should_match=min_should_match)
)
else:
if not (q.must or q.filter) and q.should:
q._params.setdefault("minimum_should_match", 1)
q.must.append(other)
return q
__rand__ = __and__
class Boosting(Query):
"""
Returns documents matching a `positive` query while reducing the
relevance score of documents that also match a `negative` query.
:arg negative_boost: (required) Floating point number between 0 and
1.0 used to decrease the relevance scores of documents matching
the `negative` query.
:arg negative: (required) Query used to decrease the relevance score
of matching documents.
:arg positive: (required) Any returned documents must match this
query.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "boosting"
_param_defs = {
"negative": {"type": "query"},
"positive": {"type": "query"},
}
def __init__(
self,
*,
negative_boost: Union[float, "DefaultType"] = DEFAULT,
negative: Union[Query, "DefaultType"] = DEFAULT,
positive: Union[Query, "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
super().__init__(
negative_boost=negative_boost,
negative=negative,
positive=positive,
boost=boost,
_name=_name,
**kwargs,
)
class Common(Query):
"""
:arg _field: The field to use in this query.
:arg _value: The query value for the field.
"""
name = "common"
def __init__(
self,
_field: Union[str, "InstrumentedField", "DefaultType"] = DEFAULT,
_value: Union[
"types.CommonTermsQuery", Dict[str, Any], "DefaultType"
] = DEFAULT,
**kwargs: Any,
):
if _field is not DEFAULT:
kwargs[str(_field)] = _value
super().__init__(**kwargs)
class CombinedFields(Query):
"""
The `combined_fields` query supports searching multiple text fields as
if their contents had been indexed into one combined field.
:arg fields: (required) List of fields to search. Field wildcard
patterns are allowed. Only `text` fields are supported, and they
must all have the same search `analyzer`.
:arg query: (required) Text to search for in the provided `fields`.
The `combined_fields` query analyzes the provided text before
performing a search.
:arg auto_generate_synonyms_phrase_query: If true, match phrase
queries are automatically created for multi-term synonyms.
Defaults to `True` if omitted.
:arg operator: Boolean logic used to interpret text in the query
value. Defaults to `or` if omitted.
:arg minimum_should_match: Minimum number of clauses that must match
for a document to be returned.
:arg zero_terms_query: Indicates whether no documents are returned if
the analyzer removes all tokens, such as when using a `stop`
filter. Defaults to `none` if omitted.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "combined_fields"
def __init__(
self,
*,
fields: Union[
Sequence[Union[str, "InstrumentedField"]], "DefaultType"
] = DEFAULT,
query: Union[str, "DefaultType"] = DEFAULT,
auto_generate_synonyms_phrase_query: Union[bool, "DefaultType"] = DEFAULT,
operator: Union[Literal["or", "and"], "DefaultType"] = DEFAULT,
minimum_should_match: Union[int, str, "DefaultType"] = DEFAULT,
zero_terms_query: Union[Literal["none", "all"], "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
super().__init__(
fields=fields,
query=query,
auto_generate_synonyms_phrase_query=auto_generate_synonyms_phrase_query,
operator=operator,
minimum_should_match=minimum_should_match,
zero_terms_query=zero_terms_query,
boost=boost,
_name=_name,
**kwargs,
)
class ConstantScore(Query):
"""
Wraps a filter query and returns every matching document with a
relevance score equal to the `boost` parameter value.
:arg filter: (required) Filter query you wish to run. Any returned
documents must match this query. Filter queries do not calculate
relevance scores. To speed up performance, Elasticsearch
automatically caches frequently used filter queries.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "constant_score"
_param_defs = {
"filter": {"type": "query"},
}
def __init__(
self,
*,
filter: Union[Query, "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
super().__init__(filter=filter, boost=boost, _name=_name, **kwargs)
class DisMax(Query):
"""
Returns documents matching one or more wrapped queries, called query
clauses or clauses. If a returned document matches multiple query
clauses, the `dis_max` query assigns the document the highest
relevance score from any matching clause, plus a tie breaking
increment for any additional matching subqueries.
:arg queries: (required) One or more query clauses. Returned documents
must match one or more of these queries. If a document matches
multiple queries, Elasticsearch uses the highest relevance score.
:arg tie_breaker: Floating point number between 0 and 1.0 used to
increase the relevance scores of documents matching multiple query
clauses.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "dis_max"
_param_defs = {
"queries": {"type": "query", "multi": True},
}
def __init__(
self,
*,
queries: Union[Sequence[Query], "DefaultType"] = DEFAULT,
tie_breaker: Union[float, "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
super().__init__(
queries=queries, tie_breaker=tie_breaker, boost=boost, _name=_name, **kwargs
)
class DistanceFeature(Query):
"""
Boosts the relevance score of documents closer to a provided origin
date or point. For example, you can use this query to give more weight
to documents closer to a certain date or location.
:arg origin: (required) Date or point of origin used to calculate
distances. If the `field` value is a `date` or `date_nanos` field,
the `origin` value must be a date. Date Math, such as `now-1h`, is
supported. If the field value is a `geo_point` field, the `origin`
value must be a geopoint.
:arg pivot: (required) Distance from the `origin` at which relevance
scores receive half of the `boost` value. If the `field` value is
a `date` or `date_nanos` field, the `pivot` value must be a time
unit, such as `1h` or `10d`. If the `field` value is a `geo_point`
field, the `pivot` value must be a distance unit, such as `1km` or
`12m`.
:arg field: (required) Name of the field used to calculate distances.
This field must meet the following criteria: be a `date`,
`date_nanos` or `geo_point` field; have an `index` mapping
parameter value of `true`, which is the default; have an
`doc_values` mapping parameter value of `true`, which is the
default.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "distance_feature"
def __init__(
self,
*,
origin: Any = DEFAULT,
pivot: Any = DEFAULT,
field: Union[str, "InstrumentedField", "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
super().__init__(
origin=origin, pivot=pivot, field=field, boost=boost, _name=_name, **kwargs
)
class Exists(Query):
"""
Returns documents that contain an indexed value for a field.
:arg field: (required) Name of the field you wish to search.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "exists"
def __init__(
self,
*,
field: Union[str, "InstrumentedField", "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
super().__init__(field=field, boost=boost, _name=_name, **kwargs)
class FunctionScore(Query):
"""
The `function_score` enables you to modify the score of documents that
are retrieved by a query.
:arg boost_mode: Defines how he newly computed score is combined with
the score of the query Defaults to `multiply` if omitted.
:arg functions: One or more functions that compute a new score for
each document returned by the query.
:arg max_boost: Restricts the new score to not exceed the provided
limit.
:arg min_score: Excludes documents that do not meet the provided score
threshold.
:arg query: A query that determines the documents for which a new
score is computed.
:arg score_mode: Specifies how the computed scores are combined
Defaults to `multiply` if omitted.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "function_score"
_param_defs = {
"query": {"type": "query"},
"filter": {"type": "query"},
"functions": {"type": "score_function", "multi": True},
}
def __init__(
self,
*,
boost_mode: Union[
Literal["multiply", "replace", "sum", "avg", "max", "min"], "DefaultType"
] = DEFAULT,
functions: Union[
Sequence["types.FunctionScoreContainer"],
Sequence[Dict[str, Any]],
"DefaultType",
] = DEFAULT,
max_boost: Union[float, "DefaultType"] = DEFAULT,
min_score: Union[float, "DefaultType"] = DEFAULT,
query: Union[Query, "DefaultType"] = DEFAULT,
score_mode: Union[
Literal["multiply", "sum", "avg", "first", "max", "min"], "DefaultType"
] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
if functions is DEFAULT:
functions = []
for name in ScoreFunction._classes:
if name in kwargs:
functions.append({name: kwargs.pop(name)}) # type: ignore
super().__init__(
boost_mode=boost_mode,
functions=functions,
max_boost=max_boost,
min_score=min_score,
query=query,
score_mode=score_mode,
boost=boost,
_name=_name,
**kwargs,
)
class Fuzzy(Query):
"""
Returns documents that contain terms similar to the search term, as
measured by a Levenshtein edit distance.
:arg _field: The field to use in this query.
:arg _value: The query value for the field.
"""
name = "fuzzy"
def __init__(
self,
_field: Union[str, "InstrumentedField", "DefaultType"] = DEFAULT,
_value: Union["types.FuzzyQuery", Dict[str, Any], "DefaultType"] = DEFAULT,
**kwargs: Any,
):
if _field is not DEFAULT:
kwargs[str(_field)] = _value
super().__init__(**kwargs)
class GeoBoundingBox(Query):
"""
Matches geo_point and geo_shape values that intersect a bounding box.
:arg _field: The field to use in this query.
:arg _value: The query value for the field.
:arg type:
:arg validation_method: Set to `IGNORE_MALFORMED` to accept geo points
with invalid latitude or longitude. Set to `COERCE` to also try to
infer correct latitude or longitude. Defaults to `'strict'` if
omitted.
:arg ignore_unmapped: Set to `true` to ignore an unmapped field and
not match any documents for this query. Set to `false` to throw an
exception if the field is not mapped.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "geo_bounding_box"
def __init__(
self,
_field: Union[str, "InstrumentedField", "DefaultType"] = DEFAULT,
_value: Union[
"types.CoordsGeoBounds",
"types.TopLeftBottomRightGeoBounds",
"types.TopRightBottomLeftGeoBounds",
"types.WktGeoBounds",
Dict[str, Any],
"DefaultType",
] = DEFAULT,
*,
type: Union[Literal["memory", "indexed"], "DefaultType"] = DEFAULT,
validation_method: Union[
Literal["coerce", "ignore_malformed", "strict"], "DefaultType"
] = DEFAULT,
ignore_unmapped: Union[bool, "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
if _field is not DEFAULT:
kwargs[str(_field)] = _value
super().__init__(
type=type,
validation_method=validation_method,
ignore_unmapped=ignore_unmapped,
boost=boost,
_name=_name,
**kwargs,
)
class GeoDistance(Query):
"""
Matches `geo_point` and `geo_shape` values within a given distance of
a geopoint.
:arg _field: The field to use in this query.
:arg _value: The query value for the field.
:arg distance: (required) The radius of the circle centred on the
specified location. Points which fall into this circle are
considered to be matches.
:arg distance_type: How to compute the distance. Set to `plane` for a
faster calculation that's inaccurate on long distances and close
to the poles. Defaults to `'arc'` if omitted.
:arg validation_method: Set to `IGNORE_MALFORMED` to accept geo points
with invalid latitude or longitude. Set to `COERCE` to also try to
infer correct latitude or longitude. Defaults to `'strict'` if
omitted.
:arg ignore_unmapped: Set to `true` to ignore an unmapped field and
not match any documents for this query. Set to `false` to throw an
exception if the field is not mapped.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "geo_distance"
def __init__(
self,
_field: Union[str, "InstrumentedField", "DefaultType"] = DEFAULT,
_value: Union[
"types.LatLonGeoLocation",
"types.GeoHashLocation",
Sequence[float],
str,
Dict[str, Any],
"DefaultType",
] = DEFAULT,
*,
distance: Union[str, "DefaultType"] = DEFAULT,
distance_type: Union[Literal["arc", "plane"], "DefaultType"] = DEFAULT,
validation_method: Union[
Literal["coerce", "ignore_malformed", "strict"], "DefaultType"
] = DEFAULT,
ignore_unmapped: Union[bool, "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
if _field is not DEFAULT:
kwargs[str(_field)] = _value
super().__init__(
distance=distance,
distance_type=distance_type,
validation_method=validation_method,
ignore_unmapped=ignore_unmapped,
boost=boost,
_name=_name,
**kwargs,
)
class GeoPolygon(Query):
"""
:arg _field: The field to use in this query.
:arg _value: The query value for the field.
:arg validation_method: Defaults to `'strict'` if omitted.
:arg ignore_unmapped:
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "geo_polygon"
def __init__(
self,
_field: Union[str, "InstrumentedField", "DefaultType"] = DEFAULT,
_value: Union[
"types.GeoPolygonPoints", Dict[str, Any], "DefaultType"
] = DEFAULT,
*,
validation_method: Union[
Literal["coerce", "ignore_malformed", "strict"], "DefaultType"
] = DEFAULT,
ignore_unmapped: Union[bool, "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
if _field is not DEFAULT:
kwargs[str(_field)] = _value
super().__init__(
validation_method=validation_method,
ignore_unmapped=ignore_unmapped,
boost=boost,
_name=_name,
**kwargs,
)
class GeoShape(Query):
"""
Filter documents indexed using either the `geo_shape` or the
`geo_point` type.
:arg _field: The field to use in this query.
:arg _value: The query value for the field.
:arg ignore_unmapped: Set to `true` to ignore an unmapped field and
not match any documents for this query. Set to `false` to throw an
exception if the field is not mapped.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "geo_shape"
def __init__(
self,
_field: Union[str, "InstrumentedField", "DefaultType"] = DEFAULT,
_value: Union[
"types.GeoShapeFieldQuery", Dict[str, Any], "DefaultType"
] = DEFAULT,
*,
ignore_unmapped: Union[bool, "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
if _field is not DEFAULT:
kwargs[str(_field)] = _value
super().__init__(
ignore_unmapped=ignore_unmapped, boost=boost, _name=_name, **kwargs
)
class HasChild(Query):
"""
Returns parent documents whose joined child documents match a provided
query.
:arg query: (required) Query you wish to run on child documents of the
`type` field. If a child document matches the search, the query
returns the parent document.
:arg type: (required) Name of the child relationship mapped for the
`join` field.
:arg ignore_unmapped: Indicates whether to ignore an unmapped `type`
and not return any documents instead of an error.
:arg inner_hits: If defined, each search hit will contain inner hits.
:arg max_children: Maximum number of child documents that match the
query allowed for a returned parent document. If the parent
document exceeds this limit, it is excluded from the search
results.
:arg min_children: Minimum number of child documents that match the
query required to match the query for a returned parent document.
If the parent document does not meet this limit, it is excluded
from the search results.
:arg score_mode: Indicates how scores for matching child documents
affect the root parent document’s relevance score. Defaults to
`'none'` if omitted.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "has_child"
_param_defs = {
"query": {"type": "query"},
}
def __init__(
self,
*,
query: Union[Query, "DefaultType"] = DEFAULT,
type: Union[str, "DefaultType"] = DEFAULT,
ignore_unmapped: Union[bool, "DefaultType"] = DEFAULT,
inner_hits: Union["types.InnerHits", Dict[str, Any], "DefaultType"] = DEFAULT,
max_children: Union[int, "DefaultType"] = DEFAULT,
min_children: Union[int, "DefaultType"] = DEFAULT,
score_mode: Union[
Literal["none", "avg", "sum", "max", "min"], "DefaultType"
] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
super().__init__(
query=query,
type=type,
ignore_unmapped=ignore_unmapped,
inner_hits=inner_hits,
max_children=max_children,
min_children=min_children,
score_mode=score_mode,
boost=boost,
_name=_name,
**kwargs,
)
class HasParent(Query):
"""
Returns child documents whose joined parent document matches a
provided query.
:arg parent_type: (required) Name of the parent relationship mapped
for the `join` field.
:arg query: (required) Query you wish to run on parent documents of
the `parent_type` field. If a parent document matches the search,
the query returns its child documents.
:arg ignore_unmapped: Indicates whether to ignore an unmapped
`parent_type` and not return any documents instead of an error.
You can use this parameter to query multiple indices that may not
contain the `parent_type`.
:arg inner_hits: If defined, each search hit will contain inner hits.
:arg score: Indicates whether the relevance score of a matching parent
document is aggregated into its child documents.
:arg boost: Floating point number used to decrease or increase the
relevance scores of the query. Boost values are relative to the
default value of 1.0. A boost value between 0 and 1.0 decreases
the relevance score. A value greater than 1.0 increases the
relevance score. Defaults to `1` if omitted.
:arg _name:
"""
name = "has_parent"
_param_defs = {
"query": {"type": "query"},
}
def __init__(
self,
*,
parent_type: Union[str, "DefaultType"] = DEFAULT,
query: Union[Query, "DefaultType"] = DEFAULT,
ignore_unmapped: Union[bool, "DefaultType"] = DEFAULT,
inner_hits: Union["types.InnerHits", Dict[str, Any], "DefaultType"] = DEFAULT,
score: Union[bool, "DefaultType"] = DEFAULT,
boost: Union[float, "DefaultType"] = DEFAULT,
_name: Union[str, "DefaultType"] = DEFAULT,
**kwargs: Any,
):
super().__init__(
parent_type=parent_type,
query=query,
ignore_unmapped=ignore_unmapped,
inner_hits=inner_hits,
score=score,
boost=boost,
_name=_name,