
    j                       d dl Z d dlZd dlmZmZ d dlmZmZmZm	Z	m
Z
mZmZ ddlmZmZmZ eeef   Zeee   ef   ZeZ G d de      Z G d d	e      Z G d
 de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z  G d de      Z! G d  d!e      Z" G d" d#e      Z# G d$ d%e      Z$ G d& d'e      Z% G d( d)e      Z& G d* d+e      Z' G d, d-e      Z( G d. d/e      Z) G d0 d1e      Z* G d2 d3e      Z+ G d4 d5e      Z, G d6 d7e      Z- G d8 d9e      Z. G d: d;e      Z/ G d< d=e      Z0 G d> d?e      Z1 G d@ dAe1      Z2 G dB dCe      Z3 G dD dEe      Z4 G dF dGe      Z5 G dH dIe      Z6dJedKdLfdMZ7dJedKdLfdNZ8dOedKdLfdPZ9y)Q    N)ABCabstractmethod)AnyDictListOptionalTupleTypeUnion   )DocumentBaseInstrumentedExpressionInstrumentedFieldc                       e Zd ZdZededdfd       Zededdfd       Zed	e	dd
fd       Z
ededdfd       Zedd       Zy)ESQLzThe static methods of the ``ESQL`` class provide access to the ES|QL source
    commands, used to create ES|QL queries.

    These methods return an instance of class ``ESQLBase``, which provides access to
    the ES|QL processing commands.
    indicesreturnFromc                      t        |  S )a#  The ``FROM`` source command returns a table with data from a data stream, index, or alias.

        :param indices: A list of indices, data streams or aliases. Supports wildcards and date math.

        Examples::

            query1 = ESQL.from_("employees")
            query2 = ESQL.from_("<logs-{now/d}>")
            query3 = ESQL.from_("employees-00001", "other-employees-*")
            query4 = ESQL.from_("cluster_one:employees-00001", "cluster_two:other-employees-*")
            query5 = ESQL.from_("employees").metadata("_id")
        )r   r   s    v/var/www/internaltesting/Shamanth/prverification/HIS_auto/venv/lib/python3.12/site-packages/elasticsearch/esql/esql.pyfrom_z
ESQL.from_&   s     W~    paramsRowc                      t        di | S )a  The ``ROW`` source command produces a row with one or more columns with values that you specify.
        This can be useful for testing.

        :param params: the column values to produce, given as keyword arguments.

        Examples::

            query1 = ESQL.row(a=1, b="two", c=None)
            query2 = ESQL.row(a=[1, 2])
            query3 = ESQL.row(a=functions.round(1.23, 0))
         )r   )r   s    r   rowzESQL.row6   s     }V}r   itemShowc                     t        |       S )zThe ``SHOW`` source command returns information about the deployment and its capabilities.

        :param item: Can only be ``INFO``.

        Examples::

            query = ESQL.show("INFO")
        )r    )r   s    r   showz	ESQL.showE   s     Dzr   TSc                      t        |  S )a  The ``TS`` source command is similar to ``FROM``, but for time series indices.

        :param indices: A list of indices, data streams or aliases. Supports wildcards and date math.

        Examples::

            query = (
                ESQL.ts("metrics")
                .where("@timestamp >= now() - 1 day")
                .stats("SUM(AVG_OVER_TIME(memory_usage)").by("host", "TBUCKET(1 hour)")
            )
        )r#   r   s    r   tszESQL.tsQ   s     7|r   c                      t               S )a  This method can only be used inside a ``FORK`` command to create each branch.

        Examples::

            query = ESQL.from_("employees").fork(
                ESQL.branch().where("emp_no == 10001"),
                ESQL.branch().where("emp_no == 10002"),
            )
        )Branchr   r   r   branchzESQL.brancha   s     xr   N)r   r'   )__name__
__module____qualname____doc__staticmethod	IndexTyper   ExpressionTyper   strr"   r%   r(   r   r   r   r   r      s     	 f   n    	3 	6 	 	 Y 4   
 
r   r   c                      e Zd ZdZdbded    fdZdefdZdefdZe	defd       Z
ed	edefd
       Zedcdededefd       Zededefd       ZdefdZdddZdedd fdZdeddfdZdededdfdZdededdfdZdedd fd!Zd"edd#fd$Zded%edd&fd'Z	 	 	 	 	 	 	 ded(d)d*ed)   d+ed)   d,ed)   d-ed)   d.ed)   d/ed)   d0ed)   dd1fd2Zdbd3ee   dd4fd5Zdededd6fd7Zd8ed9edd:fd;Zdedd<fd=Z d>e!dd?fd@Z"dAeddBfdCZ#dfdDZ$dbdEedFeddGfdHZ%dIeddJfdKZ&dLeddMfdNZ'deddOfdPZ(dQedReddSfdTZ)dUe*ddVfdWZ+deddXfdYZ,d8ed9edd:fdZZ-dgd[Z.dLedd\fd]Z/dLedd^fd_Z0d8edd`fdaZ1y)hESQLBasez|The methods of the ``ESQLBase`` class provide access to the ES|QL processing
    commands, used to build ES|QL queries.
    Nparentc                      || _         g | _        y N)_parent_directives)selfr3   s     r   __init__zESQLBase.__init__t   s    -/r   r   c                 "    | j                         S r5   )renderr8   s    r   __repr__zESQLBase.__repr__x   s    {{}r   c                    | j                   r| j                   j                         dz   }n>dj                  | j                  D cg c]  }|j	                          c}      }|r|dz  }|| j	                         z   S c c}w )Nz
