elasticsearch 9.0.2__py3-none-any.whl → 9.1.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 (110) hide show
  1. elasticsearch/__init__.py +3 -3
  2. elasticsearch/_async/client/__init__.py +88 -244
  3. elasticsearch/_async/client/async_search.py +4 -4
  4. elasticsearch/_async/client/autoscaling.py +4 -4
  5. elasticsearch/_async/client/cat.py +419 -51
  6. elasticsearch/_async/client/ccr.py +13 -13
  7. elasticsearch/_async/client/cluster.py +32 -22
  8. elasticsearch/_async/client/connector.py +30 -30
  9. elasticsearch/_async/client/dangling_indices.py +3 -3
  10. elasticsearch/_async/client/enrich.py +5 -5
  11. elasticsearch/_async/client/eql.py +14 -6
  12. elasticsearch/_async/client/esql.py +125 -9
  13. elasticsearch/_async/client/features.py +2 -2
  14. elasticsearch/_async/client/fleet.py +3 -3
  15. elasticsearch/_async/client/graph.py +1 -1
  16. elasticsearch/_async/client/ilm.py +11 -11
  17. elasticsearch/_async/client/indices.py +592 -113
  18. elasticsearch/_async/client/inference.py +521 -44
  19. elasticsearch/_async/client/ingest.py +9 -16
  20. elasticsearch/_async/client/license.py +11 -11
  21. elasticsearch/_async/client/logstash.py +3 -3
  22. elasticsearch/_async/client/migration.py +3 -3
  23. elasticsearch/_async/client/ml.py +75 -87
  24. elasticsearch/_async/client/monitoring.py +1 -1
  25. elasticsearch/_async/client/nodes.py +7 -7
  26. elasticsearch/_async/client/query_rules.py +8 -8
  27. elasticsearch/_async/client/rollup.py +9 -30
  28. elasticsearch/_async/client/search_application.py +10 -10
  29. elasticsearch/_async/client/searchable_snapshots.py +4 -4
  30. elasticsearch/_async/client/security.py +79 -81
  31. elasticsearch/_async/client/shutdown.py +3 -3
  32. elasticsearch/_async/client/simulate.py +1 -1
  33. elasticsearch/_async/client/slm.py +9 -9
  34. elasticsearch/_async/client/snapshot.py +64 -21
  35. elasticsearch/_async/client/sql.py +6 -6
  36. elasticsearch/_async/client/ssl.py +1 -1
  37. elasticsearch/_async/client/synonyms.py +26 -7
  38. elasticsearch/_async/client/tasks.py +4 -4
  39. elasticsearch/_async/client/text_structure.py +4 -4
  40. elasticsearch/_async/client/transform.py +11 -11
  41. elasticsearch/_async/client/watcher.py +17 -15
  42. elasticsearch/_async/client/xpack.py +2 -2
  43. elasticsearch/_otel.py +8 -8
  44. elasticsearch/_sync/client/__init__.py +88 -244
  45. elasticsearch/_sync/client/async_search.py +4 -4
  46. elasticsearch/_sync/client/autoscaling.py +4 -4
  47. elasticsearch/_sync/client/cat.py +419 -51
  48. elasticsearch/_sync/client/ccr.py +13 -13
  49. elasticsearch/_sync/client/cluster.py +32 -22
  50. elasticsearch/_sync/client/connector.py +30 -30
  51. elasticsearch/_sync/client/dangling_indices.py +3 -3
  52. elasticsearch/_sync/client/enrich.py +5 -5
  53. elasticsearch/_sync/client/eql.py +14 -6
  54. elasticsearch/_sync/client/esql.py +125 -9
  55. elasticsearch/_sync/client/features.py +2 -2
  56. elasticsearch/_sync/client/fleet.py +3 -3
  57. elasticsearch/_sync/client/graph.py +1 -1
  58. elasticsearch/_sync/client/ilm.py +11 -11
  59. elasticsearch/_sync/client/indices.py +592 -113
  60. elasticsearch/_sync/client/inference.py +521 -44
  61. elasticsearch/_sync/client/ingest.py +9 -16
  62. elasticsearch/_sync/client/license.py +11 -11
  63. elasticsearch/_sync/client/logstash.py +3 -3
  64. elasticsearch/_sync/client/migration.py +3 -3
  65. elasticsearch/_sync/client/ml.py +75 -87
  66. elasticsearch/_sync/client/monitoring.py +1 -1
  67. elasticsearch/_sync/client/nodes.py +7 -7
  68. elasticsearch/_sync/client/query_rules.py +8 -8
  69. elasticsearch/_sync/client/rollup.py +9 -30
  70. elasticsearch/_sync/client/search_application.py +10 -10
  71. elasticsearch/_sync/client/searchable_snapshots.py +4 -4
  72. elasticsearch/_sync/client/security.py +79 -81
  73. elasticsearch/_sync/client/shutdown.py +3 -3
  74. elasticsearch/_sync/client/simulate.py +1 -1
  75. elasticsearch/_sync/client/slm.py +9 -9
  76. elasticsearch/_sync/client/snapshot.py +64 -21
  77. elasticsearch/_sync/client/sql.py +6 -6
  78. elasticsearch/_sync/client/ssl.py +1 -1
  79. elasticsearch/_sync/client/synonyms.py +26 -7
  80. elasticsearch/_sync/client/tasks.py +4 -4
  81. elasticsearch/_sync/client/text_structure.py +4 -4
  82. elasticsearch/_sync/client/transform.py +11 -11
  83. elasticsearch/_sync/client/watcher.py +17 -15
  84. elasticsearch/_sync/client/xpack.py +2 -2
  85. elasticsearch/_version.py +1 -1
  86. elasticsearch/compat.py +5 -0
  87. elasticsearch/dsl/__init__.py +2 -1
  88. elasticsearch/dsl/aggs.py +20 -0
  89. elasticsearch/dsl/document_base.py +177 -17
  90. elasticsearch/dsl/field.py +230 -37
  91. elasticsearch/dsl/query.py +6 -3
  92. elasticsearch/dsl/response/__init__.py +1 -1
  93. elasticsearch/dsl/types.py +169 -11
  94. elasticsearch/dsl/utils.py +1 -1
  95. elasticsearch/{dsl/_sync/_sync_check → esql}/__init__.py +2 -0
  96. elasticsearch/esql/esql.py +1105 -0
  97. elasticsearch/esql/esql1.py1 +307 -0
  98. elasticsearch/esql/functions.py +1738 -0
  99. {elasticsearch-9.0.2.dist-info → elasticsearch-9.1.0.dist-info}/METADATA +3 -4
  100. elasticsearch-9.1.0.dist-info/RECORD +164 -0
  101. elasticsearch/dsl/_sync/_sync_check/document.py +0 -514
  102. elasticsearch/dsl/_sync/_sync_check/faceted_search.py +0 -50
  103. elasticsearch/dsl/_sync/_sync_check/index.py +0 -597
  104. elasticsearch/dsl/_sync/_sync_check/mapping.py +0 -49
  105. elasticsearch/dsl/_sync/_sync_check/search.py +0 -230
  106. elasticsearch/dsl/_sync/_sync_check/update_by_query.py +0 -45
  107. elasticsearch-9.0.2.dist-info/RECORD +0 -167
  108. {elasticsearch-9.0.2.dist-info → elasticsearch-9.1.0.dist-info}/WHEEL +0 -0
  109. {elasticsearch-9.0.2.dist-info → elasticsearch-9.1.0.dist-info}/licenses/LICENSE +0 -0
  110. {elasticsearch-9.0.2.dist-info → elasticsearch-9.1.0.dist-info}/licenses/NOTICE +0 -0
