Skip to content

ES|QL query builder #2997

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions docs/sphinx/esql.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
ES|QL Query Builder
===================

.. autoclass:: elasticsearch.esql.ESQL
:inherited-members:
:members:

.. autoclass:: elasticsearch.esql.esql.ESQLBase
:inherited-members:
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.From
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Row
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Show
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Dissect
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Drop
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Enrich
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Eval
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Grok
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Keep
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Limit
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.LookupJoin
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.MvExpand
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Rename
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Sample
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Sort
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Stats
:members:
:exclude-members: __init__

.. autoclass:: elasticsearch.esql.esql.Where
:members:
:exclude-members: __init__
1 change: 1 addition & 0 deletions docs/sphinx/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ High-level documentation for this client is `also available <https://www.elastic
:maxdepth: 2

es_api
esql
dsl
api_helpers
exceptions
Expand Down
100 changes: 84 additions & 16 deletions elasticsearch/dsl/document_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.

import json
from datetime import date, datetime
from fnmatch import fnmatch
from typing import (
Expand Down Expand Up @@ -56,7 +57,59 @@ def __init__(self, *args: Any, **kwargs: Any):
self.args, self.kwargs = args, kwargs


class InstrumentedField:
class InstrumentedExpression:
"""Proxy object for a ES|QL expression."""

def __init__(self, expr: str):
self._expr = expr

def __str__(self) -> str:
return self._expr

def __repr__(self) -> str:
return f"InstrumentedExpression[{self._expr}]"

def __pos__(self) -> "InstrumentedExpression":
return self

def __neg__(self) -> "InstrumentedExpression":
return InstrumentedExpression(f"-({self._expr})")

def __eq__(self, value: Any) -> "InstrumentedExpression": # type: ignore[override]
return InstrumentedExpression(f"{self._expr} == {json.dumps(value)}")

def __ne__(self, value: Any) -> "InstrumentedExpression": # type: ignore[override]
return InstrumentedExpression(f"{self._expr} != {json.dumps(value)}")

def __lt__(self, value: Any) -> "InstrumentedExpression":
return InstrumentedExpression(f"{self._expr} < {json.dumps(value)}")

def __gt__(self, value: Any) -> "InstrumentedExpression":
return InstrumentedExpression(f"{self._expr} > {json.dumps(value)}")

def __le__(self, value: Any) -> "InstrumentedExpression":
return InstrumentedExpression(f"{self._expr} <= {json.dumps(value)}")

def __ge__(self, value: Any) -> "InstrumentedExpression":
return InstrumentedExpression(f"{self._expr} >= {json.dumps(value)}")

def __add__(self, value: Any) -> "InstrumentedExpression":
return InstrumentedExpression(f"{self._expr} + {json.dumps(value)}")

def __sub__(self, value: Any) -> "InstrumentedExpression":
return InstrumentedExpression(f"{self._expr} - {json.dumps(value)}")

def __mul__(self, value: Any) -> "InstrumentedExpression":
return InstrumentedExpression(f"{self._expr} * {json.dumps(value)}")

def __truediv__(self, value: Any) -> "InstrumentedExpression":
return InstrumentedExpression(f"{self._expr} / {json.dumps(value)}")

def __mod__(self, value: Any) -> "InstrumentedExpression":
return InstrumentedExpression(f"{self._expr} % {json.dumps(value)}")


class InstrumentedField(InstrumentedExpression):
"""Proxy object for a mapped document field.

An object of this instance is returned when a field is accessed as a class
Expand All @@ -71,8 +124,8 @@ class MyDocument(Document):
s = s.sort(-MyDocument.name) # sort by name in descending order
"""

def __init__(self, name: str, field: Field):
self._name = name
def __init__(self, name: str, field: Optional[Field]):
super().__init__(name)
self._field = field

# note that the return value type here assumes classes will only be used to
Expand All @@ -83,26 +136,41 @@ def __getattr__(self, attr: str) -> "InstrumentedField":
# first let's see if this is an attribute of this object
return super().__getattribute__(attr) # type: ignore[no-any-return]
except AttributeError:
try:
# next we see if we have a sub-field with this name
return InstrumentedField(f"{self._name}.{attr}", self._field[attr])
except KeyError:
# lastly we let the wrapped field resolve this attribute
return getattr(self._field, attr) # type: ignore[no-any-return]

def __pos__(self) -> str:
if self._field:
try:
# next we see if we have a sub-field with this name
return InstrumentedField(f"{self._expr}.{attr}", self._field[attr])
except KeyError:
# lastly we let the wrapped field resolve this attribute
return getattr(self._field, attr) # type: ignore[no-any-return]
else:
raise

def __pos__(self) -> str: # type: ignore[override]
"""Return the field name representation for ascending sort order"""
return f"{self._name}"
return f"{self._expr}"

def __neg__(self) -> str:
def __neg__(self) -> str: # type: ignore[override]
"""Return the field name representation for descending sort order"""
return f"-{self._name}"
return f"-{self._expr}"

def asc(self) -> "InstrumentedField":
return InstrumentedField(f"{self._expr} ASC", None)

def desc(self) -> "InstrumentedField":
return InstrumentedField(f"{self._expr} DESC", None)

def nulls_first(self) -> "InstrumentedField":
return InstrumentedField(f"{self._expr} NULLS FIRST", None)

def nulls_last(self) -> "InstrumentedField":
return InstrumentedField(f"{self._expr} NULLS LAST", None)

def __str__(self) -> str:
return self._name
return self._expr

def __repr__(self) -> str:
return f"InstrumentedField[{self._name}]"
return f"InstrumentedField[{self._expr}]"


class DocumentMeta(type):
Expand Down
2 changes: 1 addition & 1 deletion elasticsearch/dsl/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ def __init__(self, _expand__to_dot: Optional[bool] = None, **params: Any) -> Non
_expand__to_dot = EXPAND__TO_DOT
self._params: Dict[str, Any] = {}
for pname, pvalue in params.items():
if pvalue == DEFAULT:
if pvalue is DEFAULT:
continue
# expand "__" to dots
if "__" in pname and _expand__to_dot:
Expand Down
18 changes: 18 additions & 0 deletions elasticsearch/esql/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

from .esql import ESQL # noqa: F401
Loading
Loading