| z;
)r6   r;   joinr7   _render_internal)r8   rds      r   r;   zESQLBase.render{   sn    <<##%.A

$:J:JKQA..0KLAU
4((*** Ls   A<c                      y r5   r   r<   s    r   r@   zESQLBase._render_internal   s    r   indexc                 \    t        | d      r| j                  j                  S t        |       S )N_index)hasattrrF   _namer0   )rD   s    r   _format_indexzESQLBase._format_index   s$    %,UH%=u||!!M3u:Mr   idallow_patternsc                     t        |       }|rd|v r|S t        j                  d|      r|S |j                  dd      }d| dS )N*z[a-zA-Z_@][a-zA-Z0-9_\.]*`z``)r0   re	fullmatchreplace)rJ   rK   ss      r   
_format_idzESQLBase._format_id   sJ    GcQhH<<4a8HIIc4 1#Qxr   exprc                 n    t        | t        t        f      st        j                  |       S t        |       S r5   )
isinstancer0   r   jsondumps)rT   s    r   _format_exprzESQLBase._format_expr   s5     dS*@$AB JJt	
 T	
r   c                     | j                   j                  dk(  ry| j                  r| j                  j                         S y)NForkTF)	__class__r)   r6   
_is_forkedr<   s    r   r]   zESQLBase._is_forked   s4    >>""f,<<<<**,,r   c                     | j                   r| j                   j                  |       y | j                  j                  |       y r5   )r6   _add_directiver7   append)r8   	directives     r   r_   zESQLBase._add_directive   s/    <<LL''	2##I.r   r   c                 :    | j                  t        di |       | S )a  The ``SET`` directive can be used to specify query settings that
        modify the behavior of an ES|QL query.

        Examples::

            query1 = (
                ESQL.from_("many_numbers")
                .stats(sum="SUM(sv)")
                .set(approximation=True)
            )
            query2 = (
                ESQL.from_("many_numbers")
                .stats(median="MEDIAN(sv)")
                .set(approximation={"rows": 10000})
            )
        r   )r_   Set)r8   r   s     r   setzESQLBase.set   s    " 	CM&M*r   valueChangePointc                     t        | |      S )a  ``CHANGE_POINT`` detects spikes, dips, and change points in a metric.

        :param value: The column with the metric in which you want to detect a change point.

        Examples::

            query = (
                ESQL.row(key=list(range(1, 26)))
                .mv_expand("key")
                .eval(value=functions.case("key<13", 0, 42))
                .change_point("value").on("key")
                .where("type IS NOT NULL")
            )
        )rf   )r8   re   s     r   change_pointzESQLBase.change_point   s     4''r   promptnamed_prompt
Completionc                      t        | g|i |S )aE  The ``COMPLETION`` command allows you to send prompts and context to a Large
        Language Model (LLM) directly within your ES|QL queries, to perform text
        generation tasks.

        :param prompt: The input text or expression used to prompt the LLM. This can
                       be a string literal or a reference to a column containing text.
        :param named_prompt: The input text or expresion, given as a keyword argument.
                             The argument name is used for the column name. If the
                             prompt is given as a positional argument, the results will
                             be stored in a column named ``completion``. If the
                             specified column already exists, it will be overwritten
                             with the new results.

        Examples::

            query1 = (
                ESQL.row(question="What is Elasticsearch?")
                .completion("question").with_("test_completion_model")
                .keep("question", "completion")
            )
            query2 = (
                ESQL.row(question="What is Elasticsearch?")
                .completion(answer="question").with_("test_completion_model")
                .keep("question", "answer")
            )
            query3 = (
                ESQL.from_("movies")
                .sort("rating DESC")
                .limit(10)
                .eval(prompt="""CONCAT(
                    "Summarize this movie using the following information: \n",
                    "Title: ", title, "\n",
                    "Synopsis: ", synopsis, "\n",
                    "Actors: ", MV_CONCAT(actors, ", "), "\n",
                )""")
                .completion(summary="prompt").with_("test_completion_model")
                .keep("title", "summary", "rating")
            )
        )rk   )r8   ri   rj   s      r   
completionzESQLBase.completion   s    T $88<88r   inputpatternDissectc                     t        | ||      S )a  ``DISSECT`` enables you to extract structured data out of a string.

        :param input: The column that contains the string you want to structure. If
                      the column has multiple values, ``DISSECT`` will process each value.
        :param pattern: A dissect pattern. If a field name conflicts with an existing
                        column, the existing column is dropped. If a field name is used
                        more than once, only the rightmost duplicate creates a column.

        Examples::

            query = (
                ESQL.row(a="2023-01-23T12:15:00.000Z - some text - 127.0.0.1")
                .dissect("a", "%{date} - %{msg} - %{ip}")
                .keep("date", "msg", "ip")
                .eval(date="TO_DATETIME(date)")
            )
        )rp   r8   rn   ro   s      r   dissectzESQLBase.dissect   s    $ tUG,,r   columnsDropc                     t        | g| S )a4  The ``DROP`` processing command removes one or more columns.

        :param columns: The columns to drop, given as positional arguments. Supports wildcards.

        Examples::

            query1 = ESQL.from_("employees").drop("height")
            query2 = ESQL.from_("employees").drop("height*")
        )ru   r8   rt   s     r   dropzESQLBase.drop  s     D#7##r   policyEnrichc                     t        | |      S )a0  ``ENRICH`` enables you to add data from existing indices as new columns using an
        enrich policy.

        :param policy: The name of the enrich policy. You need to create and execute the
                       enrich policy first.

        Examples::

            query1 = (
                ESQL.row(a="1")
                .enrich("languages_policy").on("a").with_("language_name")
            )
            query2 = (
                ESQL.row(a="1")
                .enrich("languages_policy").on("a").with_(name="language_name")
            )
        )rz   )r8   ry   s     r   enrichzESQLBase.enrich  s    $ dF##r   named_columnsEvalc                      t        | g|i |S )a{  The ``EVAL`` processing command enables you to append new columns with calculated values.

        :param columns: The values for the columns, given as positional arguments. Can be literals,
                        expressions, or functions. Can use columns defined left of this one.
        :param named_columns: The values for the new columns, given as keyword arguments. The name
                              of the arguments is used as column name. If a column with the same
                              name already exists, the existing column is dropped. If a column name
                              is used more than once, only the rightmost duplicate creates a column.

        Examples::

            query1 = (
                ESQL.from_("employees")
                .sort("emp_no")
                .keep("first_name", "last_name", "height")
                .eval(height_feet="height * 3.281", height_cm="height * 100")
            )
            query2 = (
                ESQL.from_("employees")
                .eval("height * 3.281")
                .stats(avg_height_feet=functions.avg("`height * 3.281`"))
            )
        )r~   )r8   rt   r}   s      r   evalzESQLBase.eval1  s    0 D474m44r   fork1r'   fork2fork3fork4fork5fork6fork7fork8r[   c	                 ^    | j                         rt        d      t        | ||||||||	      S )aT  The ``FORK`` processing command creates multiple execution branches to operate on the
        same input data and combines the results in a single output table.

        :param fork<n>: Up to 8 execution branches, created with the ``ESQL.branch()`` method.

        Examples::

            query = (
                ESQL.from_("employees")
                .fork(
                    ESQL.branch().where("emp_no == 10001"),
                    ESQL.branch().where("emp_no == 10002"),
                )
                .keep("emp_no", "_fork")
                .sort("emp_no")
            )
        za query can only have one fork)r]   
ValueErrorr[   )	r8   r   r   r   r   r   r   r   r   s	            r   forkzESQLBase.forkK  s5    8 ??=>>D%ueUE5QQr   methodFusec                     t        | |      S )aV  The ``FUSE`` processing command merges rows from multiple result sets and assigns
        new relevance scores.

        :param method: Defaults to ``RRF``. Can be one of ``RRF`` (for Reciprocal Rank Fusion)
                       or ``LINEAR`` (for linear combination of scores). Designates which
                       method to use to assign new relevance scores.

        Examples::

            query1 = (
                ESQL.from_("books").metadata("_id", "_index", "_score")
                .fork(
                    ESQL.branch().where('title:"Shakespeare"').sort("_score DESC"),
                    ESQL.branch().where('semantic_title:"Shakespeare"').sort("_score DESC"),
                )
                .fuse()
            )
            query2 = (
                ESQL.from_("books").metadata("_id", "_index", "_score")
                .fork(
                    ESQL.branch().where('title:"Shakespeare"').sort("_score DESC"),
                    ESQL.branch().where('semantic_title:"Shakespeare"').sort("_score DESC"),
                )
                .fuse("linear")
            )
            query3 = (
                ESQL.from_("books").metadata("_id", "_index", "_score")
                .fork(
                    ESQL.branch().where('title:"Shakespeare"').sort("_score DESC"),
                    ESQL.branch().where('semantic_title:"Shakespeare"').sort("_score DESC"),
                )
                .fuse("linear").by("title", "description")
            )
            query4 = (
                ESQL.from_("books").metadata("_id", "_index", "_score")
                .fork(
                    ESQL.branch().where('title:"Shakespeare"').sort("_score DESC"),
                    ESQL.branch().where('semantic_title:"Shakespeare"').sort("_score DESC"),
                )
                .fuse("linear").with_(normalizer="minmax")
            )
        )r   )r8   r   s     r   fusezESQLBase.fusek  s    V D&!!r   Grokc                     t        | ||      S )a  ``GROK`` enables you to extract structured data out of a string.

        :param input: The column that contains the string you want to structure. If the
                      column has multiple values, ``GROK`` will process each value.
        :param pattern: A grok pattern. If a field name conflicts with an existing column,
                        the existing column is discarded. If a field name is used more than
                        once, a multi-valued column will be created with one value per each
                        occurrence of the field name.

        Examples::

            query1 = (
                ESQL.row(a="2023-01-23T12:15:00.000Z 127.0.0.1 some.email@foo.com 42")
                .grok("a", "%{TIMESTAMP_ISO8601:date} %{IP:ip} %{EMAILADDRESS:email} %{NUMBER:num}")
                .keep("date", "ip", "email", "num")
            )
            query2 = (
                ESQL.row(a="2023-01-23T12:15:00.000Z 127.0.0.1 some.email@foo.com 42")
                .grok(
                    "a",
                    "%{TIMESTAMP_ISO8601:date} %{IP:ip} %{EMAILADDRESS:email} %{NUMBER:num:int}",
                )
                .keep("date", "ip", "email", "num")
                .eval(date=functions.to_datetime("date"))
            )
            query3 = (
                ESQL.from_("addresses")
                .keep("city.name", "zip_code")
                .grok("zip_code", "%{WORD:zip_parts} %{WORD:zip_parts}")
            )
        )r   rr   s      r   grokzESQLBase.grok  s    @ D%))r   expressionsnamed_expressionsStatsc                      t        | g|i |S )a-  The ``INLINE STATS`` processing command groups rows according to a common value
        and calculates one or more aggregated values over the grouped rows.

        The command is identical to ``STATS`` except that it preserves all the columns from
        the input table.

        :param expressions: A list of expressions, given as positional arguments.
        :param named_expressions: A list of expressions, given as keyword arguments. The
                                  argument names are used for the returned aggregated values.

        Note that only one of ``expressions`` and ``named_expressions`` must be provided.

        Examples::

            query1 = (
                ESQL.from_("employees")
                .keep("emp_no", "languages", "salary")
                .inline_stats(max_salary=functions.max(E("salary"))).by("languages")
            )
            query2 = (
                ESQL.from_("employees")
                .keep("emp_no", "languages", "salary")
                .inline_stats(max_salary=functions.max(E("salary")))
            )
            query3 = (
                ESQL.from_("employees")
                .where("still_hired")
                .keep("emp_no", "languages", "salary", "hire_date")
                .eval(tenure=functions.date_diff("year", E("hire_date"), "2025-09-18T00:00:00"))
                .drop("hire_date")
                .inline_stats(
                    avg_salary=functions.avg(E("salary")),
                    count=functions.count(E("*")),
                )
                .by("languages", "tenure")
            )
            query4 = (
                ESQL.from_("employees")
                .keep("emp_no", "salary")
                .inline_stats(
                    avg_lt_50=functions.round(functions.avg(E("salary"))).where(E("salary") < 50000),
                    avg_lt_60=functions.round(functions.avg(E("salary"))).where(E("salary") >= 50000, E("salary") < 60000),
                    avg_gt_60=functions.round(functions.avg(E("salary"))).where(E("salary") >= 60000),
                )
            )

        )InlineStatsr8   r   r   s      r   inline_statszESQLBase.inline_stats  s    d 4C+C1BCCr   Keepc                     t        | g| S )a  The ``KEEP`` processing command enables you to specify what columns are returned
        and the order in which they are returned.

        :param columns: The columns to keep, given as positional arguments. Supports
                        wildcards.

        Examples::

            query1 = ESQL.from_("employees").keep("emp_no", "first_name", "last_name", "height")
            query2 = ESQL.from_("employees").keep("h*")
            query3 = ESQL.from_("employees").keep("h*", "*")
        )r   rw   s     r   keepzESQLBase.keep  s     D#7##r   max_number_of_rowsLimitc                     t        | |      S )av  The ``LIMIT`` processing command enables you to limit the number of rows that are
        returned.

        :param max_number_of_rows: The maximum number of rows to return.

        Examples::

            query1 = ESQL.from_("employees").sort("emp_no ASC").limit(5)
            query2 = ESQL.from_("index").stats(functions.avg("field1")).by("field2").limit(20000)
        )r   r8   r   s     r   limitzESQLBase.limit  s     T-..r   lookup_index
LookupJoinc                     t        | |      S )a%  ``LOOKUP JOIN`` enables you to add data from another index, AKA a 'lookup' index,
        to your ES|QL query results, simplifying data enrichment and analysis workflows.

        :param lookup_index: The name of the lookup index. This must be a specific index
                             name - wildcards, aliases, and remote cluster references are
                             not supported. Indices used for lookups must be configured
                             with the lookup index mode.

        Examples::

            query1 = (
                ESQL.from_("firewall_logs")
                .lookup_join("threat_list").on("source.IP")
                .where("threat_level IS NOT NULL")
            )
            query2 = (
                ESQL.from_("system_metrics")
                .lookup_join("host_inventory").on("host.name")
                .lookup_join("ownerships").on("host.name")
            )
            query3 = (
                ESQL.from_("app_logs")
                .lookup_join("service_owners").on("service_id")
            )
            query4 = (
                ESQL.from_("employees")
                .eval(language_code="languages")
                .where("emp_no >= 10091 AND emp_no < 10094")
                .lookup_join("languages_lookup").on("language_code")
            )
        )r   )r8   r   s     r   lookup_joinzESQLBase.lookup_join
  s    @ $--r   c                     t        |       S )a  The ``METRICS_INFO`` processing command retrieves information about
        the metrics available in time series data streams, along with their
        applicable dimensions and other metadata.

        Examples::

            query1 = (
                ESQL.ts("k8s")
                .metrics_info()
                .sort("metric_name")
            )
            query2 = (
                ESQL.ts("k8s")
                .where("cluster == "prod"")
                .metrics_info()
                .sort("metric_name")
            )
        )MetricsInfor<   s    r   metrics_infozESQLBase.metrics_info,  s    & 4  r   fieldquery_vectorMmrc                     t        | ||      S )a;  The ``MMR`` command reduces the result set from a set of input rows by
        applying a diversification strategy to the return rows.

        :param field: The name of the field that will use its values for the
                      diversification process. The field must be a dense_vector
                      type.
        :param query_vector: The query vector to use as part of the
                             diversification algorithm for comparison. Must have
                             the same number of dimensions as the vector field
                             you are searching against.

        Examples::

            query1 = (
                ESQL.from_("mmr_text_vector_keyword")
                .sort("keyword_field")
                .limit(10)
                .mmr("text_vector").mmr_limit(3)
                .drop("text_vector", "byte_vector", "bit_vector")
            )
            query2 = (
                ESQL.from_("mmr_text_vector_keyword")
                .sort("keyword_field")
                .limit(10)
                .mmr("text_vector", [0.1, 0.2, 0.3]).mmr_limit(3).with_(lambda_=0.1)
                .drop("text_vector", "byte_vector", "bit_vector")
            )
            query3 = (
                ESQL.from_("dense_vector_text").metadata("_score")
                .eval(query_embedding=functions.text_embedding("be excellent to each other", "test_dense_inference"))
                .where(functions.knn("text_embedding_field", "query_embedding"))
                .sort("_score DESC")
                .limit(10)
                .mmr(
                    "text_embedding_field",
                    functions.text_embedding("be excellent to each other", "test_dense_inference")
                ).mmr_limit(3).with_(lambda_=0.2)
                .keep("text_field", "query_embedding")
            )
        )r   )r8   r   r   s      r   mmrzESQLBase.mmrA  s    R 4--r   columnMvExpandc                     t        | |      S )a!  The ``MV_EXPAND`` processing command expands multivalued columns into one row per
        value, duplicating other columns.

        :param column: The multivalued column to expand.

        Examples::

            query = ESQL.row(a=[1, 2, 3], b="b", j=["a", "b"]).mv_expand("a")
        )r   )r8   r   s     r   	mv_expandzESQLBase.mv_expandl  s     f%%r   prefixRegisteredDomainc                     t        | fi |S )a  The ``REGISTERED_DOMAIN`` processing command parses a fully qualified
        domain name (FQDN) string and extracts its parts (domain, registered
        domain, top-level domain, subdomain) into new columns using the public
        suffix list.

        :param prefix: A keyword argument, where the argument name is the prefix
                       for the output columns, and the value is the string
                       expression containing the FQDN to parse.

        Examples::

            query1 = (
                ESQL.row(fqdn="www.example.co.uk")
                .registered_domain(rd="fqdn")
                .keep("rd.*")
            )
            query2 = (
                ESQL.from_("web_logs")
                .registered_domain(rd="domain")
                .where("rd.registered_domain == "elastic.co"")
                .stats(functions.count(E("*"))).by("rd.subdomain")
            )
        )r   r8   r   s     r   registered_domainzESQLBase.registered_domainx  s    0  ///r   Renamec                     t        | fi |S )a}  The ``RENAME`` processing command renames one or more columns.

        :param columns: The old and new column name pairs, given as keyword arguments.
                        If a name conflicts with an existing column name, the existing column
                        is dropped. If multiple columns are renamed to the same name, all but
                        the rightmost column with the same new name are dropped.

        Examples::

            query = (
                ESQL.from_("employees")
                .keep("first_name", "last_name", "still_hired")
                .rename(still_hired="employed")
            )
        )r   rw   s     r   renamezESQLBase.rename  s      d&g&&r   querynamed_queryRerankc                      t        | g|i |S )a  The ``RERANK`` command uses an inference model to compute a new relevance score
        for an initial set of documents, directly within your ES|QL queries.

        :param query: The query text used to rerank the documents. This is typically the
                      same query used in the initial search.
        :param named_query: The query text used to rerank the documents, given as a
                            keyword argument. The argument name is used for the column
                            name. If the query is given as a positional argument, the
                            results will be stored in a column named ``_score``. If the
                            specified column already exists, it will be overwritten with
                            the new results.

        Examples::

            query1 = (
                ESQL.from_("books").metadata("_score")
                .where('MATCH(description, "hobbit")')
                .sort("_score DESC")
                .limit(100)
                .rerank("hobbit").on("description").with_(inference_id="test_reranker")
                .limit(3)
                .keep("title", "_score")
            )
            query2 = (
                ESQL.from_("books").metadata("_score")
                .where('MATCH(description, "hobbit") OR MATCH(author, "Tolkien")')
                .sort("_score DESC")
                .limit(100)
                .rerank(rerank_score="hobbit").on("description", "author").with_(inference_id="test_reranker")
                .sort("rerank_score")
                .limit(3)
                .keep("title", "_score", "rerank_score")
            )
            query3 = (
                ESQL.from_("books").metadata("_score")
                .where('MATCH(description, "hobbit") OR MATCH(author, "Tolkien")')
                .sort("_score DESC")
                .limit(100)
                .rerank(rerank_score="hobbit").on("description", "author").with_(inference_id="test_reranker")
                .eval(original_score="_score", _score="rerank_score + original_score")
                .sort("_score")
                .limit(3)
                .keep("title", "original_score", "rerank_score", "_score")
            )
        )r   )r8   r   r   s      r   rerankzESQLBase.rerank  s    \ d2U2k22r   probabilitySamplec                     t        | |      S )a?  The ``SAMPLE`` command samples a fraction of the table rows.

        :param probability: The probability that a row is included in the sample. The value
                            must be between 0 and 1, exclusive.

        Examples::

            query = ESQL.from_("employees").keep("emp_no").sample(0.05)
        )r   )r8   r   s     r   samplezESQLBase.sample  s     dK((r   Sortc                     t        | g| S )ae  The ``SORT`` processing command sorts a table on one or more columns.

        :param columns: The columns to sort on.

        Examples::

            query1 = (
                ESQL.from_("employees")
                .keep("first_name", "last_name", "height")
                .sort("height")
            )
            query2 =  (
                ESQL.from_("employees")
                .keep("first_name", "last_name", "height")
                .sort("height DESC")
            )
            query3 = (
                ESQL.from_("employees")
                .keep("first_name", "last_name", "height")
                .sort("height DESC", "first_name ASC")
            )
            query4 = (
                ESQL.from_("employees")
                .keep("first_name", "last_name", "height")
                .sort("first_name ASC NULLS FIRST")
            )
        )r   rw   s     r   sortzESQLBase.sort  s    8 D#7##r   c                      t        | g|i |S )aF	  The ``STATS`` processing command groups rows according to a common value and
        calculates one or more aggregated values over the grouped rows.

        :param expressions: A list of expressions, given as positional arguments.
        :param named_expressions: A list of expressions, given as keyword arguments. The
                                  argument names are used for the returned aggregated values.

        Note that only one of ``expressions`` and ``named_expressions`` must be provided.

        Examples::

            query1 = (
                ESQL.from_("employees")
                .stats(count=functions.count("emp_no")).by("languages")
                .sort("languages")
            )
            query2 = (
                ESQL.from_("employees")
                .stats(avg_lang=functions.avg("languages"))
            )
            query3 = (
                ESQL.from_("employees")
                .stats(
                    avg_lang=functions.avg("languages"),
                    max_lang=functions.max("languages")
                )
            )
            query4 = (
                ESQL.from_("employees")
                .stats(
                    avg50s=functions.avg("salary").where('birth_date < "1960-01-01"'),
                    avg60s=functions.avg("salary").where('birth_date >= "1960-01-01"'),
                ).by("gender")
                .sort("gender")
            )
            query5 = (
                ESQL.from_("employees")
                .eval(Ks="salary / 1000")
                .stats(
                    under_40K=functions.count(E("*")).where("Ks < 40"),
                    inbetween=functions.count(E("*")).where("40 <= Ks AND Ks < 60"),
                    over_60K=functions.count(E("*")).where("60 <= Ks"),
                    total=f.count(E("*"))
                )
            )
            query6 = (
                ESQL.row(i=1, a=["a", "b"])
                .stats(functions.min("i")).by("a")
                .sort("a ASC")
            )
            query7 = (
                ESQL.from_("employees")
                .eval(hired=functions.date_format("hire_date", "yyyy"))
                .stats(avg_salary=functions.avg("salary")).by("hired", "languages.long")
                .eval(avg_salary=functions.round("avg_salary"))
                .sort("hired", "languages.long")

            )
        )r   r   s      r   statszESQLBase.stats  s    | T=K=+<==r   c                     t        |       S )a5  The ``TS_INFO`` processing command retrieves information about
        individual time series available in time series data streams, along
        with the dimension values that identify each series.

        Examples::

            query1 = (
                ESQL.ts("k8s")
                .ts_info()
                .sort("metric_name", "dimensions")
            )
            query2 = (
                ESQL.ts("k8s")
                .where("cluster == "prod"")
                .ts_info()
                .sort("metric_name", "dimensions")
            )
        )TsInfor<   s    r   ts_infozESQLBase.ts_info>  s    & d|r   UriPartsc                     t        | fi |S )aN  The ``URI_PARTS`` processing command parses a Uniform Resource
        Identifier (URI) string and extracts its components into new columns.

        :param prefix: A keyword argument, where the argument name is the prefix
                       for the output columns, and the value is the string
                       expression containing the URI to parse.

        Examples::

            query1 = (
                ESQL.row(uri="http://myusername:mypassword@www.example.com:80/foo.gif?key1=val1&key2=val2#fragment")
                .uri_parts(parts="uri")
                .keep("parts.*")
            )
            query2 = (
                ESQL.from_("web_logs")
                .uri_parts(p="uri")
                .where("p.domain == "www.example.com"")
                .stats(functions.count(E("*"))).by("p.path")
            )
        )r   r   s     r   	uri_partszESQLBase.uri_partsS  s    , '''r   	UserAgentc                     t        | fi |S )a  The ``USER_AGENT`` processing command parses a user-agent string and
        extracts its components (name, version, OS, device) into new columns.

        :param prefix: A keyword argument, where the argument name is the prefix
                       for the output columns, and the value is the string
                       expression containing the user agent string to parse.

        Examples::

            query1 = (
                ESQL.row(input="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36")
                .user_agent(ua="input").with_(extract_device_type=True)
                .keep("ua.*")
            )
            query2 = (
                ESQL.row(input="Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15")
                .user_agent(ua="input").with_(
                    properties=["name", "version", "device"],
                    extract_device_type=True
                )
                .keep("ua.*")
            )
        )r   r   s     r   
user_agentzESQLBase.user_agentk  s    0 (((r   Wherec                     t        | g| S )ap  The ``WHERE`` processing command produces a table that contains all the rows
        from the input table for which the provided condition evaluates to ``true``.

        :param expressions: A list of boolean expressions, given as positional arguments.
                            These expressions are combined with an ``AND`` logical operator.

        Examples::

            query1 = (
                ESQL.from_("employees")
                .keep("first_name", "last_name", "still_hired")
                .where("still_hired == true")
            )
            query2 = (
                ESQL.from_("sample_data")
                .where("@timestamp > NOW() - 1 hour")
            )
            query3 = (
                ESQL.from_("employees")
                .keep("first_name", "last_name", "height")
                .where("LENGTH(first_name) < 4")
            )
        )r   )r8   r   s     r   wherezESQLBase.where  s    0 T(K((r   r5   )F)ra   r2   r   NNNNNNNN)r   r   )r   r   )2r)   r*   r+   r,   r   r9   r0   r=   r;   r   r@   r-   r.   rI   	FieldTypeboolrS   r/   rY   r]   r_   rd   rh   rm   rs   rx   r|   r   r   r   r   r   r   intr   r   r   r   r   r   r   r   floatr   r   r   r   r   r   r   r   r   r   r2   r2   o   s   0x
3 0# + + #   NY N3 N N y $ 3   
> 
c 
 
D /N z (() ( ("*9%*97E*9	*9X-Y - - -(
$Y 
$6 
$$S $X $(5^ 5n 5QW 5: %)$($($($($($(RR !R !	R
 !R !R !R !R !R 
R@+"8C= +"F +"Z *)  *c  *f  *D2D*2DAO2D	2Dh$Y $6 $/ / / .	  .l  .D!*). ).. ).E ).V
&	 
&j 
&0. 0=O 04'	 'h '$.3^ .3N .3x .3`
)% 
)H 
)$^ $ $<>>*>>AO>>	>>@*(. (Z (0)> )k )4). )W )r   r2   c                   H     e Zd ZdZdZdef fdZdedd fdZde	fdZ
 xZS )	r   zImplementation of the ``FROM`` source command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    FROMr   c                 N    t         |           || _        t               | _        y r5   )superr9   _indicestuple_metadata_fields)r8   r   r\   s     r   r9   zFrom.__init__  s    7<wr   fieldsr   c                     || _         | S )zContinuation of the ``FROM`` and ``TS`` source commands.

        :param fields: metadata fields to retrieve, given as positional arguments.
        )r   r8   r   s     r   metadatazFrom.metadata  s    
 !'r   c           
      >   | j                   D cg c]  }| j                  |       }}| j                   ddj                  |       }| j                  r>|ddj                  | j                  D cg c]  }| j                  |       c}       z   }|S c c}w c c}w )N , z
 METADATA )r   rI   command_namer?   r   rS   )r8   rD   r   rR   r   s        r   r@   zFrom._render_internal  s    :>--H4%%e,HH  !499W#5"67  tyydNcNc)dU$//%*@)defgh   I
 *es   B0B)r)   r*   r+   r,   r   r.   r9   r   r   r0   r@   __classcell__r\   s   @r   r   r     s:     L? ?
	 f # r   r   c                   4     e Zd ZdZdef fdZdefdZ xZS )r   zImplementation of the ``ROW`` source command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r   c           	         t         |           |j                         D ci c]K  \  }}| j                  |      t	        |t
              st        j                  |      n| j                  |      M c}}| _	        y c c}}w r5   )
