elasticsearch-dsl


Nameelasticsearch-dsl JSON
Version 8.16.0 PyPI version JSON
download
home_pagehttps://github.com/elasticsearch/elasticsearch-dsl-py
SummaryPython client for Elasticsearch
upload_time2024-11-13 12:34:56
maintainerNone
docs_urlNone
authorElastic Client Library Maintainers
requires_python>=3.8
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            Elasticsearch DSL
=================

Elasticsearch DSL is a high-level library whose aim is to help with writing and
running queries against Elasticsearch. It is built on top of the official
low-level client (`elasticsearch-py <https://github.com/elastic/elasticsearch-py>`_).

It provides a more convenient and idiomatic way to write and manipulate
queries. It stays close to the Elasticsearch JSON DSL, mirroring its
terminology and structure. It exposes the whole range of the DSL from Python
either directly using defined classes or a queryset-like expressions.

It also provides an optional wrapper for working with documents as Python
objects: defining mappings, retrieving and saving documents, wrapping the
document data in user-defined classes.

To use the other Elasticsearch APIs (eg. cluster health) just use the
underlying client.

Installation
------------

::

  pip install elasticsearch-dsl

Examples
--------

Please see the `examples
<https://github.com/elastic/elasticsearch-dsl-py/tree/master/examples>`_
directory to see some complex examples using ``elasticsearch-dsl``.

Compatibility
-------------

The library is compatible with all Elasticsearch versions since ``2.x`` but you
**have to use a matching major version**:

For **Elasticsearch 8.0** and later, use the major version 8 (``8.x.y``) of the
library.

For **Elasticsearch 7.0** and later, use the major version 7 (``7.x.y``) of the
library.

For **Elasticsearch 6.0** and later, use the major version 6 (``6.x.y``) of the
library.

For **Elasticsearch 5.0** and later, use the major version 5 (``5.x.y``) of the
library.

For **Elasticsearch 2.0** and later, use the major version 2 (``2.x.y``) of the
library.

The recommended way to set your requirements in your `setup.py` or
`requirements.txt` is::

    # Elasticsearch 8.x
    elasticsearch-dsl>=8.0.0,<9.0.0

    # Elasticsearch 7.x
    elasticsearch-dsl>=7.0.0,<8.0.0

    # Elasticsearch 6.x
    elasticsearch-dsl>=6.0.0,<7.0.0

    # Elasticsearch 5.x
    elasticsearch-dsl>=5.0.0,<6.0.0

    # Elasticsearch 2.x
    elasticsearch-dsl>=2.0.0,<3.0.0


The development is happening on ``main``, older branches only get bugfix releases

Search Example
--------------

Let's have a typical search request written directly as a ``dict``:

.. code:: python

    from elasticsearch import Elasticsearch
    client = Elasticsearch("https://localhost:9200")

    response = client.search(
        index="my-index",
        body={
          "query": {
            "bool": {
              "must": [{"match": {"title": "python"}}],
              "must_not": [{"match": {"description": "beta"}}],
              "filter": [{"term": {"category": "search"}}]
            }
          },
          "aggs" : {
            "per_tag": {
              "terms": {"field": "tags"},
              "aggs": {
                "max_lines": {"max": {"field": "lines"}}
              }
            }
          }
        }
    )

    for hit in response['hits']['hits']:
        print(hit['_score'], hit['_source']['title'])

    for tag in response['aggregations']['per_tag']['buckets']:
        print(tag['key'], tag['max_lines']['value'])



The problem with this approach is that it is very verbose, prone to syntax
mistakes like incorrect nesting, hard to modify (eg. adding another filter) and
definitely not fun to write.

Let's rewrite the example using the Python DSL:

.. code:: python

    from elasticsearch import Elasticsearch
    from elasticsearch_dsl import Search

    client = Elasticsearch("https://localhost:9200")

    s = Search(using=client, index="my-index") \
        .filter("term", category="search") \
        .query("match", title="python")   \
        .exclude("match", description="beta")

    s.aggs.bucket('per_tag', 'terms', field='tags') \
        .metric('max_lines', 'max', field='lines')

    response = s.execute()

    for hit in response:
        print(hit.meta.score, hit.title)

    for tag in response.aggregations.per_tag.buckets:
        print(tag.key, tag.max_lines.value)

