-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
__init__.py
5340 lines (5154 loc) · 245 KB
/
__init__.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 logging
import typing as t
import warnings
from elastic_transport import (
BaseNode,
BinaryApiResponse,
HeadApiResponse,
NodeConfig,
NodePool,
NodeSelector,
ObjectApiResponse,
Serializer,
Transport,
)
from elastic_transport.client_utils import DEFAULT, DefaultType
from ...exceptions import ApiError, TransportError
from ...serializer import DEFAULT_SERIALIZERS
from ._base import (
BaseClient,
create_sniff_callback,
default_sniff_callback,
resolve_auth_headers,
)
from .async_search import AsyncSearchClient
from .autoscaling import AutoscalingClient
from .cat import CatClient
from .ccr import CcrClient
from .cluster import ClusterClient
from .connector import ConnectorClient
from .dangling_indices import DanglingIndicesClient
from .enrich import EnrichClient
from .eql import EqlClient
from .esql import EsqlClient
from .features import FeaturesClient
from .fleet import FleetClient
from .graph import GraphClient
from .ilm import IlmClient
from .indices import IndicesClient
from .inference import InferenceClient
from .ingest import IngestClient
from .license import LicenseClient
from .logstash import LogstashClient
from .migration import MigrationClient
from .ml import MlClient
from .monitoring import MonitoringClient
from .nodes import NodesClient
from .query_rules import QueryRulesClient
from .rollup import RollupClient
from .search_application import SearchApplicationClient
from .searchable_snapshots import SearchableSnapshotsClient
from .security import SecurityClient
from .shutdown import ShutdownClient
from .slm import SlmClient
from .snapshot import SnapshotClient
from .sql import SqlClient
from .ssl import SslClient
from .synonyms import SynonymsClient
from .tasks import TasksClient
from .text_structure import TextStructureClient
from .transform import TransformClient
from .utils import (
_TYPE_HOSTS,
CLIENT_META_SERVICE,
SKIP_IN_PATH,
Stability,
_quote,
_rewrite_parameters,
_stability_warning,
client_node_configs,
is_requests_http_auth,
is_requests_node_class,
)
from .watcher import WatcherClient
from .xpack import XPackClient
logger = logging.getLogger("elasticsearch")
SelfType = t.TypeVar("SelfType", bound="Elasticsearch")
class Elasticsearch(BaseClient):
"""
Elasticsearch low-level client. Provides a straightforward mapping from
Python to Elasticsearch REST APIs.
The client instance has additional attributes to update APIs in different
namespaces such as ``async_search``, ``indices``, ``security``, and more:
.. code-block:: python
client = Elasticsearch("http://localhost:9200")
# Get Document API
client.get(index="*", id="1")
# Get Index API
client.indices.get(index="*")
Transport options can be set on the client constructor or using
the :meth:`~elasticsearch.Elasticsearch.options` method:
.. code-block:: python
# Set 'api_key' on the constructor
client = Elasticsearch(
"http://localhost:9200",
api_key="api_key",
)
client.search(...)
# Set 'api_key' per request
client.options(api_key="api_key").search(...)
"""
def __init__(
self,
hosts: t.Optional[_TYPE_HOSTS] = None,
*,
# API
cloud_id: t.Optional[str] = None,
api_key: t.Optional[t.Union[str, t.Tuple[str, str]]] = None,
basic_auth: t.Optional[t.Union[str, t.Tuple[str, str]]] = None,
bearer_auth: t.Optional[str] = None,
opaque_id: t.Optional[str] = None,
# Node
headers: t.Union[DefaultType, t.Mapping[str, str]] = DEFAULT,
connections_per_node: t.Union[DefaultType, int] = DEFAULT,
http_compress: t.Union[DefaultType, bool] = DEFAULT,
verify_certs: t.Union[DefaultType, bool] = DEFAULT,
ca_certs: t.Union[DefaultType, str] = DEFAULT,
client_cert: t.Union[DefaultType, str] = DEFAULT,
client_key: t.Union[DefaultType, str] = DEFAULT,
ssl_assert_hostname: t.Union[DefaultType, str] = DEFAULT,
ssl_assert_fingerprint: t.Union[DefaultType, str] = DEFAULT,
ssl_version: t.Union[DefaultType, int] = DEFAULT,
ssl_context: t.Union[DefaultType, t.Any] = DEFAULT,
ssl_show_warn: t.Union[DefaultType, bool] = DEFAULT,
# Transport
transport_class: t.Type[Transport] = Transport,
request_timeout: t.Union[DefaultType, None, float] = DEFAULT,
node_class: t.Union[DefaultType, t.Type[BaseNode]] = DEFAULT,
node_pool_class: t.Union[DefaultType, t.Type[NodePool]] = DEFAULT,
randomize_nodes_in_pool: t.Union[DefaultType, bool] = DEFAULT,
node_selector_class: t.Union[DefaultType, t.Type[NodeSelector]] = DEFAULT,
dead_node_backoff_factor: t.Union[DefaultType, float] = DEFAULT,
max_dead_node_backoff: t.Union[DefaultType, float] = DEFAULT,
serializer: t.Optional[Serializer] = None,
serializers: t.Union[DefaultType, t.Mapping[str, Serializer]] = DEFAULT,
default_mimetype: str = "application/json",
max_retries: t.Union[DefaultType, int] = DEFAULT,
retry_on_status: t.Union[DefaultType, int, t.Collection[int]] = DEFAULT,
retry_on_timeout: t.Union[DefaultType, bool] = DEFAULT,
sniff_on_start: t.Union[DefaultType, bool] = DEFAULT,
sniff_before_requests: t.Union[DefaultType, bool] = DEFAULT,
sniff_on_node_failure: t.Union[DefaultType, bool] = DEFAULT,
sniff_timeout: t.Union[DefaultType, None, float] = DEFAULT,
min_delay_between_sniffing: t.Union[DefaultType, None, float] = DEFAULT,
sniffed_node_callback: t.Optional[
t.Callable[[t.Dict[str, t.Any], NodeConfig], t.Optional[NodeConfig]]
] = None,
meta_header: t.Union[DefaultType, bool] = DEFAULT,
timeout: t.Union[DefaultType, None, float] = DEFAULT,
randomize_hosts: t.Union[DefaultType, bool] = DEFAULT,
host_info_callback: t.Optional[
t.Callable[
[t.Dict[str, t.Any], t.Dict[str, t.Union[str, int]]],
t.Optional[t.Dict[str, t.Union[str, int]]],
]
] = None,
sniffer_timeout: t.Union[DefaultType, None, float] = DEFAULT,
sniff_on_connection_fail: t.Union[DefaultType, bool] = DEFAULT,
http_auth: t.Union[DefaultType, t.Any] = DEFAULT,
maxsize: t.Union[DefaultType, int] = DEFAULT,
# Internal use only
_transport: t.Optional[Transport] = None,
) -> None:
if hosts is None and cloud_id is None and _transport is None:
raise ValueError("Either 'hosts' or 'cloud_id' must be specified")
if timeout is not DEFAULT:
if request_timeout is not DEFAULT:
raise ValueError(
"Can't specify both 'timeout' and 'request_timeout', "
"instead only specify 'request_timeout'"
)
warnings.warn(
"The 'timeout' parameter is deprecated in favor of 'request_timeout'",
category=DeprecationWarning,
stacklevel=2,
)
request_timeout = timeout
if serializer is not None:
if serializers is not DEFAULT:
raise ValueError(
"Can't specify both 'serializer' and 'serializers' parameters "
"together. Instead only specify one of the other."
)
serializers = {default_mimetype: serializer}
if randomize_hosts is not DEFAULT:
if randomize_nodes_in_pool is not DEFAULT:
raise ValueError(
"Can't specify both 'randomize_hosts' and 'randomize_nodes_in_pool', "
"instead only specify 'randomize_nodes_in_pool'"
)
warnings.warn(
"The 'randomize_hosts' parameter is deprecated in favor of 'randomize_nodes_in_pool'",
category=DeprecationWarning,
stacklevel=2,
)
randomize_nodes_in_pool = randomize_hosts
if sniffer_timeout is not DEFAULT:
if min_delay_between_sniffing is not DEFAULT:
raise ValueError(
"Can't specify both 'sniffer_timeout' and 'min_delay_between_sniffing', "
"instead only specify 'min_delay_between_sniffing'"
)
warnings.warn(
"The 'sniffer_timeout' parameter is deprecated in favor of 'min_delay_between_sniffing'",
category=DeprecationWarning,
stacklevel=2,
)
min_delay_between_sniffing = sniffer_timeout
if sniff_on_connection_fail is not DEFAULT:
if sniff_on_node_failure is not DEFAULT:
raise ValueError(
"Can't specify both 'sniff_on_connection_fail' and 'sniff_on_node_failure', "
"instead only specify 'sniff_on_node_failure'"
)
warnings.warn(
"The 'sniff_on_connection_fail' parameter is deprecated in favor of 'sniff_on_node_failure'",
category=DeprecationWarning,
stacklevel=2,
)
sniff_on_node_failure = sniff_on_connection_fail
if maxsize is not DEFAULT:
if connections_per_node is not DEFAULT:
raise ValueError(
"Can't specify both 'maxsize' and 'connections_per_node', "
"instead only specify 'connections_per_node'"
)
warnings.warn(
"The 'maxsize' parameter is deprecated in favor of 'connections_per_node'",
category=DeprecationWarning,
stacklevel=2,
)
connections_per_node = maxsize
# Setting min_delay_between_sniffing=True implies sniff_before_requests=True
if min_delay_between_sniffing is not DEFAULT:
sniff_before_requests = True
sniffing_options = (
sniff_timeout,
sniff_on_start,
sniff_before_requests,
sniff_on_node_failure,
sniffed_node_callback,
min_delay_between_sniffing,
sniffed_node_callback,
)
if cloud_id is not None and any(
x is not DEFAULT and x is not None for x in sniffing_options
):
raise ValueError(
"Sniffing should not be enabled when connecting to Elastic Cloud"
)
sniff_callback = None
if host_info_callback is not None:
if sniffed_node_callback is not None:
raise ValueError(
"Can't specify both 'host_info_callback' and 'sniffed_node_callback', "
"instead only specify 'sniffed_node_callback'"
)
warnings.warn(
"The 'host_info_callback' parameter is deprecated in favor of 'sniffed_node_callback'",
category=DeprecationWarning,
stacklevel=2,
)
sniff_callback = create_sniff_callback(
host_info_callback=host_info_callback
)
elif sniffed_node_callback is not None:
sniff_callback = create_sniff_callback(
sniffed_node_callback=sniffed_node_callback
)
elif (
sniff_on_start is True
or sniff_before_requests is True
or sniff_on_node_failure is True
):
sniff_callback = default_sniff_callback
if _transport is None:
requests_session_auth = None
if http_auth is not None and http_auth is not DEFAULT:
if is_requests_http_auth(http_auth):
# If we're using custom requests authentication
# then we need to alert the user that they also
# need to use 'node_class=requests'.
if not is_requests_node_class(node_class):
raise ValueError(
"Using a custom 'requests.auth.AuthBase' class for "
"'http_auth' must be used with node_class='requests'"
)
# Reset 'http_auth' to DEFAULT so it's not consumed below.
requests_session_auth = http_auth
http_auth = DEFAULT
node_configs = client_node_configs(
hosts,
cloud_id=cloud_id,
requests_session_auth=requests_session_auth,
connections_per_node=connections_per_node,
http_compress=http_compress,
verify_certs=verify_certs,
ca_certs=ca_certs,
client_cert=client_cert,
client_key=client_key,
ssl_assert_hostname=ssl_assert_hostname,
ssl_assert_fingerprint=ssl_assert_fingerprint,
ssl_version=ssl_version,
ssl_context=ssl_context,
ssl_show_warn=ssl_show_warn,
)
transport_kwargs: t.Dict[str, t.Any] = {}
if node_class is not DEFAULT:
transport_kwargs["node_class"] = node_class
if node_pool_class is not DEFAULT:
transport_kwargs["node_pool_class"] = node_pool_class
if randomize_nodes_in_pool is not DEFAULT:
transport_kwargs["randomize_nodes_in_pool"] = randomize_nodes_in_pool
if node_selector_class is not DEFAULT:
transport_kwargs["node_selector_class"] = node_selector_class
if dead_node_backoff_factor is not DEFAULT:
transport_kwargs["dead_node_backoff_factor"] = dead_node_backoff_factor
if max_dead_node_backoff is not DEFAULT:
transport_kwargs["max_dead_node_backoff"] = max_dead_node_backoff
if meta_header is not DEFAULT:
transport_kwargs["meta_header"] = meta_header
transport_serializers = DEFAULT_SERIALIZERS.copy()
if serializers is not DEFAULT:
transport_serializers.update(serializers)
# Override compatibility serializers from their non-compat mimetypes too.
# So we use the same serializer for requests and responses.
for mime_subtype in ("json", "x-ndjson"):
if f"application/{mime_subtype}" in serializers:
compat_mimetype = (
f"application/vnd.elasticsearch+{mime_subtype}"
)
if compat_mimetype not in serializers:
transport_serializers[compat_mimetype] = serializers[
f"application/{mime_subtype}"
]
transport_kwargs["serializers"] = transport_serializers
transport_kwargs["default_mimetype"] = default_mimetype
if sniff_on_start is not DEFAULT:
transport_kwargs["sniff_on_start"] = sniff_on_start
if sniff_before_requests is not DEFAULT:
transport_kwargs["sniff_before_requests"] = sniff_before_requests
if sniff_on_node_failure is not DEFAULT:
transport_kwargs["sniff_on_node_failure"] = sniff_on_node_failure
if sniff_timeout is not DEFAULT:
transport_kwargs["sniff_timeout"] = sniff_timeout
if min_delay_between_sniffing is not DEFAULT:
transport_kwargs["min_delay_between_sniffing"] = (
min_delay_between_sniffing
)
_transport = transport_class(
node_configs,
client_meta_service=CLIENT_META_SERVICE,
sniff_callback=sniff_callback,
**transport_kwargs,
)
super().__init__(_transport)
# These are set per-request so are stored separately.
self._request_timeout = request_timeout
self._max_retries = max_retries
self._retry_on_timeout = retry_on_timeout
if isinstance(retry_on_status, int):
retry_on_status = (retry_on_status,)
self._retry_on_status = retry_on_status
else:
super().__init__(_transport)
if headers is not DEFAULT and headers is not None:
self._headers.update(headers)
if opaque_id is not DEFAULT and opaque_id is not None: # type: ignore[comparison-overlap]
self._headers["x-opaque-id"] = opaque_id
self._headers = resolve_auth_headers(
self._headers,
http_auth=http_auth,
api_key=api_key,
basic_auth=basic_auth,
bearer_auth=bearer_auth,
)
# namespaced clients for compatibility with API names
self.async_search = AsyncSearchClient(self)
self.autoscaling = AutoscalingClient(self)
self.cat = CatClient(self)
self.cluster = ClusterClient(self)
self.connector = ConnectorClient(self)
self.fleet = FleetClient(self)
self.features = FeaturesClient(self)
self.indices = IndicesClient(self)
self.inference = InferenceClient(self)
self.ingest = IngestClient(self)
self.nodes = NodesClient(self)
self.snapshot = SnapshotClient(self)
self.tasks = TasksClient(self)
self.xpack = XPackClient(self)
self.ccr = CcrClient(self)
self.dangling_indices = DanglingIndicesClient(self)
self.enrich = EnrichClient(self)
self.eql = EqlClient(self)
self.esql = EsqlClient(self)
self.graph = GraphClient(self)
self.ilm = IlmClient(self)
self.license = LicenseClient(self)
self.logstash = LogstashClient(self)
self.migration = MigrationClient(self)
self.ml = MlClient(self)
self.monitoring = MonitoringClient(self)
self.query_rules = QueryRulesClient(self)
self.rollup = RollupClient(self)
self.search_application = SearchApplicationClient(self)
self.searchable_snapshots = SearchableSnapshotsClient(self)
self.security = SecurityClient(self)
self.slm = SlmClient(self)
self.shutdown = ShutdownClient(self)
self.sql = SqlClient(self)
self.ssl = SslClient(self)
self.synonyms = SynonymsClient(self)
self.text_structure = TextStructureClient(self)
self.transform = TransformClient(self)
self.watcher = WatcherClient(self)
def __repr__(self) -> str:
try:
# get a list of all connections
nodes = [node.base_url for node in self.transport.node_pool.all()]
# truncate to 5 if there are too many
if len(nodes) > 5:
nodes = nodes[:5] + ["..."]
return f"<{self.__class__.__name__}({nodes})>"
except Exception:
# probably operating on custom transport and connection_pool, ignore
return super().__repr__()
def __enter__(self) -> "Elasticsearch":
try:
# All this to avoid a Mypy error when using unasync.
getattr(self.transport, "_async_call")()
except AttributeError:
pass
return self
def __exit__(self, *_: t.Any) -> None:
self.close()
def options(
self: SelfType,
*,
opaque_id: t.Union[DefaultType, str] = DEFAULT,
api_key: t.Union[DefaultType, str, t.Tuple[str, str]] = DEFAULT,
basic_auth: t.Union[DefaultType, str, t.Tuple[str, str]] = DEFAULT,
bearer_auth: t.Union[DefaultType, str] = DEFAULT,
headers: t.Union[DefaultType, t.Mapping[str, str]] = DEFAULT,
request_timeout: t.Union[DefaultType, t.Optional[float]] = DEFAULT,
ignore_status: t.Union[DefaultType, int, t.Collection[int]] = DEFAULT,
max_retries: t.Union[DefaultType, int] = DEFAULT,
retry_on_status: t.Union[DefaultType, int, t.Collection[int]] = DEFAULT,
retry_on_timeout: t.Union[DefaultType, bool] = DEFAULT,
) -> SelfType:
client = type(self)(_transport=self.transport)
resolved_headers = headers if headers is not DEFAULT else None
resolved_headers = resolve_auth_headers(
headers=resolved_headers,
api_key=api_key,
basic_auth=basic_auth,
bearer_auth=bearer_auth,
)
resolved_opaque_id = opaque_id if opaque_id is not DEFAULT else None
if resolved_opaque_id:
resolved_headers["x-opaque-id"] = resolved_opaque_id
if resolved_headers:
new_headers = self._headers.copy()
new_headers.update(resolved_headers)
client._headers = new_headers
else:
client._headers = self._headers.copy()
if request_timeout is not DEFAULT:
client._request_timeout = request_timeout
else:
client._request_timeout = self._request_timeout
if ignore_status is not DEFAULT:
if isinstance(ignore_status, int):
ignore_status = (ignore_status,)
client._ignore_status = ignore_status
else:
client._ignore_status = self._ignore_status
if max_retries is not DEFAULT:
if not isinstance(max_retries, int):
raise TypeError("'max_retries' must be of type 'int'")
client._max_retries = max_retries
else:
client._max_retries = self._max_retries
if retry_on_status is not DEFAULT:
if isinstance(retry_on_status, int):
retry_on_status = (retry_on_status,)
client._retry_on_status = retry_on_status
else:
client._retry_on_status = self._retry_on_status
if retry_on_timeout is not DEFAULT:
if not isinstance(retry_on_timeout, bool):
raise TypeError("'retry_on_timeout' must be of type 'bool'")
client._retry_on_timeout = retry_on_timeout
else:
client._retry_on_timeout = self._retry_on_timeout
return client
def close(self) -> None:
"""Closes the Transport and all internal connections"""
self.transport.close()
@_rewrite_parameters()
def ping(
self,
*,
error_trace: t.Optional[bool] = None,
filter_path: t.Optional[t.Union[t.List[str], str]] = None,
human: t.Optional[bool] = None,
pretty: t.Optional[bool] = None,
) -> bool:
"""
Returns True if a successful response returns from the info() API,
otherwise returns False. This API call can fail either at the transport
layer (due to connection errors or timeouts) or from a non-2XX HTTP response
(due to authentication or authorization issues).
If you want to discover why the request failed you should use the ``info()`` API.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html>`_
"""
__path = "/"
__query: t.Dict[str, t.Any] = {}
if error_trace is not None:
__query["error_trace"] = error_trace
if filter_path is not None:
__query["filter_path"] = filter_path
if human is not None:
__query["human"] = human
if pretty is not None:
__query["pretty"] = pretty
__headers = {"accept": "application/json"}
try:
self.perform_request("HEAD", __path, params=__query, headers=__headers)
return True
except (ApiError, TransportError):
return False
# AUTO-GENERATED-API-DEFINITIONS #
@_rewrite_parameters(
body_name="operations",
parameter_aliases={
"_source": "source",
"_source_excludes": "source_excludes",
"_source_includes": "source_includes",
},
)
def bulk(
self,
*,
operations: t.Optional[t.Sequence[t.Mapping[str, t.Any]]] = None,
body: t.Optional[t.Sequence[t.Mapping[str, t.Any]]] = None,
index: t.Optional[str] = None,
error_trace: t.Optional[bool] = None,
filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None,
human: t.Optional[bool] = None,
pipeline: t.Optional[str] = None,
pretty: t.Optional[bool] = None,
refresh: t.Optional[
t.Union[bool, str, t.Literal["false", "true", "wait_for"]]
] = None,
require_alias: t.Optional[bool] = None,
routing: t.Optional[str] = None,
source: t.Optional[t.Union[bool, t.Union[str, t.Sequence[str]]]] = None,
source_excludes: t.Optional[t.Union[str, t.Sequence[str]]] = None,
source_includes: t.Optional[t.Union[str, t.Sequence[str]]] = None,
timeout: t.Optional[t.Union[str, t.Literal[-1], t.Literal[0]]] = None,
wait_for_active_shards: t.Optional[
t.Union[int, t.Union[str, t.Literal["all", "index-setting"]]]
] = None,
) -> ObjectApiResponse[t.Any]:
"""
Bulk index or delete documents. Performs multiple indexing or delete operations
in a single API call. This reduces overhead and can greatly increase indexing
speed.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/docs-bulk.html>`_
:param operations:
:param index: Name of the data stream, index, or index alias to perform bulk
actions on.
:param pipeline: ID of the pipeline to use to preprocess incoming documents.
If the index has a default ingest pipeline specified, then setting the value
to `_none` disables the default ingest pipeline for this request. If a final
pipeline is configured it will always run, regardless of the value of this
parameter.
:param refresh: If `true`, Elasticsearch refreshes the affected shards to make
this operation visible to search, if `wait_for` then wait for a refresh to
make this operation visible to search, if `false` do nothing with refreshes.
Valid values: `true`, `false`, `wait_for`.
:param require_alias: If `true`, the request’s actions must target an index alias.
:param routing: Custom value used to route operations to a specific shard.
:param source: `true` or `false` to return the `_source` field or not, or a list
of fields to return.
:param source_excludes: A comma-separated list of source fields to exclude from
the response.
:param source_includes: A comma-separated list of source fields to include in
the response.
:param timeout: Period each action waits for the following operations: automatic
index creation, dynamic mapping updates, waiting for active shards.
:param wait_for_active_shards: The number of shard copies that must be active
before proceeding with the operation. Set to all or any positive integer
up to the total number of shards in the index (`number_of_replicas+1`).
"""
if operations is None and body is None:
raise ValueError(
"Empty value passed for parameters 'operations' and 'body', one of them should be set."
)
elif operations is not None and body is not None:
raise ValueError("Cannot set both 'operations' and 'body'")
__path_parts: t.Dict[str, str]
if index not in SKIP_IN_PATH:
__path_parts = {"index": _quote(index)}
__path = f'/{__path_parts["index"]}/_bulk'
else:
__path_parts = {}
__path = "/_bulk"
__query: t.Dict[str, t.Any] = {}
if error_trace is not None:
__query["error_trace"] = error_trace
if filter_path is not None:
__query["filter_path"] = filter_path
if human is not None:
__query["human"] = human
if pipeline is not None:
__query["pipeline"] = pipeline
if pretty is not None:
__query["pretty"] = pretty
if refresh is not None:
__query["refresh"] = refresh
if require_alias is not None:
__query["require_alias"] = require_alias
if routing is not None:
__query["routing"] = routing
if source is not None:
__query["_source"] = source
if source_excludes is not None:
__query["_source_excludes"] = source_excludes
if source_includes is not None:
__query["_source_includes"] = source_includes
if timeout is not None:
__query["timeout"] = timeout
if wait_for_active_shards is not None:
__query["wait_for_active_shards"] = wait_for_active_shards
__body = operations if operations is not None else body
__headers = {
"accept": "application/json",
"content-type": "application/x-ndjson",
}
return self.perform_request( # type: ignore[return-value]
"PUT",
__path,
params=__query,
headers=__headers,
body=__body,
endpoint_id="bulk",
path_parts=__path_parts,
)
@_rewrite_parameters(
body_fields=("scroll_id",),
)
def clear_scroll(
self,
*,
error_trace: t.Optional[bool] = None,
filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None,
human: t.Optional[bool] = None,
pretty: t.Optional[bool] = None,
scroll_id: t.Optional[t.Union[str, t.Sequence[str]]] = None,
body: t.Optional[t.Dict[str, t.Any]] = None,
) -> ObjectApiResponse[t.Any]:
"""
Clear a scrolling search. Clear the search context and results for a scrolling
search.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/clear-scroll-api.html>`_
:param scroll_id: Scroll IDs to clear. To clear all scroll IDs, use `_all`.
"""
__path_parts: t.Dict[str, str] = {}
__path = "/_search/scroll"
__query: t.Dict[str, t.Any] = {}
__body: t.Dict[str, t.Any] = body if body is not None else {}
if error_trace is not None:
__query["error_trace"] = error_trace
if filter_path is not None:
__query["filter_path"] = filter_path
if human is not None:
__query["human"] = human
if pretty is not None:
__query["pretty"] = pretty
if not __body:
if scroll_id is not None:
__body["scroll_id"] = scroll_id
if not __body:
__body = None # type: ignore[assignment]
__headers = {"accept": "application/json"}
if __body is not None:
__headers["content-type"] = "application/json"
return self.perform_request( # type: ignore[return-value]
"DELETE",
__path,
params=__query,
headers=__headers,
body=__body,
endpoint_id="clear_scroll",
path_parts=__path_parts,
)
@_rewrite_parameters(
body_fields=("id",),
)
def close_point_in_time(
self,
*,
id: t.Optional[str] = None,
error_trace: t.Optional[bool] = None,
filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None,
human: t.Optional[bool] = None,
pretty: t.Optional[bool] = None,
body: t.Optional[t.Dict[str, t.Any]] = None,
) -> ObjectApiResponse[t.Any]:
"""
Close a point in time. A point in time must be opened explicitly before being
used in search requests. The `keep_alive` parameter tells Elasticsearch how long
it should persist. A point in time is automatically closed when the `keep_alive`
period has elapsed. However, keeping points in time has a cost; close them as
soon as they are no longer required for search requests.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/point-in-time-api.html>`_
:param id: The ID of the point-in-time.
"""
if id is None and body is None:
raise ValueError("Empty value passed for parameter 'id'")
__path_parts: t.Dict[str, str] = {}
__path = "/_pit"
__query: t.Dict[str, t.Any] = {}
__body: t.Dict[str, t.Any] = body if body is not None else {}
if error_trace is not None:
__query["error_trace"] = error_trace
if filter_path is not None:
__query["filter_path"] = filter_path
if human is not None:
__query["human"] = human
if pretty is not None:
__query["pretty"] = pretty
if not __body:
if id is not None:
__body["id"] = id
if not __body:
__body = None # type: ignore[assignment]
__headers = {"accept": "application/json"}
if __body is not None:
__headers["content-type"] = "application/json"
return self.perform_request( # type: ignore[return-value]
"DELETE",
__path,
params=__query,
headers=__headers,
body=__body,
endpoint_id="close_point_in_time",
path_parts=__path_parts,
)
@_rewrite_parameters(
body_fields=("query",),
)
def count(
self,
*,
index: t.Optional[t.Union[str, t.Sequence[str]]] = None,
allow_no_indices: t.Optional[bool] = None,
analyze_wildcard: t.Optional[bool] = None,
analyzer: t.Optional[str] = None,
default_operator: t.Optional[t.Union[str, t.Literal["and", "or"]]] = None,
df: t.Optional[str] = None,
error_trace: t.Optional[bool] = None,
expand_wildcards: t.Optional[
t.Union[
t.Sequence[
t.Union[str, t.Literal["all", "closed", "hidden", "none", "open"]]
],
t.Union[str, t.Literal["all", "closed", "hidden", "none", "open"]],
]
] = None,
filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None,
human: t.Optional[bool] = None,
ignore_throttled: t.Optional[bool] = None,
ignore_unavailable: t.Optional[bool] = None,
lenient: t.Optional[bool] = None,
min_score: t.Optional[float] = None,
preference: t.Optional[str] = None,
pretty: t.Optional[bool] = None,
q: t.Optional[str] = None,
query: t.Optional[t.Mapping[str, t.Any]] = None,
routing: t.Optional[str] = None,
terminate_after: t.Optional[int] = None,
body: t.Optional[t.Dict[str, t.Any]] = None,
) -> ObjectApiResponse[t.Any]:
"""
Count search results. Get the number of documents matching a query.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/search-count.html>`_
:param index: Comma-separated list of data streams, indices, and aliases to search.
Supports wildcards (`*`). To search all data streams and indices, omit this
parameter or use `*` or `_all`.
:param allow_no_indices: If `false`, the request returns an error if any wildcard
expression, index alias, or `_all` value targets only missing or closed indices.
This behavior applies even if the request targets other open indices.
:param analyze_wildcard: If `true`, wildcard and prefix queries are analyzed.
This parameter can only be used when the `q` query string parameter is specified.
:param analyzer: Analyzer to use for the query string. This parameter can only
be used when the `q` query string parameter is specified.
:param default_operator: The default operator for query string query: `AND` or
`OR`. This parameter can only be used when the `q` query string parameter
is specified.
:param df: Field to use as default where no field prefix is given in the query
string. This parameter can only be used when the `q` query string parameter
is specified.
:param expand_wildcards: Type of index that wildcard patterns can match. If the
request can target data streams, this argument determines whether wildcard
expressions match hidden data streams. Supports comma-separated values, such
as `open,hidden`.
:param ignore_throttled: If `true`, concrete, expanded or aliased indices are
ignored when frozen.
:param ignore_unavailable: If `false`, the request returns an error if it targets
a missing or closed index.
:param lenient: If `true`, format-based query failures (such as providing text
to a numeric field) in the query string will be ignored.
:param min_score: Sets the minimum `_score` value that documents must have to
be included in the result.
:param preference: Specifies the node or shard the operation should be performed
on. Random by default.
:param q: Query in the Lucene query string syntax.
:param query: Defines the search definition using the Query DSL.
:param routing: Custom value used to route operations to a specific shard.
:param terminate_after: Maximum number of documents to collect for each shard.
If a query reaches this limit, Elasticsearch terminates the query early.
Elasticsearch collects documents before sorting.
"""
__path_parts: t.Dict[str, str]
if index not in SKIP_IN_PATH:
__path_parts = {"index": _quote(index)}
__path = f'/{__path_parts["index"]}/_count'
else:
__path_parts = {}
__path = "/_count"
__query: t.Dict[str, t.Any] = {}
__body: t.Dict[str, t.Any] = body if body is not None else {}
if allow_no_indices is not None:
__query["allow_no_indices"] = allow_no_indices
if analyze_wildcard is not None:
__query["analyze_wildcard"] = analyze_wildcard
if analyzer is not None:
__query["analyzer"] = analyzer
if default_operator is not None:
__query["default_operator"] = default_operator
if df is not None:
__query["df"] = df
if error_trace is not None:
__query["error_trace"] = error_trace
if expand_wildcards is not None:
__query["expand_wildcards"] = expand_wildcards
if filter_path is not None:
__query["filter_path"] = filter_path
if human is not None:
__query["human"] = human
if ignore_throttled is not None:
__query["ignore_throttled"] = ignore_throttled
if ignore_unavailable is not None:
__query["ignore_unavailable"] = ignore_unavailable
if lenient is not None:
__query["lenient"] = lenient
if min_score is not None:
__query["min_score"] = min_score
if preference is not None:
__query["preference"] = preference
if pretty is not None:
__query["pretty"] = pretty
if q is not None:
__query["q"] = q
if routing is not None:
__query["routing"] = routing
if terminate_after is not None:
__query["terminate_after"] = terminate_after
if not __body:
if query is not None:
__body["query"] = query
if not __body:
__body = None # type: ignore[assignment]
__headers = {"accept": "application/json"}
if __body is not None:
__headers["content-type"] = "application/json"
return self.perform_request( # type: ignore[return-value]
"POST",
__path,
params=__query,
headers=__headers,
body=__body,
endpoint_id="count",
path_parts=__path_parts,
)
@_rewrite_parameters(
body_name="document",
)
def create(
self,
*,
index: str,
id: str,
document: t.Optional[t.Mapping[str, t.Any]] = None,
body: t.Optional[t.Mapping[str, t.Any]] = None,
error_trace: t.Optional[bool] = None,
filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None,
human: t.Optional[bool] = None,
pipeline: t.Optional[str] = None,
pretty: t.Optional[bool] = None,
refresh: t.Optional[
t.Union[bool, str, t.Literal["false", "true", "wait_for"]]
] = None,
routing: t.Optional[str] = None,
timeout: t.Optional[t.Union[str, t.Literal[-1], t.Literal[0]]] = None,
version: t.Optional[int] = None,
version_type: t.Optional[
t.Union[str, t.Literal["external", "external_gte", "force", "internal"]]
] = None,