r   r9   itemsrS   rV   r   rW   rX   rY   _paramsr8   r   kvr\   s       r   r9   zRow.__init__  so     
 1 OOA!!%;< 

1&&q)*
 
s   AA=r   c           
          ddj                  | j                  j                         D cg c]  \  }}| d|  c}}      z   S c c}}w )NzROW r    = r?   r   r   r8   r   r   s      r   r@   zRow._render_internal  ?    		DLL<N<N<P"QDAqaSA3<"QRRR"Q   A	r)   r*   r+   r,   r/   r9   r0   r@   r   r   s   @r   r   r     "    	
 	
S# Sr   r   c                   4     e Zd ZdZdef fdZdefdZ xZS )r    zImplementation of the ``SHOW`` source command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    which makes it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r   c                 0    t         |           || _        y r5   )r   r9   _item)r8   r   r\   s     r   r9   zShow.__init__  s    
r   r   c                 >    d| j                  | j                         S )NzSHOW )rS   r   r<   s    r   r@   zShow._render_internal  s    ttzz2344r   )r)   r*   r+   r,   r0   r9   r@   r   r   s   @r   r    r      s     S 5# 5r   r    c                       e Zd ZdZd Zy)r#   zImplementation of the ``TS`` source command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    Nr)   r*   r+   r,   r   r   r   r   r#   r#     s     Lr   r#   c                       e Zd ZdZdefdZy)r'   a  Implementation of a branch inside a ``FORK`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    which makes it possible to chain all the commands that belong to the branch
    in a single expression.
    r   c                      y)N r   r<   s    r   r@   zBranch._render_internal  s    r   N)r)   r*   r+   r,   r0   r@   r   r   r   r'   r'     s    # r   r'   c                   4     e Zd ZdZdef fdZdefdZ xZS )rc   zImplementation of the ``SET`` query directive.

    This class inherits from :class:`ESQL <elasticsearch.esql.esql.ESQL>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r   c           	         t         |           |j                         D ci c]O  \  }}| j                  |      t	        |t
              st        j                  |      nt        j                  |      Q c}}| _
        y c c}}w r5   )r   r9   r   rS   rV   r   rW   rX   r2   rY   r   r   s       r   r9   zSet.__init__  so     
 1 OOA!!%;< 

1**1-.
 
s   ABr   c           
          ddj                  | j                  j                         D cg c]  \  }}| d|  c}}      z   S c c}}w )NzSET r   r   r   r   s      r   r@   zSet._render_internal  r   r   r   r   s   @r   rc   rc      r   r   rc   c                   \     e Zd ZdZdedef fdZdedd fdZded	edd fd
Z	defdZ
 xZS )rf   zImplementation of the ``CHANGE POINT`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   re   c                 \    t         |   |       || _        d | _        d | _        d | _        y r5   )r   r9   _value_key