@@ -0,0 +1,1105 @@
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
+ import json
19
+ from abc import ABC, abstractmethod
20
+ from typing import Any, Dict, Optional, Tuple, Type, Union
21
+
22
+ from ..dsl.document_base import DocumentBase, InstrumentedExpression, InstrumentedField
23
+
24
+ FieldType = Union[InstrumentedField, str]
25
+ IndexType = Union[Type[DocumentBase], str]
26
+ ExpressionType = Any
27
+
28
+
29
+ class ESQL(ABC):
30
+ """The static methods of the ``ESQL`` class provide access to the ES|QL source
31
+ commands, used to create ES|QL queries.
32
+
33
+ These methods return an instance of class ``ESQLBase``, which provides access to
34
+ the ES|QL processing commands.
35
+ """
36
+
37
+ @staticmethod
38
+ def from_(*indices: IndexType) -> "From":
39
+ """The ``FROM`` source command returns a table with data from a data stream, index, or alias.
40
+
41
+ :param indices: A list of indices, data streams or aliases. Supports wildcards and date math.
42
+
43
+ Examples::
44
+
45
+ query1 = ESQL.from_("employees")
46
+ query2 = ESQL.from_("<logs-{now/d}>")
47
+ query3 = ESQL.from_("employees-00001", "other-employees-*")
48
+ query4 = ESQL.from_("cluster_one:employees-00001", "cluster_two:other-employees-*")
49
+ query5 = ESQL.from_("employees").metadata("_id")
50
+ """
51
+ return From(*indices)
52
+
53
+ @staticmethod
54
+ def row(**params: ExpressionType) -> "Row":
55
+ """The ``ROW`` source command produces a row with one or more columns with values that you specify.
56
+ This can be useful for testing.
57
+
58
+ :param params: the column values to produce, given as keyword arguments.
59
+
60
+ Examples::
61
+
62
+ query1 = ESQL.row(a=1, b="two", c=None)
63
+ query2 = ESQL.row(a=[1, 2])
64
+ query3 = ESQL.row(a=functions.round(1.23, 0))
65
+ """
66
+ return Row(**params)
67
+
68
+ @staticmethod
69
+ def show(item: str) -> "Show":
70
+ """The ``SHOW`` source command returns information about the deployment and its capabilities.
71
+
72
+ :param item: Can only be ``INFO``.
73
+
74
+ Examples::
75
+
76
+ query = ESQL.show("INFO")
77
+ """
78
+ return Show(item)
79
+
80
+ @staticmethod
81
+ def branch() -> "Branch":
82
+ """This method can only be used inside a ``FORK`` command to create each branch.
83
+
84
+ Examples::
85
+
86
+ query = ESQL.from_("employees").fork(
87
+ ESQL.branch().where("emp_no == 10001"),
88
+ ESQL.branch().where("emp_no == 10002"),
89
+ )
90
+ """
91
+ return Branch()
92
+
93
+
94
+ class ESQLBase(ABC):
95
+ """The methods of the ``ESQLBase`` class provide access to the ES|QL processing
96
+ commands, used to build ES|QL queries.
97
+ """
98
+
99
+ def __init__(self, parent: Optional["ESQLBase"] = None):
100
+ self._parent = parent
101
+
102
+ def __repr__(self) -> str:
103
+ return self.render()
104
+
105
+ def render(self) -> str:
106
+ return (
107
+ self._parent.render() + "\n| " if self._parent else ""
108
+ ) + self._render_internal()
109
+
110
+ @abstractmethod
111
+ def _render_internal(self) -> str:
112
+ pass
113
+
114
+ def _is_forked(self) -> bool:
115
+ if self.__class__.__name__ == "Fork":
116
+ return True
117
+ if self._parent:
118
+ return self._parent._is_forked()
119
+ return False
120
+
121
+ def change_point(self, value: FieldType) -> "ChangePoint":
122
+ """`CHANGE_POINT` detects spikes, dips, and change points in a metric.
123
+
124
+ :param value: The column with the metric in which you want to detect a change point.
125
+
126
+ Examples::
127
+
128
+ query = (
129
+ ESQL.row(key=list(range(1, 26)))
130
+ .mv_expand("key")
131
+ .eval(value=functions.case("key<13", 0, 42))
132
+ .change_point("value")
133
+ .on("key")
134
+ .where("type IS NOT NULL")
135
+ )
136
+ """
137
+ return ChangePoint(self, value)
138
+
139
+ def completion(
140
+ self, *prompt: ExpressionType, **named_prompt: ExpressionType
141
+ ) -> "Completion":
142
+ """The `COMPLETION` command allows you to send prompts and context to a Large
143
+ Language Model (LLM) directly within your ES|QL queries, to perform text
144
+ generation tasks.
145
+
146
+ :param prompt: The input text or expression used to prompt the LLM. This can
147
+ be a string literal or a reference to a column containing text.
148
+ :param named_prompt: The input text or expresion, given as a keyword argument.
149
+ The argument name is used for the column name. If not
150
+ specified, the results will be stored in a column named
151
+ `completion`. If the specified column already exists, it
152
+ will be overwritten with the new results.
153
+
154
+ Examples::
155
+
156
+ query1 = (
157
+ ESQL.row(question="What is Elasticsearch?")
158
+ .completion("question").with_("test_completion_model")
159
+ .keep("question", "completion")
160
+ )
161
+ query2 = (
162
+ ESQL.row(question="What is Elasticsearch?")
163
+ .completion(answer="question").with_("test_completion_model")
164
+ .keep("question", "answer")
165
+ )
166
+ query3 = (
167
+ ESQL.from_("movies")
168
+ .sort("rating DESC")
169
+ .limit(10)
170
+ .eval(prompt=\"\"\"CONCAT(
171
+ "Summarize this movie using the following information: \\n",
172
+ "Title: ", title, "\\n",
173
+ "Synopsis: ", synopsis, "\\n",
174
+ "Actors: ", MV_CONCAT(actors, ", "), "\\n",
175
+ )\"\"\")
176
+ .completion(summary="prompt").with_("test_completion_model")
177
+ .keep("title", "summary", "rating")
178
+ )
179
+ """
180
+ return Completion(self, *prompt, **named_prompt)
181
+
182
+ def dissect(self, input: FieldType, pattern: str) -> "Dissect":
183
+ """``DISSECT`` enables you to extract structured data out of a string.
184
+
185
+ :param input: The column that contains the string you want to structure. If
186
+ the column has multiple values, ``DISSECT`` will process each value.
187
+ :param pattern: A dissect pattern. If a field name conflicts with an existing
188
+ column, the existing column is dropped. If a field name is used
189
+ more than once, only the rightmost duplicate creates a column.
190
+
191
+ Examples::
192
+
193
+ query = (
194
+ ESQL.row(a="2023-01-23T12:15:00.000Z - some text - 127.0.0.1")
195
+ .dissect("a", "%{date} - %{msg} - %{ip}")
196
+ .keep("date", "msg", "ip")
197
+ .eval(date="TO_DATETIME(date)")
198
+ )
199
+ """
200
+ return Dissect(self, input, pattern)
201
+
202
+ def drop(self, *columns: FieldType) -> "Drop":
203
+ """The ``DROP`` processing command removes one or more columns.
204
+
205
+ :param columns: The columns to drop, given as positional arguments. Supports wildcards.
206
+
207
+ Examples::
208
+
209
+ query1 = ESQL.from_("employees").drop("height")
210
+ query2 = ESQL.from_("employees").drop("height*")
211
+ """
212
+ return Drop(self, *columns)
213
+
214
+ def enrich(self, policy: str) -> "Enrich":
215
+ """``ENRICH`` enables you to add data from existing indices as new columns using an
216
+ enrich policy.
217
+
218
+ :param policy: The name of the enrich policy. You need to create and execute the
219
+ enrich policy first.
220
+
221
+ Examples::
222
+
223
+ query1 = (
224
+ ESQL.row(a="1")
225
+ .enrich("languages_policy").on("a").with_("language_name")
226
+ )
227
+ query2 = (
228
+ ESQL.row(a="1")
229
+ .enrich("languages_policy").on("a").with_(name="language_name")
230
+ )
231
+ """
232
+ return Enrich(self, policy)
233
+
234
+ def eval(self, *columns: ExpressionType, **named_columns: ExpressionType) -> "Eval":
235
+ """The ``EVAL`` processing command enables you to append new columns with calculated values.
236
+
237
+ :param columns: The values for the columns, given as positional arguments. Can be literals,
238
+ expressions, or functions. Can use columns defined left of this one.
239
+ :param named_columns: The values for the new columns, given as keyword arguments. The name
240
+ of the arguments is used as column name. If a column with the same
241
+ name already exists, the existing column is dropped. If a column name
242
+ is used more than once, only the rightmost duplicate creates a column.
243
+
244
+ Examples::
245
+
246
+ query1 = (
247
+ ESQL.from_("employees")
248
+ .sort("emp_no")
249
+ .keep("first_name", "last_name", "height")
250
+ .eval(height_feet="height * 3.281", height_cm="height * 100")
251
+ )
252
+ query2 = (
253
+ ESQL.from_("employees")
254
+ .eval("height * 3.281")
255
+ .stats(avg_height_feet=functions.avg("`height * 3.281`"))
256
+ )
257
+ """
258
+ return Eval(self, *columns, **named_columns)
259
+
260
+ def fork(
261
+ self,
262
+ fork1: "ESQLBase",
263
+ fork2: Optional["ESQLBase"] = None,
264
+ fork3: Optional["ESQLBase"] = None,
265
+ fork4: Optional["ESQLBase"] = None,
266
+ fork5: Optional["ESQLBase"] = None,
267
+ fork6: Optional["ESQLBase"] = None,
268
+ fork7: Optional["ESQLBase"] = None,
269
+ fork8: Optional["ESQLBase"] = None,
270
+ ) -> "Fork":
271
+ """The ``FORK`` processing command creates multiple execution branches to operate on the
272
+ same input data and combines the results in a single output table.
273
+
274
+ :param fork<n>: Up to 8 execution branches, created with the ``ESQL.branch()`` method.
275
+
276
+ Examples::
277
+
278
+ query = (
279
+ ESQL.from_("employees")
280
+ .fork(
281
+ ESQL.branch().where("emp_no == 10001"),
282
+ ESQL.branch().where("emp_no == 10002"),
283
+ )
284
+ .keep("emp_no", "_fork")
285
+ .sort("emp_no")
286
+ )
287
+ """
288
+ if self._is_forked():
289
+ raise ValueError("a query can only have one fork")
290
+ return Fork(self, fork1, fork2, fork3, fork4, fork5, fork6, fork7, fork8)
291
+
292
+ def grok(self, input: FieldType, pattern: str) -> "Grok":
293
+ """``GROK`` enables you to extract structured data out of a string.
294
+
295
+ :param input: The column that contains the string you want to structure. If the
296
+ column has multiple values, ``GROK`` will process each value.
297
+ :param pattern: A grok pattern. If a field name conflicts with an existing column,
298
+ the existing column is discarded. If a field name is used more than
299
+ once, a multi-valued column will be created with one value per each
300
+ occurrence of the field name.
301
+
302
+ Examples::
303
+
304
+ query1 = (
305
+ ESQL.row(a="2023-01-23T12:15:00.000Z 127.0.0.1 some.email@foo.com 42")
306
+ .grok("a", "%{TIMESTAMP_ISO8601:date} %{IP:ip} %{EMAILADDRESS:email} %{NUMBER:num}")
307
+ .keep("date", "ip", "email", "num")
308
+ )
309
+ query2 = (
310
+ ESQL.row(a="2023-01-23T12:15:00.000Z 127.0.0.1 some.email@foo.com 42")
311
+ .grok(
312
+ "a",
313
+ "%{TIMESTAMP_ISO8601:date} %{IP:ip} %{EMAILADDRESS:email} %{NUMBER:num:int}",
314
+ )
315
+ .keep("date", "ip", "email", "num")
316
+ .eval(date=functions.to_datetime("date"))
317
+ )
318
+ query3 = (
319
+ ESQL.from_("addresses")
320
+ .keep("city.name", "zip_code")
321
+ .grok("zip_code", "%{WORD:zip_parts} %{WORD:zip_parts}")
322
+ )
323
+ """
324
+ return Grok(self, input, pattern)
325
+
326
+ def keep(self, *columns: FieldType) -> "Keep":
327
+ """The ``KEEP`` processing command enables you to specify what columns are returned
328
+ and the order in which they are returned.
329
+
330
+ :param columns: The columns to keep, given as positional arguments. Supports
331
+ wildcards.
332
+
333
+ Examples::
334
+
335
+ query1 = ESQL.from_("employees").keep("emp_no", "first_name", "last_name", "height")
336
+ query2 = ESQL.from_("employees").keep("h*")
337
+ query3 = ESQL.from_("employees").keep("h*", "*")
338
+ """
339
+ return Keep(self, *columns)
340
+
341
+ def limit(self, max_number_of_rows: int) -> "Limit":
342
+ """The ``LIMIT`` processing command enables you to limit the number of rows that are
343
+ returned.
344
+
345
+ :param max_number_of_rows: The maximum number of rows to return.
346
+
347
+ Examples::
348
+
349
+ query1 = ESQL.from_("employees").sort("emp_no ASC").limit(5)
350
+ query2 = ESQL.from_("index").stats(functions.avg("field1")).by("field2").limit(20000)
351
+ """
352
+ return Limit(self, max_number_of_rows)
353
+
354
+ def lookup_join(self, lookup_index: IndexType) -> "LookupJoin":
355
+ """`LOOKUP JOIN` enables you to add data from another index, AKA a 'lookup' index,
356
+ to your ES|QL query results, simplifying data enrichment and analysis workflows.
357
+
358
+ :param lookup_index: The name of the lookup index. This must be a specific index
359
+ name - wildcards, aliases, and remote cluster references are
360
+ not supported. Indices used for lookups must be configured
361
+ with the lookup index mode.
362
+
363
+ Examples::
364
+
365
+ query1 = (
366
+ ESQL.from_("firewall_logs")
367
+ .lookup_join("threat_list").on("source.IP")
368
+ .where("threat_level IS NOT NULL")
369
+ )
370
+ query2 = (
371
+ ESQL.from_("system_metrics")
372
+ .lookup_join("host_inventory").on("host.name")
373
+ .lookup_join("ownerships").on("host.name")
374
+ )
375
+ query3 = (
376
+ ESQL.from_("app_logs")
377
+ .lookup_join("service_owners").on("service_id")
378
+ )
379
+ query4 = (
380
+ ESQL.from_("employees")
381
+ .eval(language_code="languages")
382
+ .where("emp_no >= 10091 AND emp_no < 10094")
383
+ .lookup_join("languages_lookup").on("language_code")
384
+ )
385
+ """
386
+ return LookupJoin(self, lookup_index)
387
+
388
+ def mv_expand(self, column: FieldType) -> "MvExpand":
389
+ """The `MV_EXPAND` processing command expands multivalued columns into one row per
390
+ value, duplicating other columns.
391
+
392
+ :param column: The multivalued column to expand.
393
+
394
+ Examples::
395
+
396
+ query = ESQL.row(a=[1, 2, 3], b="b", j=["a", "b"]).mv_expand("a")
397
+ """
398
+ return MvExpand(self, column)
399
+
400
+ def rename(self, **columns: FieldType) -> "Rename":
401
+ """The ``RENAME`` processing command renames one or more columns.
402
+
403
+ :param columns: The old and new column name pairs, given as keyword arguments.
404
+ If a name conflicts with an existing column name, the existing column
405
+ is dropped. If multiple columns are renamed to the same name, all but
406
+ the rightmost column with the same new name are dropped.
407
+
408
+ Examples::
409
+
410
+ query = (
411
+ ESQL.from_("employees")
412
+ .keep("first_name", "last_name", "still_hired")
413
+ .rename(still_hired="employed")
414
+ )
415
+ """
416
+ return Rename(self, **columns)
417
+
418
+ def sample(self, probability: float) -> "Sample":
419
+ """The ``SAMPLE`` command samples a fraction of the table rows.
420
+
421
+ :param probability: The probability that a row is included in the sample. The value
422
+ must be between 0 and 1, exclusive.
423
+
424
+ Examples::
425
+
426
+ query = ESQL.from_("employees").keep("emp_no").sample(0.05)
427
+ """
428
+ return Sample(self, probability)
429
+
430
+ def sort(self, *columns: FieldType) -> "Sort":
431
+ """The ``SORT`` processing command sorts a table on one or more columns.
432
+
433
+ :param columns: The columns to sort on.
434
+
435
+ Examples::
436
+
437
+ query1 = (
438
+ ESQL.from_("employees")
439
+ .keep("first_name", "last_name", "height")
440
+ .sort("height")
441
+ )
442
+ query2 = (
443
+ ESQL.from_("employees")
444
+ .keep("first_name", "last_name", "height")
445
+ .sort("height DESC")
446
+ )
447
+ query3 = (
448
+ ESQL.from_("employees")
449
+ .keep("first_name", "last_name", "height")
450
+ .sort("height DESC", "first_name ASC")
451
+ )
452
+ query4 = (
453
+ ESQL.from_("employees")
454
+ .keep("first_name", "last_name", "height")
455
+ .sort("first_name ASC NULLS FIRST")
456
+ )
457
+ """
458
+ return Sort(self, *columns)
459
+
460
+ def stats(
461
+ self, *expressions: ExpressionType, **named_expressions: ExpressionType
462
+ ) -> "Stats":
463
+ """The ``STATS`` processing command groups rows according to a common value and
464
+ calculates one or more aggregated values over the grouped rows.
465
+
466
+ :param expressions: A list of expressions, given as positional arguments.
467
+ :param named_expressions: A list of expressions, given as keyword arguments. The
468
+ argument names are used for the returned aggregated values.
469
+
470
+ Note that only one of `expressions` and `named_expressions` must be provided.
471
+
472
+ Examples::
473
+
474
+ query1 = (
475
+ ESQL.from_("employees")
476
+ .stats(count=functions.count("emp_no")).by("languages")
477
+ .sort("languages")
478
+ )
479
+ query2 = (
480
+ ESQL.from_("employees")
481
+ .stats(avg_lang=functions.avg("languages"))
482
+ )
483
+ query3 = (
484
+ ESQL.from_("employees")
485
+ .stats(
486
+ avg_lang=functions.avg("languages"),
487
+ max_lang=functions.max("languages")
488
+ )
489
+ )
490
+ query4 = (
491
+ ESQL.from_("employees")
492
+ .stats(
493
+ avg50s=functions.avg("salary").where('birth_date < "1960-01-01"'),
494
+ avg60s=functions.avg("salary").where('birth_date >= "1960-01-01"'),
495
+ ).by("gender")
496
+ .sort("gender")
497
+ )
498
+ query5 = (
499
+ ESQL.from_("employees")
500
+ .eval(Ks="salary / 1000")
501
+ .stats(
502
+ under_40K=functions.count("*").where("Ks < 40"),
503
+ inbetween=functions.count("*").where("40 <= Ks AND Ks < 60"),
504
+ over_60K=functions.count("*").where("60 <= Ks"),
505
+ total=f.count("*")
506
+ )
507
+ )
508
+ query6 = (
509
+ ESQL.row(i=1, a=["a", "b"])
510
+ .stats(functions.min("i")).by("a")
511
+ .sort("a ASC")
512
+ )
513
+ query7 = (
514
+ ESQL.from_("employees")
515
+ .eval(hired=functions.date_format("hire_date", "yyyy"))
516
+ .stats(avg_salary=functions.avg("salary")).by("hired", "languages.long")
517
+ .eval(avg_salary=functions.round("avg_salary"))
518
+ .sort("hired", "languages.long")
519
+
520
+ )
521
+ """
522
+ return Stats(self, *expressions, **named_expressions)
523
+
524
+ def where(self, *expressions: ExpressionType) -> "Where":
525
+ """The ``WHERE`` processing command produces a table that contains all the rows
526
+ from the input table for which the provided condition evaluates to `true`.
527
+
528
+ :param expressions: A list of boolean expressions, given as positional arguments.
529
+ These expressions are combined with an ``AND`` logical operator.
530
+
531
+ Examples::
532
+
533
+ query1 = (
534
+ ESQL.from_("employees")
535
+ .keep("first_name", "last_name", "still_hired")
536
+ .where("still_hired == true")
537
+ )
538
+ query2 = (
539
+ ESQL.from_("sample_data")
540
+ .where("@timestamp > NOW() - 1 hour")
541
+ )
542
+ query3 = (
543
+ ESQL.from_("employees")
544
+ .keep("first_name", "last_name", "height")
545
+ .where("LENGTH(first_name) < 4")
546
+ )
547
+ """
548
+ return Where(self, *expressions)
549
+
550
+
551
+ class From(ESQLBase):
552
+ """Implementation of the ``FROM`` source command.
553
+
554
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
555
+ to make it possible to chain all the commands that belong to an ES|QL query
556
+ in a single expression.
557
+ """
558
+
559
+ def __init__(self, *indices: IndexType):
560
+ super().__init__()
561
+ self._indices = indices
562
+ self._metadata_fields: Tuple[FieldType, ...] = tuple()
563
+
564
+ def metadata(self, *fields: FieldType) -> "From":
565
+ """Continuation of the ``FROM`` source command.
566
+
567
+ :param fields: metadata fields to retrieve, given as positional arguments.
568
+ """
569
+ self._metadata_fields = fields
570
+ return self
571
+
572
+ def _render_internal(self) -> str:
573
+ indices = [
574
+ index if isinstance(index, str) else index._index._name
575
+ for index in self._indices
576
+ ]
577
+ s = f'{self.__class__.__name__.upper()} {", ".join(indices)}'
578
+ if self._metadata_fields:
579
+ s = (
580
+ s
581
+ + f' METADATA {", ".join([str(field) for field in self._metadata_fields])}'
582
+ )
583
+ return s
584
+
585
+
586
+ class Row(ESQLBase):
587
+ """Implementation of the ``ROW`` source command.
588
+
589
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
590
+ to make it possible to chain all the commands that belong to an ES|QL query
591
+ in a single expression.
592
+ """
593
+
594
+ def __init__(self, **params: ExpressionType):
595
+ super().__init__()
596
+ self._params = {
597
+ k: json.dumps(v) if not isinstance(v, InstrumentedExpression) else v
598
+ for k, v in params.items()
599
+ }
600
+
601
+ def _render_internal(self) -> str:
602
+ return "ROW " + ", ".join([f"{k} = {v}" for k, v in self._params.items()])
603
+
604
+
605
+ class Show(ESQLBase):
606
+ """Implementation of the ``SHOW`` source command.
607
+
608
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
609
+ which makes it possible to chain all the commands that belong to an ES|QL query
610
+ in a single expression.
611
+ """
612
+
613
+ def __init__(self, item: str):
614
+ super().__init__()
615
+ self._item = item
616
+
617
+ def _render_internal(self) -> str:
618
+ return f"SHOW {self._item}"
619
+
620
+
621
+ class Branch(ESQLBase):
622
+ """Implementation of a branch inside a ``FORK`` processing command.
623
+
624
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
625
+ which makes it possible to chain all the commands that belong to the branch
626
+ in a single expression.
627
+ """
628
+
629
+ def _render_internal(self) -> str:
630
+ return ""
631
+
632
+
633
+ class ChangePoint(ESQLBase):
634
+ """Implementation of the ``CHANGE POINT`` processing command.
635
+
636
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
637
+ to make it possible to chain all the commands that belong to an ES|QL query
638
+ in a single expression.
639
+ """
640
+
641
+ def __init__(self, parent: ESQLBase, value: FieldType):
642
+ super().__init__(parent)
643
+ self._value = value
644
+ self._key: Optional[FieldType] = None
645
+ self._type_name: Optional[str] = None
646
+ self._pvalue_name: Optional[str] = None
647
+
648
+ def on(self, key: FieldType) -> "ChangePoint":
649
+ """Continuation of the `CHANGE_POINT` command.
650
+
651
+ :param key: The column with the key to order the values by. If not specified,
652
+ `@timestamp` is used.
653
+ """
654
+ self._key = key
655
+ return self
656
+
657
+ def as_(self, type_name: str, pvalue_name: str) -> "ChangePoint":
658
+ """Continuation of the `CHANGE_POINT` command.
659
+
660
+ :param type_name: The name of the output column with the change point type.
661
+ If not specified, `type` is used.
662
+ :param pvalue_name: The name of the output column with the p-value that indicates
663
+ how extreme the change point is. If not specified, `pvalue` is used.
664
+ """
665
+ self._type_name = type_name
666
+ self._pvalue_name = pvalue_name
667
+ return self
668
+
669
+ def _render_internal(self) -> str:
670
+ key = "" if not self._key else f" ON {self._key}"
671
+ names = (
672
+ ""
673
+ if not self._type_name and not self._pvalue_name
674
+ else f' AS {self._type_name or "type"}, {self._pvalue_name or "pvalue"}'
675
+ )
676
+ return f"CHANGE_POINT {self._value}{key}{names}"
677
+
678
+
679
+ class Completion(ESQLBase):
680
+ """Implementation of the ``COMPLETION`` processing command.
681
+
682
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
683
+ to make it possible to chain all the commands that belong to an ES|QL query
684
+ in a single expression.
685
+ """
686
+
687
+ def __init__(
688
+ self, parent: ESQLBase, *prompt: ExpressionType, **named_prompt: ExpressionType
689
+ ):
690
+ if len(prompt) + len(named_prompt) > 1:
691
+ raise ValueError(
692
+ "this method requires either one positional or one keyword argument only"
693
+ )
694
+ super().__init__(parent)
695
+ self._prompt = prompt
696
+ self._named_prompt = named_prompt
697
+ self._inference_id: Optional[str] = None
698
+
699
+ def with_(self, inference_id: str) -> "Completion":
700
+ """Continuation of the `COMPLETION` command.
701
+
702
+ :param inference_id: The ID of the inference endpoint to use for the task. The
703
+ inference endpoint must be configured with the completion
704
+ task type.
705
+ """
706
+ self._inference_id = inference_id
707
+ return self
708
+
709
+ def _render_internal(self) -> str:
710
+ if self._inference_id is None:
711
+ raise ValueError("The completion command requires an inference ID")
712
+ if self._named_prompt:
713
+ column = list(self._named_prompt.keys())[0]
714
+ prompt = list(self._named_prompt.values())[0]
715
+ return f"COMPLETION {column} = {prompt} WITH {self._inference_id}"
716
+ else:
717
+ return f"COMPLETION {self._prompt[0]} WITH {self._inference_id}"
718
+
719
+
720
+ class Dissect(ESQLBase):
721
+ """Implementation of the ``DISSECT`` processing command.
722
+
723
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
724
+ to make it possible to chain all the commands that belong to an ES|QL query
725
+ in a single expression.
726
+ """
727
+
728
+ def __init__(self, parent: ESQLBase, input: FieldType, pattern: str):
729
+ super().__init__(parent)
730
+ self._input = input
731
+ self._pattern = pattern
732
+ self._separator: Optional[str] = None
733
+
734
+ def append_separator(self, separator: str) -> "Dissect":
735
+ """Continuation of the ``DISSECT`` command.
736
+
737
+ :param separator: A string used as the separator between appended values,
738
+ when using the append modifier.
739
+ """
740
+ self._separator = separator
741
+ return self
742
+
743
+ def _render_internal(self) -> str:
744
+ sep = (
745
+ "" if self._separator is None else f' APPEND_SEPARATOR="{self._separator}"'
746
+ )
747
+ return f"DISSECT {self._input} {json.dumps(self._pattern)}{sep}"
748
+
749
+
750
+ class Drop(ESQLBase):
751
+ """Implementation of the ``DROP`` processing command.
752
+
753
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
754
+ to make it possible to chain all the commands that belong to an ES|QL query
755
+ in a single expression.
756
+ """
757
+
758
+ def __init__(self, parent: ESQLBase, *columns: FieldType):
759
+ super().__init__(parent)
760
+ self._columns = columns
761
+
762
+ def _render_internal(self) -> str:
763
+ return f'DROP {", ".join([str(col) for col in self._columns])}'
764
+
765
+
766
+ class Enrich(ESQLBase):
767
+ """Implementation of the ``ENRICH`` processing command.
768
+
769
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
770
+ to make it possible to chain all the commands that belong to an ES|QL query
771
+ in a single expression.
772
+ """
773
+
774
+ def __init__(self, parent: ESQLBase, policy: str):
775
+ super().__init__(parent)
776
+ self._policy = policy
777
+ self._match_field: Optional[FieldType] = None
778
+ self._fields: Optional[Tuple[FieldType, ...]] = None
779
+ self._named_fields: Optional[Dict[str, FieldType]] = None
780
+
781
+ def on(self, match_field: FieldType) -> "Enrich":
782
+ """Continuation of the ``ENRICH`` command.
783
+
784
+ :param match_field: The match field. ``ENRICH`` uses its value to look for records
785
+ in the enrich index. If not specified, the match will be
786
+ performed on the column with the same name as the
787
+ `match_field` defined in the enrich policy.
788
+ """
789
+ self._match_field = match_field
790
+ return self
791
+
792
+ def with_(self, *fields: FieldType, **named_fields: FieldType) -> "Enrich":
793
+ """Continuation of the ``ENRICH`` command.
794
+
795
+ :param fields: The enrich fields from the enrich index that are added to the result
796
+ as new columns, given as positional arguments. If a column with the
797
+ same name as the enrich field already exists, the existing column will
798
+ be replaced by the new column. If not specified, each of the enrich
799
+ fields defined in the policy is added. A column with the same name as
800
+ the enrich field will be dropped unless the enrich field is renamed.
801
+ :param named_fields: The enrich fields from the enrich index that are added to the
802
+ result as new columns, given as keyword arguments. The name of
803
+ the keyword arguments are used as column names. If a column has
804
+ the same name as the new name, it will be discarded. If a name
805
+ (new or original) occurs more than once, only the rightmost
806
+ duplicate creates a new column.
807
+ """
808
+ if fields and named_fields:
809
+ raise ValueError(
810
+ "this method supports positional or keyword arguments but not both"
811
+ )
812
+ self._fields = fields
813
+ self._named_fields = named_fields
814
+ return self
815
+
816
+ def _render_internal(self) -> str:
817
+ on = "" if self._match_field is None else f" ON {self._match_field}"
818
+ with_ = ""
819
+ if self._named_fields:
820
+ with_ = f' WITH {", ".join([f"{name} = {field}" for name, field in self._named_fields.items()])}'
821
+ elif self._fields is not None:
822
+ with_ = f' WITH {", ".join([str(field) for field in self._fields])}'
823
+ return f"ENRICH {self._policy}{on}{with_}"
824
+
825
+
826
+ class Eval(ESQLBase):
827
+ """Implementation of the ``EVAL`` processing command.
828
+
829
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
830
+ to make it possible to chain all the commands that belong to an ES|QL query
831
+ in a single expression.
832
+ """
833
+
834
+ def __init__(
835
+ self, parent: ESQLBase, *columns: FieldType, **named_columns: FieldType
836
+ ):
837
+ if columns and named_columns:
838
+ raise ValueError(
839
+ "this method supports positional or keyword arguments but not both"
840
+ )
841
+ super().__init__(parent)
842
+ self._columns = columns or named_columns
843
+
844
+ def _render_internal(self) -> str:
845
+ if isinstance(self._columns, dict):
846
+ cols = ", ".join(
847
+ [f"{name} = {value}" for name, value in self._columns.items()]
848
+ )
849
+ else:
850
+ cols = ", ".join([f"{col}" for col in self._columns])
851
+ return f"EVAL {cols}"
852
+
853
+
854
+ class Fork(ESQLBase):
855
+ """Implementation of the ``FORK`` processing command.
856
+
857
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
858
+ to make it possible to chain all the commands that belong to an ES|QL query
859
+ in a single expression.
860
+ """
861
+
862
+ def __init__(
863
+ self,
864
+ parent: ESQLBase,
865
+ fork1: ESQLBase,
866
+ fork2: Optional[ESQLBase] = None,
867
+ fork3: Optional[ESQLBase] = None,
868
+ fork4: Optional[ESQLBase] = None,
869
+ fork5: Optional[ESQLBase] = None,
870
+ fork6: Optional[ESQLBase] = None,
871
+ fork7: Optional[ESQLBase] = None,
872
+ fork8: Optional[ESQLBase] = None,
873
+ ):
874
+ super().__init__(parent)
875
+ self._branches = [fork1, fork2, fork3, fork4, fork5, fork6, fork7, fork8]
876
+
877
+ def _render_internal(self) -> str:
878
+ cmds = ""
879
+ for branch in self._branches:
880
+ if branch:
881
+ cmd = branch.render()[3:].replace("\n", " ")
882
+ if cmds == "":
883
+ cmds = f"( {cmd} )"
884
+ else:
885
+ cmds += f"\n ( {cmd} )"
886
+ return f"FORK {cmds}"
887
+
888
+
889
+ class Grok(ESQLBase):
890
+ """Implementation of the ``GROK`` processing command.
891
+
892
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
893
+ to make it possible to chain all the commands that belong to an ES|QL query
894
+ in a single expression.
895
+ """
896
+
897
+ def __init__(self, parent: ESQLBase, input: FieldType, pattern: str):
898
+ super().__init__(parent)
899
+ self._input = input
900
+ self._pattern = pattern
901
+
902
+ def _render_internal(self) -> str:
903
+ return f"GROK {self._input} {json.dumps(self._pattern)}"
904
+
905
+
906
+ class Keep(ESQLBase):
907
+ """Implementation of the ``KEEP`` processing command.
908
+
909
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
910
+ to make it possible to chain all the commands that belong to an ES|QL query
911
+ in a single expression.
912
+ """
913
+
914
+ def __init__(self, parent: ESQLBase, *columns: FieldType):
915
+ super().__init__(parent)
916
+ self._columns = columns
917
+
918
+ def _render_internal(self) -> str:
919
+ return f'KEEP {", ".join([f"{col}" for col in self._columns])}'
920
+
921
+
922
+ class Limit(ESQLBase):
923
+ """Implementation of the ``LIMIT`` processing command.
924
+
925
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
926
+ to make it possible to chain all the commands that belong to an ES|QL query
927
+ in a single expression.
928
+ """
929
+
930
+ def __init__(self, parent: ESQLBase, max_number_of_rows: int):
931
+ super().__init__(parent)
932
+ self._max_number_of_rows = max_number_of_rows
933
+
934
+ def _render_internal(self) -> str:
935
+ return f"LIMIT {self._max_number_of_rows}"
936
+
937
+
938
+ class LookupJoin(ESQLBase):
939
+ """Implementation of the ``LOOKUP JOIN`` processing command.
940
+
941
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
942
+ to make it possible to chain all the commands that belong to an ES|QL query
943
+ in a single expression.
944
+ """
945
+
946
+ def __init__(self, parent: ESQLBase, lookup_index: IndexType):
947
+ super().__init__(parent)
948
+ self._lookup_index = lookup_index
949
+ self._field: Optional[FieldType] = None
950
+
951
+ def on(self, field: FieldType) -> "LookupJoin":
952
+ """Continuation of the `LOOKUP_JOIN` command.
953
+
954
+ :param field: The field to join on. This field must exist in both your current query
955
+ results and in the lookup index. If the field contains multi-valued
956
+ entries, those entries will not match anything (the added fields will
957
+ contain null for those rows).
958
+ """
959
+ self._field = field
960
+ return self
961
+
962
+ def _render_internal(self) -> str:
963
+ if self._field is None:
964
+ raise ValueError("Joins require a field to join on.")
965
+ index = (
966
+ self._lookup_index
967
+ if isinstance(self._lookup_index, str)
968
+ else self._lookup_index._index._name
969
+ )
970
+ return f"LOOKUP JOIN {index} ON {self._field}"
971
+
972
+
973
+ class MvExpand(ESQLBase):
974
+ """Implementation of the ``MV_EXPAND`` processing command.
975
+
976
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
977
+ to make it possible to chain all the commands that belong to an ES|QL query
978
+ in a single expression.
979
+ """
980
+
981
+ def __init__(self, parent: ESQLBase, column: FieldType):
982
+ super().__init__(parent)
983
+ self._column = column
984
+
985
+ def _render_internal(self) -> str:
986
+ return f"MV_EXPAND {self._column}"
987
+
988
+
989
+ class Rename(ESQLBase):
990
+ """Implementation of the ``RENAME`` processing command.
991
+
992
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
993
+ to make it possible to chain all the commands that belong to an ES|QL query
994
+ in a single expression.
995
+ """
996
+
997
+ def __init__(self, parent: ESQLBase, **columns: FieldType):
998
+ super().__init__(parent)
999
+ self._columns = columns
1000
+
1001
+ def _render_internal(self) -> str:
1002
+ return f'RENAME {", ".join([f"{old_name} AS {new_name}" for old_name, new_name in self._columns.items()])}'
1003
+
1004
+
1005
+ class Sample(ESQLBase):
1006
+ """Implementation of the ``SAMPLE`` processing command.
1007
+
1008
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
1009
+ to make it possible to chain all the commands that belong to an ES|QL query
1010
+ in a single expression.
1011
+ """
1012
+
1013
+ def __init__(self, parent: ESQLBase, probability: float):
1014
+ super().__init__(parent)
1015
+ self._probability = probability
1016
+
1017
+ def _render_internal(self) -> str:
1018
+ return f"SAMPLE {self._probability}"
1019
+
1020
+
1021
+ class Sort(ESQLBase):
1022
+ """Implementation of the ``SORT`` processing command.
1023
+
1024
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
1025
+ to make it possible to chain all the commands that belong to an ES|QL query
1026
+ in a single expression.
1027
+ """
1028
+
1029
+ def __init__(self, parent: ESQLBase, *columns: FieldType):
1030
+ super().__init__(parent)
1031
+ self._columns = columns
1032
+
1033
+ def _render_internal(self) -> str:
1034
+ return f'SORT {", ".join([f"{col}" for col in self._columns])}'
1035
+
1036
+
1037
+ class Stats(ESQLBase):
1038
+ """Implementation of the ``STATS`` processing command.
1039
+
1040
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
1041
+ to make it possible to chain all the commands that belong to an ES|QL query
1042
+ in a single expression.
1043
+ """
1044
+
1045
+ def __init__(
1046
+ self,
1047
+ parent: ESQLBase,
1048
+ *expressions: ExpressionType,
1049
+ **named_expressions: ExpressionType,
1050
+ ):
1051
+ if expressions and named_expressions:
1052
+ raise ValueError(
1053
+ "this method supports positional or keyword arguments but not both"
1054
+ )
1055
+ super().__init__(parent)
1056
+ self._expressions = expressions or named_expressions
1057
+ self._grouping_expressions: Optional[Tuple[ExpressionType, ...]] = None
1058
+
1059
+ def by(self, *grouping_expressions: ExpressionType) -> "Stats":
1060
+ self._grouping_expressions = grouping_expressions
1061
+ return self
1062
+
1063
+ def _render_internal(self) -> str:
1064
+ if isinstance(self._expressions, dict):
1065
+ exprs = [f"{key} = {value}" for key, value in self._expressions.items()]
1066
+ else:
1067
+ exprs = [f"{expr}" for expr in self._expressions]
1068
+ expression_separator = ",\n "
1069
+ by = (
1070
+ ""
1071
+ if self._grouping_expressions is None
1072
+ else f'\n BY {", ".join([f"{expr}" for expr in self._grouping_expressions])}'
1073
+ )
1074
+ return f'STATS {expression_separator.join([f"{expr}" for expr in exprs])}{by}'
1075
+
1076
+
1077
+ class Where(ESQLBase):
1078
+ """Implementation of the ``WHERE`` processing command.
1079
+
1080
+ This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
1081
+ to make it possible to chain all the commands that belong to an ES|QL query
1082
+ in a single expression.
1083
+ """
1084
+
1085
+ def __init__(self, parent: ESQLBase, *expressions: ExpressionType):
1086
+ super().__init__(parent)
1087
+ self._expressions = expressions
1088
+
1089
+ def _render_internal(self) -> str:
1090
+ return f'WHERE {" AND ".join([f"{expr}" for expr in self._expressions])}'
1091
+
1092
+
1093
+ def and_(*expressions: InstrumentedExpression) -> "InstrumentedExpression":
1094
+ """Combine two or more expressions with the AND operator."""
1095
+ return InstrumentedExpression(" AND ".join([f"({expr})" for expr in expressions]))
1096
+
1097
+
1098
+ def or_(*expressions: InstrumentedExpression) -> "InstrumentedExpression":
1099
+ """Combine two or more expressions with the OR operator."""
1100
+ return InstrumentedExpression(" OR ".join([f"({expr})" for expr in expressions]))
1101
+
1102
+
1103
+ def not_(expression: InstrumentedExpression) -> "InstrumentedExpression":
1104
+ """Negate an expression."""
1105
+ return InstrumentedExpression(f"NOT ({expression})")