{"id":13461723,"url":"https://github.com/elastic/elasticsearch-dsl-py","last_synced_at":"2025-12-11T21:03:41.908Z","repository":{"id":14726008,"uuid":"17446726","full_name":"elastic/elasticsearch-dsl-py","owner":"elastic","description":"High level Python client for Elasticsearch","archived":false,"fork":false,"pushed_at":"2025-04-18T13:50:16.000Z","size":1953,"stargazers_count":3866,"open_issues_count":50,"forks_count":801,"subscribers_count":433,"default_branch":"main","last_synced_at":"2025-05-10T13:42:18.026Z","etag":null,"topics":["elasticsearch","python","search"],"latest_commit_sha":null,"homepage":"http://elasticsearch-dsl.readthedocs.org","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/elastic.png","metadata":{"files":{"readme":"README","changelog":"Changelog.rst","contributing":"CONTRIBUTING.rst","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2014-03-05T16:19:39.000Z","updated_at":"2025-05-09T18:11:14.000Z","dependencies_parsed_at":"2022-07-14T06:40:32.041Z","dependency_job_id":"f504581b-414e-4416-8c7b-f6b8c51021a4","html_url":"https://github.com/elastic/elasticsearch-dsl-py","commit_stats":{"total_commits":1097,"total_committers":146,"mean_commits":7.513698630136986,"dds":"0.30811303555150416","last_synced_commit":"bacfc745ea56dd224d498e7843445b607f0772c8"},"previous_names":["elasticsearch/elasticsearch-dsl-py"],"tags_count":50,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elastic%2Felasticsearch-dsl-py","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elastic%2Felasticsearch-dsl-py/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elastic%2Felasticsearch-dsl-py/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/elastic%2Felasticsearch-dsl-py/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/elastic","download_url":"https://codeload.github.com/elastic/elasticsearch-dsl-py/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253745198,"owners_count":21957319,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["elasticsearch","python","search"],"created_at":"2024-07-31T11:00:54.668Z","updated_at":"2025-12-11T21:03:36.523Z","avatar_url":"https://github.com/elastic.png","language":"Python","readme":"Elasticsearch DSL\n=================\n\nDeprecation notice\n------------------\n\nAs of release 8.18.0, the Elasticsearch DSL package is part of the official\n`Elasticsearch Python client \u003chttps://github.com/elastic/elasticsearch-py\u003e`_,\nso a separate install is not needed anymore. To migrate, follow these steps:\n\n- Uninstall the ``elasticsearch-dsl`` package\n- Make sure you have version 8.18.0 or newer of the ``elasticsearch`` package\n  installed\n- Replace ``elasticsearch_dsl`` with ``elasticsearch.dsl`` in your imports\n\nTo prevent applications from breaking unexpectedly due to this change, the\n8.18.0 release of this package automatically redirects all imports to the\ncorresponding modules of the Python client package.\n\nThe following instructions only apply to versions 8.17 and older of this\npackage.\n\nIntroduction\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 \u003chttps://github.com/elastic/elasticsearch-py\u003e`_).\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\u003chttps://github.com/elastic/elasticsearch-dsl-py/tree/master/examples\u003e`_\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\u003e=8.0.0,\u003c9.0.0\n\n    # Elasticsearch 7.x\n    elasticsearch-dsl\u003e=7.0.0,\u003c8.0.0\n\n    # Elasticsearch 6.x\n    elasticsearch-dsl\u003e=6.0.0,\u003c7.0.0\n\n    # Elasticsearch 5.x\n    elasticsearch-dsl\u003e=5.0.0,\u003c6.0.0\n\n    # Elasticsearch 2.x\n    elasticsearch-dsl\u003e=2.0.0,\u003c3.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() \u003e 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 \u003chttp://docs.python-guide.org/en/latest/dev/virtualenvs/\u003e`_):\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\u003chttp://doc.pytest.org/en/latest/\u003e`_, 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\u003chttps://github.com/elastic/elasticsearch-py/blob/master/elasticsearch\n/connection/base.py#L29\u003e`_ 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 \u003chttps://github.com/elastic/elasticsearch-dsl-py/blob/master/CONTRIBUTING.rst\u003e`_.\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","funding_links":[],"categories":["Search","Python","资源列表","Database Clients","Data Management \u0026 Processing","搜索","Search [🔝](#readme)","Awesome Python"],"sub_categories":["搜索","Database \u0026 Cloud Management","Search"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felastic%2Felasticsearch-dsl-py","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Felastic%2Felasticsearch-dsl-py","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felastic%2Felasticsearch-dsl-py/lists"}