_type_name_pvalue_name)r8   r3   re   r\   s      r   r9   zChangePoint.__init__  s-     )-	)-+/r   keyr   c                     || _         | S )zContinuation of the ``CHANGE_POINT`` command.

        :param key: The column with the key to order the values by. If not specified,
                    ``@timestamp`` is used.
        )r  )r8   r  s     r   onzChangePoint.on&  s     	r   	type_namepvalue_namec                 "    || _         || _        | S )a  Continuation of the ``CHANGE_POINT`` command.

        :param type_name: The name of the output column with the change point type.
                          If not specified, ``type`` is used.
        :param pvalue_name: The name of the output column with the p-value that indicates
                            how extreme the change point is. If not specified, ``pvalue``
                            is used.
        )r	  r
  )r8   r  r  s      r   as_zChangePoint.as_/  s     $'r   c                 8   | j                   sdnd| j                  | j                          }| j                  s| j                  sdnAd| j                  | j                  xs d       d| j                  | j                  xs d       }d| j                   | | S )Nr   ON  AS typer   pvaluezCHANGE_POINT )r  rS   r	  r
  r  )r8   r  namess      r   r@   zChangePoint._render_internal<  s    		bdoodii.H-I'J ??4+<+< (A6BC2dooVZVgVgVsksFtEuv 	
 t{{mC588r   )r)   r*   r+   r,   r2   r   r9   r  r0   r  r@   r   r   s   @r   rf   rf     sT    0x 0	 0i M S s } 9# 9r   rf   c                   L     e Zd ZdZdededef fdZdedd fdZdefd	Z	 xZ
