elasticsearch9 9.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. elasticsearch9/__init__.py +98 -0
  2. elasticsearch9/_async/__init__.py +16 -0
  3. elasticsearch9/_async/client/__init__.py +6531 -0
  4. elasticsearch9/_async/client/_base.py +430 -0
  5. elasticsearch9/_async/client/async_search.py +637 -0
  6. elasticsearch9/_async/client/autoscaling.py +252 -0
  7. elasticsearch9/_async/client/cat.py +2995 -0
  8. elasticsearch9/_async/client/ccr.py +1043 -0
  9. elasticsearch9/_async/client/cluster.py +1223 -0
  10. elasticsearch9/_async/client/connector.py +1978 -0
  11. elasticsearch9/_async/client/dangling_indices.py +192 -0
  12. elasticsearch9/_async/client/enrich.py +291 -0
  13. elasticsearch9/_async/client/eql.py +359 -0
  14. elasticsearch9/_async/client/esql.py +490 -0
  15. elasticsearch9/_async/client/features.py +130 -0
  16. elasticsearch9/_async/client/fleet.py +658 -0
  17. elasticsearch9/_async/client/graph.py +113 -0
  18. elasticsearch9/_async/client/ilm.py +668 -0
  19. elasticsearch9/_async/client/indices.py +5582 -0
  20. elasticsearch9/_async/client/inference.py +2247 -0
  21. elasticsearch9/_async/client/ingest.py +766 -0
  22. elasticsearch9/_async/client/license.py +400 -0
  23. elasticsearch9/_async/client/logstash.py +176 -0
  24. elasticsearch9/_async/client/migration.py +160 -0
  25. elasticsearch9/_async/client/ml.py +5835 -0
  26. elasticsearch9/_async/client/monitoring.py +100 -0
  27. elasticsearch9/_async/client/nodes.py +543 -0
  28. elasticsearch9/_async/client/query_rules.py +485 -0
  29. elasticsearch9/_async/client/rollup.py +616 -0
  30. elasticsearch9/_async/client/search_application.py +574 -0
  31. elasticsearch9/_async/client/searchable_snapshots.py +313 -0
  32. elasticsearch9/_async/client/security.py +4688 -0
  33. elasticsearch9/_async/client/shutdown.py +268 -0
  34. elasticsearch9/_async/client/simulate.py +145 -0
  35. elasticsearch9/_async/client/slm.py +559 -0
  36. elasticsearch9/_async/client/snapshot.py +1338 -0
  37. elasticsearch9/_async/client/sql.py +469 -0
  38. elasticsearch9/_async/client/ssl.py +76 -0
  39. elasticsearch9/_async/client/synonyms.py +413 -0
  40. elasticsearch9/_async/client/tasks.py +295 -0
  41. elasticsearch9/_async/client/text_structure.py +664 -0
  42. elasticsearch9/_async/client/transform.py +922 -0
  43. elasticsearch9/_async/client/utils.py +48 -0
  44. elasticsearch9/_async/client/watcher.py +894 -0
  45. elasticsearch9/_async/client/xpack.py +134 -0
  46. elasticsearch9/_async/helpers.py +596 -0
  47. elasticsearch9/_otel.py +110 -0
  48. elasticsearch9/_sync/__init__.py +16 -0
  49. elasticsearch9/_sync/client/__init__.py +6529 -0
  50. elasticsearch9/_sync/client/_base.py +430 -0
  51. elasticsearch9/_sync/client/async_search.py +637 -0
  52. elasticsearch9/_sync/client/autoscaling.py +252 -0
  53. elasticsearch9/_sync/client/cat.py +2995 -0
  54. elasticsearch9/_sync/client/ccr.py +1043 -0
  55. elasticsearch9/_sync/client/cluster.py +1223 -0
  56. elasticsearch9/_sync/client/connector.py +1978 -0
  57. elasticsearch9/_sync/client/dangling_indices.py +192 -0
  58. elasticsearch9/_sync/client/enrich.py +291 -0
  59. elasticsearch9/_sync/client/eql.py +359 -0
  60. elasticsearch9/_sync/client/esql.py +490 -0
  61. elasticsearch9/_sync/client/features.py +130 -0
  62. elasticsearch9/_sync/client/fleet.py +658 -0
  63. elasticsearch9/_sync/client/graph.py +113 -0
  64. elasticsearch9/_sync/client/ilm.py +668 -0
  65. elasticsearch9/_sync/client/indices.py +5582 -0
  66. elasticsearch9/_sync/client/inference.py +2247 -0
  67. elasticsearch9/_sync/client/ingest.py +766 -0
  68. elasticsearch9/_sync/client/license.py +400 -0
  69. elasticsearch9/_sync/client/logstash.py +176 -0
  70. elasticsearch9/_sync/client/migration.py +160 -0
  71. elasticsearch9/_sync/client/ml.py +5835 -0
  72. elasticsearch9/_sync/client/monitoring.py +100 -0
  73. elasticsearch9/_sync/client/nodes.py +543 -0
  74. elasticsearch9/_sync/client/query_rules.py +485 -0
  75. elasticsearch9/_sync/client/rollup.py +616 -0
  76. elasticsearch9/_sync/client/search_application.py +574 -0
  77. elasticsearch9/_sync/client/searchable_snapshots.py +313 -0
  78. elasticsearch9/_sync/client/security.py +4688 -0
  79. elasticsearch9/_sync/client/shutdown.py +268 -0
  80. elasticsearch9/_sync/client/simulate.py +145 -0
  81. elasticsearch9/_sync/client/slm.py +559 -0
  82. elasticsearch9/_sync/client/snapshot.py +1338 -0
  83. elasticsearch9/_sync/client/sql.py +469 -0
  84. elasticsearch9/_sync/client/ssl.py +76 -0
  85. elasticsearch9/_sync/client/synonyms.py +413 -0
  86. elasticsearch9/_sync/client/tasks.py +295 -0
  87. elasticsearch9/_sync/client/text_structure.py +664 -0
  88. elasticsearch9/_sync/client/transform.py +922 -0
  89. elasticsearch9/_sync/client/utils.py +475 -0
  90. elasticsearch9/_sync/client/watcher.py +894 -0
  91. elasticsearch9/_sync/client/xpack.py +134 -0
  92. elasticsearch9/_utils.py +34 -0
  93. elasticsearch9/_version.py +18 -0
  94. elasticsearch9/client.py +126 -0
  95. elasticsearch9/compat.py +79 -0
  96. elasticsearch9/dsl/__init__.py +203 -0
  97. elasticsearch9/dsl/_async/__init__.py +16 -0
  98. elasticsearch9/dsl/_async/document.py +522 -0
  99. elasticsearch9/dsl/_async/faceted_search.py +50 -0
  100. elasticsearch9/dsl/_async/index.py +639 -0
  101. elasticsearch9/dsl/_async/mapping.py +49 -0
  102. elasticsearch9/dsl/_async/search.py +237 -0
  103. elasticsearch9/dsl/_async/update_by_query.py +47 -0
  104. elasticsearch9/dsl/_sync/__init__.py +16 -0
  105. elasticsearch9/dsl/_sync/document.py +514 -0
  106. elasticsearch9/dsl/_sync/faceted_search.py +50 -0
  107. elasticsearch9/dsl/_sync/index.py +597 -0
  108. elasticsearch9/dsl/_sync/mapping.py +49 -0
  109. elasticsearch9/dsl/_sync/search.py +230 -0
  110. elasticsearch9/dsl/_sync/update_by_query.py +45 -0
  111. elasticsearch9/dsl/aggs.py +3734 -0
  112. elasticsearch9/dsl/analysis.py +341 -0
  113. elasticsearch9/dsl/async_connections.py +37 -0
  114. elasticsearch9/dsl/connections.py +142 -0
  115. elasticsearch9/dsl/document.py +20 -0
  116. elasticsearch9/dsl/document_base.py +444 -0
  117. elasticsearch9/dsl/exceptions.py +32 -0
  118. elasticsearch9/dsl/faceted_search.py +28 -0
  119. elasticsearch9/dsl/faceted_search_base.py +489 -0
  120. elasticsearch9/dsl/field.py +4392 -0
  121. elasticsearch9/dsl/function.py +180 -0
  122. elasticsearch9/dsl/index.py +23 -0
  123. elasticsearch9/dsl/index_base.py +178 -0
  124. elasticsearch9/dsl/mapping.py +19 -0
  125. elasticsearch9/dsl/mapping_base.py +219 -0
  126. elasticsearch9/dsl/query.py +2822 -0
  127. elasticsearch9/dsl/response/__init__.py +388 -0
  128. elasticsearch9/dsl/response/aggs.py +100 -0
  129. elasticsearch9/dsl/response/hit.py +53 -0
  130. elasticsearch9/dsl/search.py +20 -0
  131. elasticsearch9/dsl/search_base.py +1053 -0
  132. elasticsearch9/dsl/serializer.py +34 -0
  133. elasticsearch9/dsl/types.py +6453 -0
  134. elasticsearch9/dsl/update_by_query.py +19 -0
  135. elasticsearch9/dsl/update_by_query_base.py +149 -0
  136. elasticsearch9/dsl/utils.py +687 -0
  137. elasticsearch9/dsl/wrappers.py +144 -0
  138. elasticsearch9/exceptions.py +133 -0
  139. elasticsearch9/helpers/__init__.py +41 -0
  140. elasticsearch9/helpers/actions.py +875 -0
  141. elasticsearch9/helpers/errors.py +40 -0
  142. elasticsearch9/helpers/vectorstore/__init__.py +62 -0
  143. elasticsearch9/helpers/vectorstore/_async/__init__.py +16 -0
  144. elasticsearch9/helpers/vectorstore/_async/_utils.py +39 -0
  145. elasticsearch9/helpers/vectorstore/_async/embedding_service.py +89 -0
  146. elasticsearch9/helpers/vectorstore/_async/strategies.py +487 -0
  147. elasticsearch9/helpers/vectorstore/_async/vectorstore.py +421 -0
  148. elasticsearch9/helpers/vectorstore/_sync/__init__.py +16 -0
  149. elasticsearch9/helpers/vectorstore/_sync/_utils.py +39 -0
  150. elasticsearch9/helpers/vectorstore/_sync/embedding_service.py +89 -0
  151. elasticsearch9/helpers/vectorstore/_sync/strategies.py +487 -0
  152. elasticsearch9/helpers/vectorstore/_sync/vectorstore.py +421 -0
  153. elasticsearch9/helpers/vectorstore/_utils.py +116 -0
  154. elasticsearch9/py.typed +0 -0
  155. elasticsearch9/serializer.py +250 -0
  156. elasticsearch9-9.0.0.dist-info/METADATA +175 -0
  157. elasticsearch9-9.0.0.dist-info/RECORD +160 -0
  158. elasticsearch9-9.0.0.dist-info/WHEEL +4 -0
  159. elasticsearch9-9.0.0.dist-info/licenses/LICENSE +176 -0
  160. elasticsearch9-9.0.0.dist-info/licenses/NOTICE +2 -0