As you see, the library took care of:

- creating appropriate ``Query`` objects by name (eq. "match")
- composing queries into a compound ``bool`` query
- putting the ``term`` query in a filter context of the ``bool`` query
- providing a convenient access to response data
- no curly or square brackets everywhere


Persistence Example
-------------------

Let's have a simple Python class representing an article in a blogging system:

.. code:: python

    from datetime import datetime
    from elasticsearch_dsl import Document, Date, Integer, Keyword, Text, connections

    # Define a default Elasticsearch client
    connections.create_connection(hosts="https://localhost:9200")

    class Article(Document):
        title = Text(analyzer='snowball', fields={'raw': Keyword()})
        body = Text(analyzer='snowball')
        tags = Keyword()
        published_from = Date()
        lines = Integer()

        class Index:
            name = 'blog'
            settings = {
              "number_of_shards": 2,
            }

        def save(self, ** kwargs):
            self.lines = len(self.body.split())
            return super(Article, self).save(** kwargs)

        def is_published(self):
            return datetime.now() > self.published_from

    # create the mappings in elasticsearch
    Article.init()

    # create and save and article
    article = Article(meta={'id': 42}, title='Hello world!', tags=['test'])
    article.body = ''' looong text '''
    article.published_from = datetime.now()
    article.save()

    article = Article.get(id=42)
    print(article.is_published())

    # Display cluster health
    print(connections.get_connection().cluster.health())


In this example you can see:

- providing a default connection
- defining fields with mapping configuration
- setting index name
- defining custom methods
- overriding the built-in ``.save()`` method to hook into the persistence
  life cycle
- retrieving and saving the object into Elasticsearch
- accessing the underlying client for other APIs

You can see more in the persistence chapter of the documentation.

Migration from ``elasticsearch-py``
-----------------------------------

You don't have to port your entire application to get the benefits of the
Python DSL, you can start gradually by creating a ``Search`` object from your
existing ``dict``, modifying it using the API and serializing it back to a
``dict``:

.. code:: python

    body = {...} # insert complicated query here

    # Convert to Search object
    s = Search.from_dict(body)

    # Add some filters, aggregations, queries, ...
    s.filter("term", tags="python")

    # Convert back to dict to plug back into existing code
    body = s.to_dict()

Development
-----------

Activate Virtual Environment (`virtualenvs <http://docs.python-guide.org/en/latest/dev/virtualenvs/>`_):

.. code:: bash

    $ virtualenv venv
    $ source venv/bin/activate

To install all of the dependencies necessary for development, run:

.. code:: bash

    $ pip install -e '.[develop]'

To run all of the tests for ``elasticsearch-dsl-py``, run:

.. code:: bash

    $ python setup.py test

Alternatively, it is possible to use the ``run_tests.py`` script in
``test_elasticsearch_dsl``, which wraps `pytest
<http://doc.pytest.org/en/latest/>`_, to run subsets of the test suite. Some
examples can be seen below:

.. code:: bash

    # Run all of the tests in `test_elasticsearch_dsl/test_analysis.py`
    $ ./run_tests.py test_analysis.py

    # Run only the `test_analyzer_serializes_as_name` test.
    $ ./run_tests.py test_analysis.py::test_analyzer_serializes_as_name

``pytest`` will skip tests from ``test_elasticsearch_dsl/test_integration``
unless there is an instance of Elasticsearch on which a connection can occur.
By default, the test connection is attempted at ``localhost:9200``, based on
the defaults specified in the ``elasticsearch-py`` `Connection
<https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch
/connection/base.py#L29>`_ class. **Because running the integration
tests will cause destructive changes to the Elasticsearch cluster, only run
them when the associated cluster is empty.** As such, if the
Elasticsearch instance at ``localhost:9200`` does not meet these requirements,
it is possible to specify a different test Elasticsearch server through the
``TEST_ES_SERVER`` environment variable.

.. code:: bash

    $ TEST_ES_SERVER=my-test-server:9201 ./run_tests

Documentation
-------------

Documentation is available at https://elasticsearch-dsl.readthedocs.io.