S )
rk   zImplementation of the ``COMPLETION`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   ri   rj   c                     t        |      t        |      z   dkD  rt        d      t        |   |       || _        || _        d | _        y N   zGthis method requires either one positional or one keyword argument only)lenr   r   r9   _prompt_named_prompt_inference_id)r8   r3   ri   rj   r\   s       r   r9   zCompletion.__init__N  sQ     v;\**Q.Y  	 ),0r   inference_idr   c                     || _         | S )a  Continuation of the ``COMPLETION`` command.

        :param inference_id: The ID of the inference endpoint to use for the task. The
                             inference endpoint must be configured with the ``completion``
                             task type.
        r  r8   r   s     r   with_zCompletion.with_Z       *r   c                    | j                   t        d      d| j                   i}| j                  rt        | j                  j	                               d   }t        | j                  j                               d   }d| j                  |       d| j                  |       dt        j                  |       S d| j                  | j                  d          dt        j                  |       S )N/The completion command requires an inference IDr   r   zCOMPLETION r    WITH )
r  r   r  listkeysvaluesrS   rW   rX   r  )r8   r$  r   ri   s       r   r@   zCompletion._render_internald  s    %NOO!3!34$,,1134Q7F$,,3356q9F !8 9T__V=T<UU[\`\f\fgl\m[noo a!A B&TYIZH[\\r   r)   r*   r+   r,   r2   r/   r9   r0   r$  r@   r   r   s   @r   rk   rk   F  sF    
1
1)7
1IW
1# , 	]# 	]r   rk   c                   L     e Zd ZdZdededef fdZdedd fdZdefd	Z	 xZ
S )
rp   zImplementation of the ``DISSECT`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   rn   ro   c                 N    t         |   |       || _        || _        d | _        y r5   )r   r9   _input_pattern
_separatorr8   r3   rn   ro   r\   s       r   r9   zDissect.__init__x  s%     )-r   	separatorr   c                     || _         | S )zContinuation of the ``DISSECT`` command.

        :param separator: A string used as the separator between appended values,
                          when using the append modifier.
        )r1  )r8   r3  s     r   append_separatorzDissect.append_separator~  s     $r   c                     | j                   dn!dt        j                  | j                          }d| j                  | j                         dt        j                  | j
                         | S )Nr  z APPEND_SEPARATOR=zDISSECT r   )r1  rW   rX   rS   r/  r0  )r8   seps     r   r@   zDissect._render_internal  si     & %djj&A%BC 	 tt{{34Adjj6O5PQTPUV	
r   )r)   r*   r+   r,   r2   r   r0   r9   r5  r@   r   r   s   @r   rp   rp   p  sA    .x .	 .C .# ) 
# 
r   rp   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )ru   zImplementation of the ``DROP`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   rt   c                 2    t         |   |       || _        y r5   r   r9   _columnsr8   r3   rt   r\   s      r   r9   zDrop.__init__       r   r   c           
          ddj                  | j                  D cg c]  }| j                  |d       c}       S c c}w )NzDROP r   TrK   r?   r;  rS   r8   cols     r   r@   zDrop._render_internal  s<    tyyW[WdWd!ePS$//#d/"K!efghh!es   >

r)   r*   r+   r,   r2   r   r9   r0   r@   r   r   s   @r   ru   ru     s)     x  9  i# ir   ru   c                   \     e Zd ZdZdedef fdZdedd fdZded	edd fd
Z	defdZ
 xZS )rz   zImplementation of the ``ENRICH`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   ry   c                 \    t         |   |       || _        d | _        d | _        d | _        y r5   )r   r9   _policy_match_field_fields_named_fields)r8   r3   ry   r\   s      r   r9   zEnrich.__init__  s.     158<=Ar   match_fieldr   c                     || _         | S )ay  Continuation of the ``ENRICH`` command.

        :param match_field: The match field. ``ENRICH`` uses its value to look for records
                            in the enrich index. If not specified, the match will be
                            performed on the column with the same name as the
                            ``match_field`` defined in the enrich policy.
        )rG  )r8   rJ  s     r   r  z	Enrich.on  s     (r   r   named_fieldsc                 @    |r|rt        d      || _        || _        | S )a`  Continuation of the ``ENRICH`` command.

        :param fields: The enrich fields from the enrich index that are added to the result
                       as new columns, given as positional arguments. If a column with the
                       same name as the enrich field already exists, the existing column will
                       be replaced by the new column. If not specified, each of the enrich
                       fields defined in the policy is added. A column with the same name as
                       the enrich field will be dropped unless the enrich field is renamed.
        :param named_fields: The enrich fields from the enrich index that are added to the
                             result as new columns, given as keyword arguments. The name of
                             the keyword arguments are used as column names. If a column has
                             the same name as the new name, it will be discarded. If a name
                             (new or original) occurs more than once, only the rightmost
                             duplicate creates a new column.
        Athis method supports positional or keyword arguments but not both)r   rH  rI  )r8   r   rL  s      r   r$  zEnrich.with_  s/      lS  )r   c                    | j                   dnd| j                  | j                          }d}| j                  rcddj                  | j                  j	                         D cg c]*  \  }}| j                  |       d| j                  |       , c}}       }nG| j
                  ;ddj                  | j
                  D cg c]  }| j                  |       c}       }d| j                   | | S c c}}w c c}w )Nr  r  r(  r   r   zENRICH )rG  rS   rI  r?   r   rH  rF  )r8   r  r$  namer   s        r   r@   zEnrich._render_internal  s!      ( (9(9:;< 	
 TYYqu  rD  rD  rJ  rJ  rL  (Mbmbfhm4??4+@*AT__UZE[D\(]  (M  N  O  PE\\%#UuDOOE$:#UVWX  rd5'22 (M $Vs   $/C8C>
)r)   r*   r+   r,   r2   r0   r9   r   r  r$  r@   r   r   s   @r   rz   rz     sW    Bx B B	i 	H 	Y 	 h 03# 3r   rz   c                   <     e Zd ZdZdededef fdZdefdZ xZ	S )r~   zImplementation of the ``EVAL`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   rt   r}   c                 X    |r|rt        d      t        | 	  |       |xs || _        y NrN  )r   r   r9   r;  )r8   r3   rt   r}   r\   s       r   r9   zEval.__init__  s5     }S  	 0=r   r   c                    t        | j                  t              r`dj                  | j                  j	                         D cg c]*  \  }}| j                  |       d| j                  |       , c}}      }n9dj                  | j                  D cg c]  }| j                  |        c}      }d| S c c}}w c c}w )Nr   r   zEVAL )rV   r;  dictr?   r   rS   rY   )r8   rP  re   colsrB  s        r   r@   zEval._render_internal  s    dmmT*99 (,}}':':'<#e t,-S1B1B51I0JKD 99T]]Sc!2!23!7 89STDtf~ Ts   /B9
B?
r)   r*   r+   r,   r2   r/   r9   r0   r@   r   r   s   @r   r~   r~     s5    11 !1 (	1
# 
r   r~   c                        e Zd ZdZ	 	 	 	 	 	 	 ddeddded   ded   ded   ded   d	ed   d
ed   ded   f fdZdefdZ xZ	S )r[   zImplementation of the ``FORK`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   r'   r   r   r   r   r   r   r   c
                 B    t         