@@ -0,0 +1,687 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+
19
+ import collections.abc
20
+ from copy import copy
21
+ from typing import (
22
+ TYPE_CHECKING,
23
+ Any,
24
+ Callable,
25
+ ClassVar,
26
+ Dict,
27
+ Generic,
28
+ Iterable,
29
+ Iterator,
30
+ List,
31
+ Mapping,
32
+ Optional,
33
+ Tuple,
34
+ Type,
35
+ Union,
36
+ cast,
37
+ )
38
+
39
+ from elastic_transport.client_utils import DEFAULT
40
+ from typing_extensions import Self, TypeAlias, TypeVar
41
+
42
+ from .exceptions import UnknownDslObject, ValidationException
43
+
44
+ if TYPE_CHECKING:
45
+ from elastic_transport import ObjectApiResponse
46
+
47
+ from elasticsearch import AsyncElasticsearch, Elasticsearch
48
+
49
+ from .document_base import DocumentOptions
50
+ from .field import Field
51
+ from .index_base import IndexBase
52
+ from .response import Hit # noqa: F401
53
+ from .types import Hit as HitBaseType
54
+
55
+ UsingType: TypeAlias = Union[str, "Elasticsearch"]
56
+ AsyncUsingType: TypeAlias = Union[str, "AsyncElasticsearch"]
57
+ AnyUsingType: TypeAlias = Union[str, "Elasticsearch", "AsyncElasticsearch"]
58
+
59
+ _ValT = TypeVar("_ValT") # used by AttrDict
60
+ _R = TypeVar("_R", default="Hit") # used by Search and Response classes
61
+
62
+ SKIP_VALUES = ("", None)
63
+ EXPAND__TO_DOT = True
64
+
65
+ DOC_META_FIELDS = frozenset(
66
+ (
67
+ "id",
68
+ "routing",
69
+ )
70
+ )
71
+
72
+ META_FIELDS = frozenset(
73
+ (
74
+ # Elasticsearch metadata fields, except 'type'
75
+ "index",
76
+ "using",
77
+ "score",
78
+ "version",
79
+ "seq_no",
80
+ "primary_term",
81
+ )
82
+ ).union(DOC_META_FIELDS)
83
+
84
+
85
+ def _wrap(val: Any, obj_wrapper: Optional[Callable[[Any], Any]] = None) -> Any:
86
+ if isinstance(val, dict):
87
+ return AttrDict(val) if obj_wrapper is None else obj_wrapper(val)
88
+ if isinstance(val, list):
89
+ return AttrList(val)
90
+ return val
91
+
92
+
93
+ def _recursive_to_dict(value: Any) -> Any:
94
+ if hasattr(value, "to_dict"):
95
+ return value.to_dict()
96
+ elif isinstance(value, dict) or isinstance(value, AttrDict):
97
+ return {k: _recursive_to_dict(v) for k, v in value.items()}
98
+ elif isinstance(value, list) or isinstance(value, AttrList):
99
+ return [recursive_to_dict(elem) for elem in value]
100
+ else:
101
+ return value
102
+
103
+
104
+ class AttrList(Generic[_ValT]):
105
+ def __init__(
106
+ self, l: List[_ValT], obj_wrapper: Optional[Callable[[_ValT], Any]] = None
107
+ ):
108
+ # make iterables into lists
109
+ if not isinstance(l, list):
110
+ l = list(l)
111
+ self._l_ = l
112
+ self._obj_wrapper = obj_wrapper
113
+
114
+ def __repr__(self) -> str:
115
+ return repr(self._l_)
116
+
117
+ def __eq__(self, other: Any) -> bool:
118
+ if isinstance(other, AttrList):
119
+ return other._l_ == self._l_
120
+ # make sure we still equal to a dict with the same data
121
+ return bool(other == self._l_)
122
+
123
+ def __ne__(self, other: Any) -> bool:
124
+ return not self == other
125
+
126
+ def __getitem__(self, k: Union[int, slice]) -> Any:
127
+ l = self._l_[k]
128
+ if isinstance(k, slice):
129
+ return AttrList[_ValT](l, obj_wrapper=self._obj_wrapper) # type: ignore[arg-type]
130
+ return _wrap(l, self._obj_wrapper)
131
+
132
+ def __setitem__(self, k: int, value: _ValT) -> None:
133
+ self._l_[k] = value
134
+
135
+ def __iter__(self) -> Iterator[Any]:
136
+ return map(lambda i: _wrap(i, self._obj_wrapper), self._l_)
137
+
138
+ def __len__(self) -> int:
139
+ return len(self._l_)
140
+
141
+ def __nonzero__(self) -> bool:
142
+ return bool(self._l_)
143
+
144
+ __bool__ = __nonzero__
145
+
146
+ def __getattr__(self, name: str) -> Any:
147
+ return getattr(self._l_, name)
148
+
149
+ def __getstate__(self) -> Tuple[List[_ValT], Optional[Callable[[_ValT], Any]]]:
150
+ return self._l_, self._obj_wrapper
151
+
152
+ def __setstate__(
153
+ self, state: Tuple[List[_ValT], Optional[Callable[[_ValT], Any]]]
154
+ ) -> None:
155
+ self._l_, self._obj_wrapper = state
156
+
157
+ def to_list(self) -> List[_ValT]:
158
+ return self._l_
159
+
160
+
161
+ class AttrDict(Generic[_ValT]):
162
+ """
163
+ Helper class to provide attribute like access (read and write) to
164
+ dictionaries. Used to provide a convenient way to access both results and
165
+ nested dsl dicts.
166
+ """
167
+
168
+ _d_: Dict[str, _ValT]
169
+ RESERVED: Dict[str, str] = {"from_": "from"}
170
+
171
+ def __init__(self, d: Dict[str, _ValT]):
172
+ # assign the inner dict manually to prevent __setattr__ from firing
173
+ super().__setattr__("_d_", d)
174
+
175
+ def __contains__(self, key: object) -> bool:
176
+ return key in self._d_
177
+
178
+ def __nonzero__(self) -> bool:
179
+ return bool(self._d_)
180
+
181
+ __bool__ = __nonzero__
182
+
183
+ def __dir__(self) -> List[str]:
184
+ # introspection for auto-complete in IPython etc
185
+ return list(self._d_.keys())
186
+
187
+ def __eq__(self, other: Any) -> bool:
188
+ if isinstance(other, AttrDict):
189
+ return other._d_ == self._d_
190
+ # make sure we still equal to a dict with the same data
191
+ return bool(other == self._d_)
192
+
193
+ def __ne__(self, other: Any) -> bool:
194
+ return not self == other
195
+
196
+ def __repr__(self) -> str:
197
+ r = repr(self._d_)
198
+ if len(r) > 60:
199
+ r = r[:60] + "...}"
200
+ return r
201
+
202
+ def __getstate__(self) -> Tuple[Dict[str, _ValT]]:
203
+ return (self._d_,)
204
+
205
+ def __setstate__(self, state: Tuple[Dict[str, _ValT]]) -> None:
206
+ super().__setattr__("_d_", state[0])
207
+
208
+ def __getattr__(self, attr_name: str) -> Any:
209
+ try:
210
+ return self.__getitem__(attr_name)
211
+ except KeyError:
212
+ raise AttributeError(
213
+ f"{self.__class__.__name__!r} object has no attribute {attr_name!r}"
214
+ )
215
+
216
+ def __delattr__(self, attr_name: str) -> None:
217
+ try:
218
+ del self._d_[self.RESERVED.get(attr_name, attr_name)]
219
+ except KeyError:
220
+ raise AttributeError(
221
+ f"{self.__class__.__name__!r} object has no attribute {attr_name!r}"
222
+ )
223
+
224
+ def __getitem__(self, key: str) -> Any:
225
+ return _wrap(self._d_[self.RESERVED.get(key, key)])
226
+
227
+ def __setitem__(self, key: str, value: _ValT) -> None:
228
+ self._d_[self.RESERVED.get(key, key)] = value
229
+
230
+ def __delitem__(self, key: str) -> None:
231
+ del self._d_[self.RESERVED.get(key, key)]
232
+
233
+ def __setattr__(self, name: str, value: _ValT) -> None:
234
+ # the __orig__class__ attribute has to be treated as an exception, as
235
+ # is it added to an object when it is instantiated with type arguments
236
+ if (
237
+ name in self._d_ or not hasattr(self.__class__, name)
238
+ ) and name != "__orig_class__":
239
+ self._d_[self.RESERVED.get(name, name)] = value
240
+ else:
241
+ # there is an attribute on the class (could be property, ..) - don't add it as field
242
+ super().__setattr__(name, value)
243
+
244
+ def __iter__(self) -> Iterator[str]:
245
+ return iter(self._d_)
246
+
247
+ def to_dict(self, recursive: bool = False) -> Dict[str, _ValT]:
248
+ return cast(
249
+ Dict[str, _ValT], _recursive_to_dict(self._d_) if recursive else self._d_
250
+ )
251
+
252
+ def keys(self) -> Iterable[str]:
253
+ return self._d_.keys()
254
+
255
+ def items(self) -> Iterable[Tuple[str, _ValT]]:
256
+ return self._d_.items()
257
+
258
+
259
+ class DslMeta(type):
260
+ """
261
+ Base Metaclass for DslBase subclasses that builds a registry of all classes
262
+ for given DslBase subclass (== all the query types for the Query subclass
263
+ of DslBase).
264
+
265
+ It then uses the information from that registry (as well as `name` and
266
+ `shortcut` attributes from the base class) to construct any subclass based
267
+ on it's name.
268
+
269
+ For typical use see `QueryMeta` and `Query` in `elasticsearch.dsl.query`.
270
+ """
271
+
272
+ name: str
273
+ _classes: Dict[str, type]
274
+ _type_name: str
275
+ _types: ClassVar[Dict[str, Type["DslBase"]]] = {}
276
+
277
+ def __init__(cls, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any]):
278
+ super().__init__(name, bases, attrs)
279
+ # skip for DslBase
280
+ if not hasattr(cls, "_type_shortcut"):
281
+ return
282
+ if not cls.name:
283
+ # abstract base class, register it's shortcut
284
+ cls._types[cls._type_name] = cls._type_shortcut
285
+ # and create a registry for subclasses
286
+ if not hasattr(cls, "_classes"):
287
+ cls._classes = {}
288
+ elif cls.name not in cls._classes:
289
+ # normal class, register it
290
+ cls._classes[cls.name] = cls
291
+
292
+ @classmethod
293
+ def get_dsl_type(cls, name: str) -> Type["DslBase"]:
294
+ try:
295
+ return cls._types[name]
296
+ except KeyError:
297
+ raise UnknownDslObject(f"DSL type {name} does not exist.")
298
+
299
+
300
+ class DslBase(metaclass=DslMeta):
301
+ """
302
+ Base class for all DSL objects - queries, filters, aggregations etc. Wraps
303
+ a dictionary representing the object's json.
304
+
305
+ Provides several feature:
306
+ - attribute access to the wrapped dictionary (.field instead of ['field'])
307
+ - _clone method returning a copy of self
308
+ - to_dict method to serialize into dict (to be sent via elasticsearch-py)
309
+ - basic logical operators (&, | and ~) using a Bool(Filter|Query) TODO:
310
+ move into a class specific for Query/Filter
311
+ - respects the definition of the class and (de)serializes it's
312
+ attributes based on the `_param_defs` definition (for example turning
313
+ all values in the `must` attribute into Query objects)
314
+ """
315
+
316
+ _param_defs: ClassVar[Dict[str, Dict[str, Union[str, bool]]]] = {}
317
+
318
+ @classmethod
319
+ def get_dsl_class(
320
+ cls: Type[Self], name: str, default: Optional[str] = None
321
+ ) -> Type[Self]:
322
+ try:
323
+ return cls._classes[name]
324
+ except KeyError:
325
+ if default is not None:
326
+ return cls._classes[default]
327
+ raise UnknownDslObject(
328
+ f"DSL class `{name}` does not exist in {cls._type_name}."
329
+ )
330
+
331
+ def __init__(self, _expand__to_dot: Optional[bool] = None, **params: Any) -> None:
332
+ if _expand__to_dot is None:
333
+ _expand__to_dot = EXPAND__TO_DOT
334
+ self._params: Dict[str, Any] = {}
335
+ for pname, pvalue in params.items():
336
+ if pvalue == DEFAULT:
337
+ continue
338
+ # expand "__" to dots
339
+ if "__" in pname and _expand__to_dot:
340
+ pname = pname.replace("__", ".")
341
+ # convert instrumented fields to string
342
+ if type(pvalue).__name__ == "InstrumentedField":
343
+ pvalue = str(pvalue)
344
+ self._setattr(pname, pvalue)
345
+
346
+ def _repr_params(self) -> str:
347
+ """Produce a repr of all our parameters to be used in __repr__."""
348
+ return ", ".join(
349
+ f"{n.replace('.', '__')}={v!r}"
350
+ for (n, v) in sorted(self._params.items())
351
+ # make sure we don't include empty typed params
352
+ if "type" not in self._param_defs.get(n, {}) or v
353
+ )
354
+
355
+ def __repr__(self) -> str:
356
+ return f"{self.__class__.__name__}({self._repr_params()})"
357
+
358
+ def __eq__(self, other: Any) -> bool:
359
+ return isinstance(other, self.__class__) and other.to_dict() == self.to_dict()
360
+
361
+ def __ne__(self, other: Any) -> bool:
362
+ return not self == other
363
+
364
+ def __setattr__(self, name: str, value: Any) -> None:
365
+ if name.startswith("_"):
366
+ return super().__setattr__(name, value)
367
+ return self._setattr(name, value)
368
+
369
+ def _setattr(self, name: str, value: Any) -> None:
370
+ # if this attribute has special type assigned to it...
371
+ name = AttrDict.RESERVED.get(name, name)
372
+ if name in self._param_defs:
373
+ pinfo = self._param_defs[name]
374
+
375
+ if "type" in pinfo:
376
+ # get the shortcut used to construct this type (query.Q, aggs.A, etc)
377
+ shortcut = self.__class__.get_dsl_type(str(pinfo["type"]))
378
+
379
+ # list of dict(name -> DslBase)
380
+ if pinfo.get("multi") and pinfo.get("hash"):
381
+ if not isinstance(value, (tuple, list)):
382
+ value = (value,)
383
+ value = list(
384
+ {k: shortcut(v) for (k, v) in obj.items()} for obj in value
385
+ )
386
+ elif pinfo.get("multi"):
387
+ if not isinstance(value, (tuple, list)):
388
+ value = (value,)
389
+ value = list(map(shortcut, value))
390
+
391
+ # dict(name -> DslBase), make sure we pickup all the objs
392
+ elif pinfo.get("hash"):
393
+ value = {k: shortcut(v) for (k, v) in value.items()}
394
+
395
+ # single value object, just convert
396
+ else:
397
+ value = shortcut(value)
398
+ self._params[name] = value
399
+
400
+ def __getattr__(self, name: str) -> Any:
401
+ if name.startswith("_"):
402
+ raise AttributeError(
403
+ f"{self.__class__.__name__!r} object has no attribute {name!r}"
404
+ )
405
+
406
+ value = None
407
+ try:
408
+ value = self._params[name]
409
+ except KeyError:
410
+ # compound types should never throw AttributeError and return empty
411
+ # container instead
412
+ if name in self._param_defs:
413
+ pinfo = self._param_defs[name]
414
+ if pinfo.get("multi"):
415
+ value = self._params.setdefault(name, [])
416
+ elif pinfo.get("hash"):
417
+ value = self._params.setdefault(name, {})
418
+ if value is None:
419
+ raise AttributeError(
420
+ f"{self.__class__.__name__!r} object has no attribute {name!r}"
421
+ )
422
+
423
+ # wrap nested dicts in AttrDict for convenient access
424
+ if isinstance(value, dict):
425
+ return AttrDict(value)
426
+ return value
427
+
428
+ def to_dict(self) -> Dict[str, Any]:
429
+ """
430
+ Serialize the DSL object to plain dict
431
+ """
432
+ d = {}
433
+ for pname, value in self._params.items():
434
+ pinfo = self._param_defs.get(pname)
435
+
436
+ # typed param
437
+ if pinfo and "type" in pinfo:
438
+ # don't serialize empty lists and dicts for typed fields
439
+ if value in ({}, []):
440
+ continue
441
+
442
+ # list of dict(name -> DslBase)
443
+ if pinfo.get("multi") and pinfo.get("hash"):
444
+ value = list(
445
+ {k: v.to_dict() for k, v in obj.items()} for obj in value
446
+ )
447
+
448
+ # multi-values are serialized as list of dicts
449
+ elif pinfo.get("multi"):
450
+ value = list(map(lambda x: x.to_dict(), value))
451
+
452
+ # squash all the hash values into one dict
453
+ elif pinfo.get("hash"):
454
+ value = {k: v.to_dict() for k, v in value.items()}
455
+
456
+ # serialize single values
457
+ else:
458
+ value = value.to_dict()
459
+
460
+ # serialize anything with to_dict method
461
+ elif hasattr(value, "to_dict"):
462
+ value = value.to_dict()
463
+
464
+ d[pname] = value
465
+ return {self.name: d}
466
+
467
+ def _clone(self) -> Self:
468
+ c = self.__class__()
469
+ for attr in self._params:
470
+ c._params[attr] = copy(self._params[attr])
471
+ return c
472
+
473
+
474
+ if TYPE_CHECKING:
475
+ HitMetaBase = HitBaseType
476
+ else:
477
+ HitMetaBase = AttrDict[Any]
478
+
479
+
480
+ class HitMeta(HitMetaBase):
481
+ inner_hits: Mapping[str, Any]
482
+
483
+ def __init__(
484
+ self,
485
+ document: Dict[str, Any],
486
+ exclude: Tuple[str, ...] = ("_source", "_fields"),
487
+ ):
488
+ d = {
489
+ k[1:] if k.startswith("_") else k: v
490
+ for (k, v) in document.items()
491
+ if k not in exclude
492
+ }
493
+ if "type" in d:
494
+ # make sure we are consistent everywhere in python
495
+ d["doc_type"] = d.pop("type")
496
+ super().__init__(d)
497
+
498
+
499
+ class ObjectBase(AttrDict[Any]):
500
+ _doc_type: "DocumentOptions"
501
+ _index: "IndexBase"
502
+ meta: HitMeta
503
+
504
+ def __init__(self, meta: Optional[Dict[str, Any]] = None, **kwargs: Any):
505
+ meta = meta or {}
506
+ for k in list(kwargs):
507
+ if k.startswith("_") and k[1:] in META_FIELDS:
508
+ meta[k] = kwargs.pop(k)
509
+
510
+ super(AttrDict, self).__setattr__("meta", HitMeta(meta))
511
+
512
+ # process field defaults
513
+ if hasattr(self, "_defaults"):
514
+ for name in self._defaults:
515
+ if name not in kwargs:
516
+ value = self._defaults[name]
517
+ if callable(value):
518
+ value = value()
519
+ kwargs[name] = value
520
+
521
+ super().__init__(kwargs)
522
+
523
+ @classmethod
524
+ def __list_fields(cls) -> Iterator[Tuple[str, "Field", bool]]:
525
+ """
526
+ Get all the fields defined for our class, if we have an Index, try
527
+ looking at the index mappings as well, mark the fields from Index as
528
+ optional.
529
+ """
530
+ for name in cls._doc_type.mapping:
531
+ field = cls._doc_type.mapping[name]
532
+ yield name, field, False
533
+
534
+ if hasattr(cls.__class__, "_index"):
535
+ if not cls._index._mapping:
536
+ return
537
+ for name in cls._index._mapping:
538
+ # don't return fields that are in _doc_type
539
+ if name in cls._doc_type.mapping:
540
+ continue
541
+ field = cls._index._mapping[name]
542
+ yield name, field, True
543
+
544
+ @classmethod
545
+ def __get_field(cls, name: str) -> Optional["Field"]:
546
+ try:
547
+ return cls._doc_type.mapping[name]
548
+ except KeyError:
549
+ # fallback to fields on the Index
550
+ if hasattr(cls, "_index") and cls._index._mapping:
551
+ try:
552
+ return cls._index._mapping[name]
553
+ except KeyError:
554
+ pass
555
+ return None
556
+
557
+ @classmethod
558
+ def from_es(cls, hit: Union[Dict[str, Any], "ObjectApiResponse[Any]"]) -> Self:
559
+ meta = hit.copy()
560
+ data = meta.pop("_source", {})
561
+ doc = cls(meta=meta)
562
+ doc._from_dict(data)
563
+ return doc
564
+
565
+ def _from_dict(self, data: Dict[str, Any]) -> None:
566
+ for k, v in data.items():
567
+ f = self.__get_field(k)
568
+ if f and f._coerce:
569
+ v = f.deserialize(v)
570
+ setattr(self, k, v)
571
+
572
+ def __getstate__(self) -> Tuple[Dict[str, Any], Dict[str, Any]]: # type: ignore[override]
573
+ return self.to_dict(), self.meta._d_
574
+
575
+ def __setstate__(self, state: Tuple[Dict[str, Any], Dict[str, Any]]) -> None: # type: ignore[override]
576
+ data, meta = state
577
+ super(AttrDict, self).__setattr__("_d_", {})
578
+ super(AttrDict, self).__setattr__("meta", HitMeta(meta))
579
+ self._from_dict(data)
580
+
581
+ def __getattr__(self, name: str) -> Any:
582
+ try:
583
+ return super().__getattr__(name)
584
+ except AttributeError:
585
+ f = self.__get_field(name)
586
+ if f is not None and hasattr(f, "empty"):
587
+ value = f.empty()
588
+ if value not in SKIP_VALUES:
589
+ setattr(self, name, value)
590
+ value = getattr(self, name)
591
+ return value
592
+ raise
593
+
594
+ def __setattr__(self, name: str, value: Any) -> None:
595
+ if name in self.__class__._doc_type.mapping:
596
+ self._d_[name] = value
597
+ else:
598
+ super().__setattr__(name, value)
599
+
600
+ def to_dict(self, skip_empty: bool = True) -> Dict[str, Any]:
601
+ out = {}
602
+ for k, v in self._d_.items():
603
+ # if this is a mapped field,
604
+ f = self.__get_field(k)
605
+ if f and f._coerce:
606
+ v = f.serialize(v)
607
+
608
+ # if someone assigned AttrList, unwrap it
609
+ if isinstance(v, AttrList):
610
+ v = v._l_
611
+
612
+ if skip_empty:
613
+ # don't serialize empty values
614
+ # careful not to include numeric zeros
615
+ if v in ([], {}, None):
616
+ continue
617
+
618
+ out[k] = v
619
+ return out
620
+
621
+ def clean_fields(self, validate: bool = True) -> None:
622
+ errors: Dict[str, List[ValidationException]] = {}
623
+ for name, field, optional in self.__list_fields():
624
+ data = self._d_.get(name, None)
625
+ if data is None and optional:
626
+ continue
627
+ try:
628
+ # save the cleaned value
629
+ data = field.clean(data)
630
+ except ValidationException as e:
631
+ errors.setdefault(name, []).append(e)
632
+
633
+ if name in self._d_ or data not in ([], {}, None):
634
+ self._d_[name] = cast(Any, data)
635
+
636
+ if validate and errors:
637
+ raise ValidationException(errors)
638
+
639
+ def clean(self) -> None:
640
+ pass
641
+
642
+ def full_clean(self) -> None:
643
+ self.clean_fields(validate=False)
644
+ self.clean()
645
+ self.clean_fields(validate=True)
646
+
647
+
648
+ def merge(
649
+ data: Union[Dict[str, Any], AttrDict[Any]],
650
+ new_data: Union[Dict[str, Any], AttrDict[Any]],
651
+ raise_on_conflict: bool = False,
652
+ ) -> None:
653
+ if not (
654
+ isinstance(data, (AttrDict, collections.abc.Mapping))
655
+ and isinstance(new_data, (AttrDict, collections.abc.Mapping))
656
+ ):
657
+ raise ValueError(
658
+ f"You can only merge two dicts! Got {data!r} and {new_data!r} instead."
659
+ )
660
+
661
+ for key, value in new_data.items():
662
+ if (
663
+ key in data
664
+ and isinstance(data[key], (AttrDict, collections.abc.Mapping))
665
+ and isinstance(value, (AttrDict, collections.abc.Mapping))
666
+ ):
667
+ merge(data[key], value, raise_on_conflict) # type: ignore[arg-type]
668
+ elif key in data and data[key] != value and raise_on_conflict:
669
+ raise ValueError(f"Incompatible data for key {key!r}, cannot be merged.")
670
+ else:
671
+ data[key] = value
672
+
673
+
674
+ def recursive_to_dict(data: Any) -> Any:
675
+ """Recursively transform objects that potentially have .to_dict()
676
+ into dictionary literals by traversing AttrList, AttrDict, list,
677
+ tuple, and Mapping types.
678
+ """
679
+ if isinstance(data, AttrList):
680
+ data = list(data._l_)
681
+ elif hasattr(data, "to_dict"):
682
+ data = data.to_dict()
683
+ if isinstance(data, (list, tuple)):
684
+ return type(data)(recursive_to_dict(inner) for inner in data)
685
+ elif isinstance(data, dict):
686
+ return {key: recursive_to_dict(val) for key, val in data.items()}
687
+ return data