Contribution Guide
------------------

Want to hack on Elasticsearch DSL? Awesome! We have `Contribution-Guide <https://github.com/elastic/elasticsearch-dsl-py/blob/master/CONTRIBUTING.rst>`_.

License
-------

Copyright 2013 Elasticsearch

Licensed 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.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/elasticsearch/elasticsearch-dsl-py",
    "name": "elasticsearch-dsl",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Elastic Client Library Maintainers",
    "author_email": "client-libs@elastic.co",
    "download_url": "https://files.pythonhosted.org/packages/6d/36/c1fd534eb4b688f8ac214c2b5f46512c267cf52c11f4b702ac10dac2555c/elasticsearch_dsl-8.16.0.tar.gz",
    "platform": null,
    "description": "Elasticsearch DSL\n=================\n\nElasticsearch DSL is a high-level library whose aim is to help with writing and\nrunning queries against Elasticsearch. It is built on top of the official\nlow-level client (`elasticsearch-py <https://github.com/elastic/elasticsearch-py>`_).\n\nIt provides a more convenient and idiomatic way to write and manipulate\nqueries. It stays close to the Elasticsearch JSON DSL, mirroring its\nterminology and structure. It exposes the whole range of the DSL from Python\neither directly using defined classes or a queryset-like expressions.\n\nIt also provides an optional wrapper for working with documents as Python\nobjects: defining mappings, retrieving and saving documents, wrapping the\ndocument data in user-defined classes.\n\nTo use the other Elasticsearch APIs (eg. cluster health) just use the\nunderlying client.\n\nInstallation\n------------\n\n::\n\n  pip install elasticsearch-dsl\n\nExamples\n--------\n\nPlease see the `examples\n<https://github.com/elastic/elasticsearch-dsl-py/tree/master/examples>`_\ndirectory to see some complex examples using ``elasticsearch-dsl``.\n\nCompatibility\n-------------\n\nThe library is compatible with all Elasticsearch versions since ``2.x`` but you\n**have to use a matching major version**:\n\nFor **Elasticsearch 8.0** and later, use the major version 8 (``8.x.y``) of the\nlibrary.\n\nFor **Elasticsearch 7.0** and later, use the major version 7 (``7.x.y``) of the\nlibrary.\n\nFor **Elasticsearch 6.0** and later, use the major version 6 (``6.x.y``) of the\nlibrary.\n\nFor **Elasticsearch 5.0** and later, use the major version 5 (``5.x.y``) of the\nlibrary.\n\nFor **Elasticsearch 2.0** and later, use the major version 2 (``2.x.y``) of the\nlibrary.\n\nThe recommended way to set your requirements in your `setup.py` or\n`requirements.txt` is::\n\n    # Elasticsearch 8.x\n    elasticsearch-dsl>=8.0.0,<9.0.0\n\n    # Elasticsearch 7.x\n    elasticsearch-dsl>=7.0.0,<8.0.0\n\n    # Elasticsearch 6.x\n    elasticsearch-dsl>=6.0.0,<7.0.0\n\n    # Elasticsearch 5.x\n    elasticsearch-dsl>=5.0.0,<6.0.0\n\n    # Elasticsearch 2.x\n    elasticsearch-dsl>=2.0.0,<3.0.0\n\n\nThe development is happening on ``main``, older branches only get bugfix releases\n\nSearch Example\n--------------\n\nLet's have a typical search request written directly as a ``dict``:\n\n.. code:: python\n\n    from elasticsearch import Elasticsearch\n    client = Elasticsearch(\"https://localhost:9200\")\n\n    response = client.search(\n        index=\"my-index\",\n        body={\n          \"query\": {\n            \"bool\": {\n              \"must\": [{\"match\": {\"title\": \"python\"}}],\n              \"must_not\": [{\"match\": {\"description\": \"beta\"}}],\n              \"filter\": [{\"term\": {\"category\": \"search\"}}]\n            }\n          },\n          \"aggs\" : {\n            \"per_tag\": {\n              \"terms\": {\"field\": \"tags\"},\n              \"aggs\": {\n                \"max_lines\": {\"max\": {\"field\": \"lines\"}}\n              }\n            }\n          }\n        }\n    )\n\n    for hit in response['hits']['hits']:\n        print(hit['_score'], hit['_source']['title'])\n\n    for tag in response['aggregations']['per_tag']['buckets']:\n        print(tag['key'], tag['max_lines']['value'])\n\n\n\nThe problem with this approach is that it is very verbose, prone to syntax\nmistakes like incorrect nesting, hard to modify (eg. adding another filter) and\ndefinitely not fun to write.\n\nLet's rewrite the example using the Python DSL:\n\n.. code:: python\n\n    from elasticsearch import Elasticsearch\n    from elasticsearch_dsl import Search\n\n    client = Elasticsearch(\"https://localhost:9200\")\n\n    s = Search(using=client, index=\"my-index\") \\\n        .filter(\"term\", category=\"search\") \\\n        .query(\"match\", title=\"python\")   \\\n        .exclude(\"match\", description=\"beta\")\n\n    s.aggs.bucket('per_tag', 'terms', field='tags') \\\n        .metric('max_lines', 'max', field='lines')\n\n    response = s.execute()\n\n    for hit in response:\n        print(hit.meta.score, hit.title)\n\n    for tag in response.aggregations.per_tag.buckets:\n        print(tag.key, tag.max_lines.value)\n\nAs you see, the library took care of:\n\n- creating appropriate ``Query`` objects by name (eq. \"match\")\n- composing queries into a compound ``bool`` query\n- putting the ``term`` query in a filter context of the ``bool`` query\n- providing a convenient access to response data\n- no curly or square brackets everywhere\n\n\nPersistence Example\n-------------------\n\nLet's have a simple Python class representing an article in a blogging system:\n\n.. code:: python\n\n    from datetime import datetime\n    from elasticsearch_dsl import Document, Date, Integer, Keyword, Text, connections\n\n    # Define a default Elasticsearch client\n    connections.create_connection(hosts=\"https://localhost:9200\")\n\n    class Article(Document):\n        title = Text(analyzer='snowball', fields={'raw': Keyword()})\n        body = Text(analyzer='snowball')\n        tags = Keyword()\n        published_from = Date()\n        lines = Integer()\n\n        class Index:\n            name = 'blog'\n            settings = {\n              \"number_of_shards\": 2,\n            }\n\n        def save(self, ** kwargs):\n            self.lines = len(self.body.split())\n            return super(Article, self).save(** kwargs)\n\n        def is_published(self):\n            return datetime.now() > self.published_from\n\n    # create the mappings in elasticsearch\n    Article.init()\n\n    # create and save and article\n    article = Article(meta={'id': 42}, title='Hello world!', tags=['test'])\n    article.body = ''' looong text '''\n    article.published_from = datetime.now()\n    article.save()\n\n    article = Article.get(id=42)\n    print(article.is_published())\n\n    # Display cluster health\n    print(connections.get_connection().cluster.health())\n\n\nIn this example you can see:\n\n- providing a default connection\n- defining fields with mapping configuration\n- setting index name\n- defining custom methods\n- overriding the built-in ``.save()`` method to hook into the persistence\n  life cycle\n- retrieving and saving the object into Elasticsearch\n- accessing the underlying client for other APIs\n\nYou can see more in the persistence chapter of the documentation.\n\nMigration from ``elasticsearch-py``\n-----------------------------------\n\nYou don't have to port your entire application to get the benefits of the\nPython DSL, you can start gradually by creating a ``Search`` object from your\nexisting ``dict``, modifying it using the API and serializing it back to a\n``dict``:\n\n.. code:: python\n\n    body = {...} # insert complicated query here\n\n    # Convert to Search object\n    s = Search.from_dict(body)\n\n    # Add some filters, aggregations, queries, ...\n    s.filter(\"term\", tags=\"python\")\n\n    # Convert back to dict to plug back into existing code\n    body = s.to_dict()\n\nDevelopment\n-----------\n\nActivate Virtual Environment (`virtualenvs <http://docs.python-guide.org/en/latest/dev/virtualenvs/>`_):\n\n.. code:: bash\n\n    $ virtualenv venv\n    $ source venv/bin/activate\n\nTo install all of the dependencies necessary for development, run:\n\n.. code:: bash\n\n    $ pip install -e '.[develop]'\n\nTo run all of the tests for ``elasticsearch-dsl-py``, run:\n\n.. code:: bash\n\n    $ python setup.py test\n\nAlternatively, it is possible to use the ``run_tests.py`` script in\n``test_elasticsearch_dsl``, which wraps `pytest\n<http://doc.pytest.org/en/latest/>`_, to run subsets of the test suite. Some\nexamples can be seen below:\n\n.. code:: bash\n\n    # Run all of the tests in `test_elasticsearch_dsl/test_analysis.py`\n    $ ./run_tests.py test_analysis.py\n\n    # Run only the `test_analyzer_serializes_as_name` test.\n    $ ./run_tests.py test_analysis.py::test_analyzer_serializes_as_name\n\n``pytest`` will skip tests from ``test_elasticsearch_dsl/test_integration``\nunless there is an instance of Elasticsearch on which a connection can occur.\nBy default, the test connection is attempted at ``localhost:9200``, based on\nthe defaults specified in the ``elasticsearch-py`` `Connection\n<https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch\n/connection/base.py#L29>`_ class. **Because running the integration\ntests will cause destructive changes to the Elasticsearch cluster, only run\nthem when the associated cluster is empty.** As such, if the\nElasticsearch instance at ``localhost:9200`` does not meet these requirements,\nit is possible to specify a different test Elasticsearch server through the\n``TEST_ES_SERVER`` environment variable.\n\n.. code:: bash\n\n    $ TEST_ES_SERVER=my-test-server:9201 ./run_tests\n\nDocumentation\n-------------\n\nDocumentation is available at https://elasticsearch-dsl.readthedocs.io.\n\nContribution Guide\n------------------\n\nWant to hack on Elasticsearch DSL? Awesome! We have `Contribution-Guide <https://github.com/elastic/elasticsearch-dsl-py/blob/master/CONTRIBUTING.rst>`_.\n\nLicense\n-------\n\nCopyright 2013 Elasticsearch\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Python client for Elasticsearch",
    "version": "8.16.0",
    "project_urls": {
        "Homepage": "https://github.com/elasticsearch/elasticsearch-dsl-py"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4c56d1d731c98e5d4e45f6700d347a1d011eac4ed1573edbc332c4a107be4f73",
                "md5": "99a1c4837756abbb2652e4b55ba1a0ef",
                "sha256": "39b753804df885cbc71fcaf40efcece6ef5569e2d70f6fe79c5bdb7da066acb4"
            },
            "downloads": -1,
            "filename": "elasticsearch_dsl-8.16.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "99a1c4837756abbb2652e4b55ba1a0ef",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 158692,
            "upload_time": "2024-11-13T12:34:54",
            "upload_time_iso_8601": "2024-11-13T12:34:54.470854Z",
            "url": "https://files.pythonhosted.org/packages/4c/56/d1d731c98e5d4e45f6700d347a1d011eac4ed1573edbc332c4a107be4f73/elasticsearch_dsl-8.16.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6d36c1fd534eb4b688f8ac214c2b5f46512c267cf52c11f4b702ac10dac2555c",
                "md5": "b3d84b43ab4e8c536a874b406d26c33e",
                "sha256": "05bd5050eef7d0706a4487cd22864d3c158c8e1cbca26b53ef1a473bdee13459"
            },
            "downloads": -1,
            "filename": "elasticsearch_dsl-8.16.0.tar.gz",
            "has_sig": false,
            "md5_digest": "b3d84b43ab4e8c536a874b406d26c33e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 152123,
            "upload_time": "2024-11-13T12:34:56",
            "upload_time_iso_8601": "2024-11-13T12:34:56.220388Z",
            "url": "https://files.pythonhosted.org/packages/6d/36/c1fd534eb4b688f8ac214c2b5f46512c267cf52c11f4b702ac10dac2555c/elasticsearch_dsl-8.16.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-13 12:34:56",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "elasticsearch",
    "github_project": "elasticsearch-dsl-py",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "elasticsearch-dsl"
}
        
Elapsed time: 1.00700s