|   |       ||||||||	g| _        y r5   )r   r9   	_branches)r8   r3   r   r   r   r   r   r   r   r   r\   s             r   r9   zFork.__init__  s*     	 ueUE5Qr   r   c                     d}| j                   D ]=  }|s|j                         dd  j                  dd      }|dk(  rd| d}5|d| dz  }? d| S )	Nr     
r   z( z )z

       ( zFORK )rZ  r;   rQ   )r8   cmdsr(   cmds       r   r@   zFork._render_internal  sq    nn 	2Fmmoab)11$<2:uB<Dk#b11D	2 tf~r   r   )
r)   r*   r+   r,   r2   r   r9   r0   r@   r   r   s   @r   r[   r[     s     %)$($($($($($(RR R !	R
 !R !R !R !R !R !R	# 	r   r[   c                   `     e Zd ZdZddedee   f fdZdedd fdZ	de
dd fd	Zdefd
Z xZS )r   zImplementation of the ``FUSE`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   c                 N    t         |   |       || _        g | _        i | _        y r5   )r   r9   r   
by_columnsoptions)r8   r3   r   r\   s      r   r9   zFuse.__init__1  s%     +-')r   rt   r   c                 B    | xj                   t        |      z  c_         | S r5   )rb  r)  rw   s     r   byzFuse.by7  s    4=(r   rc  c                     || _         | S r5   )rc  r8   rc  s     r   r$  z
Fuse.with_;  s    r   c                 N   | j                   rd| j                   j                          nd}| j                  r/ddj                  | j                  D cg c]  }d| 	 c}      z   nd}| j                  r"dt        j                  | j                        z   nd}d| | | S c c}w )Nr   r  BY r(  FUSE)r   upperrb  r?   rc  rW   rX   )r8   r   r   re  r$  s        r   r@   zFuse._render_internal?  s    .2kk1T[[&&()*r  #((Ivc&NIJJ 	
 8<||4::dll33fXbT%)) Js   B"
r5   )r)   r*   r+   r,   r2   r   r0   r9   r   re  r   r$  r@   r   r   s   @r   r   r   )  sQ    *x *# *9  s v *# *r   r   c                   <     e Zd ZdZdededef fdZdefdZ xZ	S )r   zImplementation of the ``GROK`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   rn   ro   c                 @    t         |   |       || _        || _        y r5   )r   r9   r/  r0  r2  s       r   r9   zGrok.__init__R  s     r   r   c                 ~    d| j                  | j                         dt        j                  | j                         S )NzGROK r   )rS   r/  rW   rX   r0  r<   s    r   r@   zGrok._render_internalW  s1    tt{{34Adjj6O5PQQr   )
r)   r*   r+   r,   r2   r   r0   r9   r@   r   r   s   @r   r   r   J  s0     x  	  C  
R# Rr   r   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )r   zImplementation of the ``KEEP`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   rt   c                 2    t         |   |       || _        y r5   r:  r<  s      r   r9   zKeep.__init__c  r=  r   r   c           
          ddj                  | j                  D cg c]  }| j                  |d        c}       S c c}w )NzKEEP r   Tr?  r@  rA  s     r   r@   zKeep._render_internalg  sB    tyy\`\i\i!jUXT__S_%N$O"P!jklmm!js   ?
rC  r   s   @r   r   r   [  s)     x  9  n# nr   r   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )r   zImplementation of the ``LIMIT`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   c                 2    t         |   |       || _        y r5   )r   r9   _max_number_of_rows)r8   r3   r   r\   s      r   r9   zLimit.__init__s  s     #5 r   r   c                 F    dt        j                  | j                         S )NzLIMIT )rW   rX   rt  r<   s    r   r@   zLimit._render_internalw  s    

4#;#;<=>>r   )
r)   r*   r+   r,   r2   r   r9   r0   r@   r   r   s   @r   r   r   k  s'    6x 6S 6?# ?r   r   c                   H     e Zd ZdZdedef fdZdedd fdZde	fdZ
 xZS )	r   zImplementation of the ``LOOKUP JOIN`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   c                 @    t         |   |       || _        d | _        y r5   )r   r9   _lookup_index_field)r8   r3   r   r\   s      r   r9   zLookupJoin.__init__  s     )+/r   r   r   c                     || _         | S )a}  Continuation of the ``LOOKUP JOIN`` command.

        :param field: The field to join on. This field must exist in both your current query
                      results and in the lookup index. If the field contains multi-valued
                      entries, those entries will not match anything (the added fields will
                      contain null for those rows).
        )ry  )r8   r   s     r   r  zLookupJoin.on  s     r   c                    | j                   t        d      t        | j                  t              r| j                  n| j                  j
                  j                  }d| j                  |       d| j                  | j                          S )Nz!Joins require a field to join on.zLOOKUP JOIN r  )	ry  r   rV   rx  r0   rF   rH   rI   rS   )r8   rD   s     r   r@   zLookupJoin._render_internal  s    ;;@AA $,,c2 ##**00 	 4--e45T$//$++:V9WX	
r   )r)   r*   r+   r,   r2   r.   r9   r   r  r0   r@   r   r   s   @r   r   r   {  s:    0x 0y 0
		 	l 	

# 

r   r   c                   4     e Zd ZdZdef fdZdefdZ xZS )r   zImplementation of the ``METRICS_INFO`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   c                 $    t         |   |       y r5   r   r9   r8   r3   r\   s     r   r9   zMetricsInfo.__init__       r   r   c                      y)NMETRICS_INFOr   r<   s    r   r@   zMetricsInfo._render_internal  s    r   	r)   r*   r+   r,   r2   r9   r0   r@   r   r   s   @r   r   r     s     !x !# r   r   c                   \     e Zd ZdZdededef fdZdedd fdZ	d	e
dd fd
ZdefdZ xZS )r   zImplementation of the ``MMR`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   r   c                 \    t         |   |       || _        || _        d | _        d | _        y r5   )r   r9   ry  _query_vectorrt  _lambda)r8   r3   r   r   r\   s       r   r9   zMmr.__init__  s0     	 )26 (,r   r   r   c                     || _         | S )zContinuation of the ``MMR`` command.

        :param max_number_of_rows: The maximum number of rows to return after
                                   diversification.
        )rt  r   s     r   	mmr_limitzMmr.mmr_limit  s     $6 r   lambda_c                     || _         | S )a{  Continuation of the ``MMR`` command.

        :param lambda_: A value between 0.0 and 1.0 that controls how
                        similarity is calculated during diversification.
                        Higher values weight the similarity to the
                        query_vector more heavily, lower values weight the
                        diversity more heavily.
        )r  )r8   r  s     r   r$  z	Mmr.with_  s     r   c                 R   d}| j                   !|| j                  | j                          dz  }|d| j                  | j                         z  }d}| j                  d| j                   }| j
                  $dt        j                  d| j
                  i      z   nd}d| | | S )Nr  r   zON z LIMIT r(  lambdazMMR )r  rY   rS   ry  rt  r  rW   rX   )r8   r  r   r$  s       r   r@   zMmr._render_internal  s    )T&&t'9'9:;1==B
DOODKK0122##/d6678E ||' tzz8T\\":;; 	
 bT%((r   )r)   r*   r+   r,   r2   r   r/   r9   r   r  r   r$  r0   r@   r   r   s   @r   r   r     sW    --'0-@N-C E 
U 
u 
)# )r   r   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )r   zImplementation of the ``MV_EXPAND`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   c                 2    t         |   |       || _        y r5   )r   r9   _column)r8   r3   r   r\   s      r   r9   zMvExpand.__init__  s     r   r   c                 >    d| j                  | j                         S )Nz
MV_EXPAND )rS   r  r<   s    r   r@   zMvExpand._render_internal  s    DOODLL9:;;r   rC  r   s   @r   r   r     s'    x  <# <r   r   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )r   a  Implementation of the ``REGISTERED_DOMAIN`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   c                 d    t         |   |       t        |      dk7  rt        d      || _        y Nr  z1this method requires exactly one keyword argumentr   r9   r  r   _prefixr8   r3   r   r\   s      r   r9   zRegisteredDomain.__init__  /     v;!PQQr   r   c                     t        | j                  j                               d   }t        | j                  j                               d   }d| j	                  |       d| j                  |       S )Nr   zREGISTERED_DOMAIN r   r)  r  r*  r+  rS   rY   r8   r   rT   s      r   r@   z!RegisteredDomain._render_internal  sd    T\\&&()!,DLL'')*1-#DOOE$:#;3t?P?PQU?V>WXXr   rW  r   s   @r   r   r     s)    x > Y# Yr   r   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )r   zImplementation of the ``RENAME`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   rt   c                 2    t         |   |       || _        y r5   r:  r<  s      r   r9   zRename.__init__  r=  r   r   c                     ddj                  | j                  j                         D cg c]*  \  }}| j                  |       d| j                  |       , c}}       S c c}}w )NzRENAME r   r  )r?   r;  r   rS   )r8   old_namenew_names      r   r@   zRename._render_internal  s      }A  }J  }J  }P  }P  }R  $Sfxfnpxtx'@&AdooV^F_E`$a  $S  T  U  V  	V  $Ss   /A#rC  r   s   @r   r   r   	  s)     x  I  V# Vr   r   c                   \     e Zd ZdZdededef fdZdedd fdZd	edd fd
Z	defdZ
 xZS )r   zImplementation of the ``RERANK`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   r   c                     t        |      t        |      z   dkD  rt        d      t        |   |       || _        || _        d | _        d | _        y r  )r  r   r   r9   _query_named_queryrH  r  )r8   r3   r   r   r\   s       r   r9   zRerank.__init__!  sX     u:K((1,Y  	 '26,0r   r   r   c                     || _         | S )zContinuation of the ``RERANK`` command.

        :param fields: One or more fields to use for reranking. These fields should
                       contain the text that the reranking model will evaluate.
        )rH  r   s     r   r  z	Rerank.on.  s     r   r   c                     || _         | S )a  Continuation of the ``RERANK`` command.

        :param inference_id: The ID of the inference endpoint to use for the task. The
                             inference endpoint must be configured with the ``rerank``
                             task type.
        r"  r#  s     r   r$  zRerank.with_7  r%  r   c                 t   | j                   t        d      | j                  t        d      d| j                  i}| j                  rvt	        | j                  j                               d   }t	        | j                  j                               d   }| j                  |       dt        j                  |       }n"t        j                  | j                  d         }d| ddj                  | j                   D cg c]  }| j                  |       c}       d	t        j                  |       S c c}w )
Nz;The rerank command requires one or more fields to rerank onr'  r   r   r   zRERANK r  r   r(  )rH  r   r  r  r)  r*  r+  rS   rW   rX   r  r?   )r8   r$  r   r   r   s        r   r@   zRerank._render_internalA  s   <<M  %NOO!3!34$++0023A6F**1134Q7Ev./s4::e3D2EFEJJt{{1~.EeW ))NT__U3NOP QJJu%&(	
Ns   >D5)r)   r*   r+   r,   r2   r/   r9   r0   r  r$  r@   r   r   s   @r   r   r     sW    11(61GU1# ( # ( 
# 
r   r   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )r   zImplementation of the ``SAMPLE`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   c                 2    t         |   |       || _        y r5   )r   r9   _probability)r8   r3   r   r\   s      r   r9   zSample.__init__^       'r   r   c                 F    dt        j                  | j                         S )NzSAMPLE )rW   rX   r  r<   s    r   r@   zSample._render_internalb  s    D$5$56788r   )
r)   r*   r+   r,   r2   r   r9   r0   r@   r   r   s   @r   r   r   V  s'    (x (e (9# 9r   r   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )r   zImplementation of the ``SORT`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   rt   c                 2    t         |   |       || _        y r5   r:  r<  s      r   r9   zSort.__init__n  r=  r   r   c                 &   | j                   D cg c]H  }dj                  t        |      j                  d      D cg c]  }| j	                  |       c}      J }}}ddj                  |D cg c]  }|  c}       S c c}w c c}}w c c}w )Nr   zSORT r   )r;  r?   r0   splitrS   )r8   rB  termsortsr   s        r   r@   zSort._render_internalr  s     }}
 HHCs8KLdood+LM
 
 tyy!>TF)!>?@AA M
 "?s   ,BB	B0
B
BrW  r   s   @r   r   r   f  s)     x  >  B# Br   r   c                   P     e Zd ZdZdZdededef fdZdedd fd	Zde	fd
Z
 xZS )r   zImplementation of the ``STATS`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    STATSr3   r   r   c                 f    |r|rt        d      t        | 	  |       |xs || _        d | _        y rS  )r   r   r9   _expressions_grouping_expressions)r8   r3   r   r   r\   s       r   r9   zStats.__init__  s@     ,S  	 '<+<KO"r   grouping_expressionsr   c                     || _         | S )a<  Continuation of the ``STATS`` and ``INLINE STATS`` commands.

        :param grouping_expressions: Expressions that output the values to group by.
                                     If their names coincide with one of the computed
                                     columns, that column will be ignored.
        )r  )r8   r  s     r   re  zStats.by  s     &:"r   c                    t        | j                  t              rP| j                  j                         D cg c]*  \  }}| j	                  |       d| j                  |       , }}}n)| j                  D cg c]  }| j                  |        }}dt        | j                        dz   z  }d| }| j                  dn>d| ddj                  | j                  D cg c]  }| j                  |        c}       }| j                   d|j                  |D cg c]  }|  c}       | S c c}}w c c}w c c}w c c}w )	Nr   r   r\  z,
r  r]  ri  r   )
rV   r  rU  r   rS   rY   r  r   r  r?   )r8   r  re   exprsrT   indentexpression_separatorre  s           r   r@   zStats._render_internal  s^   d''. #'"3"3"9"9";C ??3'(D,=,=e,D+EFE 
 ?C>O>OPd))$/01PEPD--.23!$VH~ ))1 fXSUYUoUo+pTt/@/@/F.G,H+p!q rs 	
 ##$A&:&?&?W\@]tD6@]&^%_`b_cdd
 Q ,q@]s   /D29D8D=
E)r)   r*   r+   r,   r   r2   r/   r9   re  r0   r@   r   r   s   @r   r   r   z  sU     LPP %P ,	P 7 e# er   r   c                       e Zd ZdZdZy)r   zImplementation of the ``INLINE STATS`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    zINLINE STATSNr   r   r   r   r   r     s     "Lr   r   c                   4     e Zd ZdZdef fdZdefdZ xZS )r   zImplementation of the ``TS_INFO`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   c                 $    t         |   |       y r5   r~  r  s     r   r9   zTsInfo.__init__  r  r   r   c                      y)NTS_INFOr   r<   s    r   r@   zTsInfo._render_internal  s    r   r  r   s   @r   r   r     s     !x !# r   r   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )r   zImplementation of the ``URI_PARTS`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   c                 d    t         |   |       t        |      dk7  rt        d      || _        y r  r  r  s      r   r9   zUriParts.__init__  r  r   r   c                     t        | j                  j                               d   }t        | j                  j                               d   }d| j	                  |       d| j                  |       S )Nr   z
URI_PARTS r   r  r  s      r   r@   zUriParts._render_internal  sc    T\\&&()!,DLL'')*1-DOOE233t7H7H7N6OPPr   rW  r   s   @r   r   r     s)    x > Q# Qr   r   c                   H     e Zd ZdZdedef fdZdedd fdZdefdZ	 xZ
S )	r   zImplementation of the ``USER_AGENT`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   c                 r    t         |   |       t        |      dk7  rt        d      || _        d | _        y r  )r   r9   r  r   r  _optionsr  s      r   r9   zUserAgent.__init__  s6     v;!PQQ26r   rc  r   c                     || _         | S r5   )r  rg  s     r   r$  zUserAgent.with_  s    r   c                 B   t        | j                  j                               d   }t        | j                  j                               d   }d}| j                  rd| j                  | j                         }d| j                  |       d| j                  |       | S )Nr   r  r(  zUSER_AGENT r   )r)  r  r*  r+  r  rY   rS   )r8   r   rT   r$  s       r   r@   zUserAgent._render_internal  s    T\\&&()!,DLL'')*1-==T..t}}=>?ET__U34C8I8I$8O7PQVPWXXr   r,  r   s   @r   r   r     s<    7x 7> 7s { Y# Yr   r   c                   8     e Zd ZdZdedef fdZdefdZ xZ	S )r   zImplementation of the ``WHERE`` processing command.

    This class inherits from :class:`ESQLBase <elasticsearch.esql.esql.ESQLBase>`,
    to make it possible to chain all the commands that belong to an ES|QL query
    in a single expression.
    r3   r   c                 2    t         |   |       || _        y r5   )r   r9   r  )r8   r3   r   r\   s      r   r9   zWhere.__init__   r  r   r   c           	          ddj                  | j                  D cg c]  }| j                  |        c}       S c c}w )NzWHERE  AND )r?   r  rY   )r8   rT   s     r   r@   zWhere._render_internal  s>    tO`O`%at):):4)@(A&B%abcdd%as   =
rW  r   s   @r   r   r     s)    (x (~ (e# er   r   r   r   r   c            
      d    t        dj                  | D cg c]  }d| d
 c}            S c c}w )z6Combine two or more expressions with the AND operator.r  ()r   r?   r   rT   s     r   and_r    s,    !',,/T!D6/T"UVV/T   -c            
      d    t        dj                  | D cg c]  }d| d
 c}            S c c}w )z5Combine two or more expressions with the OR operator.z OR r  r  r  r  s     r   or_r    s,    !&++{.St4&{.S"TUU.Sr  
expressionc                      t        d|  d      S )zNegate an expression.zNOT (r  )r   )r  s    r   not_r    s    !E*Q"788r   ):rW   rO   abcr   r   typingr   r   r   r   r	   r
   r   dsl.document_baser   r   r   r0   r   r.   r/   r   r2   r   r   r    r#   r'   rc   rf   rk   rp   ru   rz   r~   r[   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r   r   <module>r     sQ  $  	 # @ @ @ W W#S()	$|$c)*	N3 Nbn)s n)b8 DS( S.58 5  	X 	S( S.,9( ,9^'] ']T
h 
Di8 i ?3X ?3D8 D 8  F*8 *BR8 R"n8 n ?H ? "
 "
J( 3)( 3)l<x < Yx Y(VX V :
X :
z9X 9 B8 B(1eH 1eh"% "X Qx Q(Y Y8eH e W- W2J W
V, V1I V
9+ 90H 9r   