{"id":5615,"library":"elasticsearch-dsl","title":"Elasticsearch DSL","description":"Elasticsearch DSL is a Python client that provides a high-level, declarative, and object-oriented way to write and execute queries against Elasticsearch. It allows users to define document mappings as Python classes and build complex search queries and aggregations using Python objects. As of version 8.18.0, the `elasticsearch-dsl` package's functionality has been integrated directly into the `elasticsearch-py` client library under the `elasticsearch.dsl` namespace. While the `elasticsearch-dsl` package still exists for compatibility, active development now continues within the main `elasticsearch-py` project. Releases are generally tied to Elasticsearch major/minor versions or feature additions.","status":"renamed","version":"8.18.0","language":"en","source_language":"en","source_url":"https://github.com/elasticsearch/elasticsearch-dsl-py","tags":["elasticsearch","search","database","orm","dsl","client"],"install":[{"cmd":"pip install elasticsearch-dsl","lang":"bash","label":"Install for compatibility (re-exports `elasticsearch.dsl`)"},{"cmd":"pip install elasticsearch","lang":"bash","label":"Install the main client (contains `elasticsearch.dsl`)"}],"dependencies":[{"reason":"Provides the underlying client connection and the actual DSL implementation in v8.18.0+","package":"elasticsearch","optional":false}],"imports":[{"note":"While functional in v8.18.0 via compatibility layer, future-proof approach is 'from elasticsearch.dsl import Search'","symbol":"Search","correct":"from elasticsearch_dsl import Search"},{"note":"`DocType` was renamed to `Document` in v7.0.0. Using `DocType` is deprecated and will fail in v8.","wrong":"from elasticsearch_dsl import DocType","symbol":"Document","correct":"from elasticsearch_dsl import Document"},{"note":"Manages connections to Elasticsearch clusters.","symbol":"connections","correct":"from elasticsearch_dsl import connections"},{"note":"Common field types for defining document mappings.","symbol":"Text, Keyword, Integer, Date","correct":"from elasticsearch_dsl import Text, Keyword, Integer, Date"}],"quickstart":{"code":"import os\nfrom elasticsearch_dsl import Document, Text, Keyword, connections, Search\n\n# Configure connection to Elasticsearch\n# Replace with your Elasticsearch host and credentials if necessary\nES_HOST = os.environ.get('ES_HOST', 'http://localhost:9200')\n# For cloud deployments or API key auth, uncomment and set these:\n# ES_CLOUD_ID = os.environ.get('ES_CLOUD_ID')\n# ES_API_KEY = os.environ.get('ES_API_KEY')\n# ES_USERNAME = os.environ.get('ES_USERNAME', 'elastic')\n# ES_PASSWORD = os.environ.get('ES_PASSWORD', 'changeme')\n\nconnections.create_connection(hosts=[ES_HOST]) # Example for local or basic auth\n# For cloud/API key: connections.create_connection(cloud_id=ES_CLOUD_ID, api_key=ES_API_KEY)\n\n# Define a Document (schema for your data)\nclass Article(Document):\n    title = Text(fields={'keyword': Keyword()})\n    author = Text(fields={'keyword': Keyword()})\n    published_date = Keyword()\n    word_count = Keyword()\n\n    class Index:\n        name = 'my-articles'\n        settings = {\n            'number_of_shards': 1,\n            'number_of_replicas': 0\n        }\n\n# Create the index (if it doesn't exist) based on the Document definition\nArticle.init()\n\n# Index some data\narticle1 = Article(meta={'id': '1'}, title='Python for AI', author='John Doe', published_date='2023-01-01', word_count='2000')\narticle1.save()\n\narticle2 = Article(meta={'id': '2'}, title='Elasticsearch DSL Basics', author='Jane Smith', published_date='2023-03-15', word_count='1500')\narticle2.save()\n\n# Refresh the index to make documents searchable immediately\nconnections.get_connection().indices.refresh(index='my-articles')\n\n# Perform a search\ns = Search(index='my-articles').query(\"match\", title=\"python\")\nresponse = s.execute()\n\nprint(f\"Found {response.hits.total.value} results for 'python':\")\nfor hit in response:\n    print(f\"ID: {hit.meta.id}, Title: {hit.title}, Author: {hit.author}\")\n\n# Example of a more complex search with filtering\ns = Search(index='my-articles') \\\n    .query(\"match_all\") \\\n    .filter(\"range\", word_count={\"gte\": 1500}) \\\n    .exclude(\"match\", author=\"john\")\n\nresponse = s.execute()\nprint(f\"\\nFound {response.hits.total.value} results for complex query:\")\nfor hit in response:\n    print(f\"ID: {hit.meta.id}, Title: {hit.title}, Author: {hit.author}\")\n\n# Cleanup (optional)\n# connections.get_connection().indices.delete(index='my-articles', ignore=[400, 404])","lang":"python","description":"This quickstart demonstrates how to define an Elasticsearch document mapping using a Python class, establish a connection to Elasticsearch, index a few documents, and perform both simple and complex search queries using the DSL. It connects to a local Elasticsearch instance by default but can be configured for cloud or API key authentication."},"warnings":[{"fix":"For new projects, `pip install elasticsearch` and change imports from `from elasticsearch_dsl import ...` to `from elasticsearch.dsl import ...`. For existing projects using `elasticsearch-dsl`, upgrading to 8.18.0 may not require immediate import changes due to compatibility layers, but be aware of the underlying change and plan for future migration.","message":"As of v8.18.0, the `elasticsearch-dsl` package has been integrated into `elasticsearch-py` as the `elasticsearch.dsl` namespace. While `pip install elasticsearch-dsl` still works and provides a compatibility layer (re-exporting `elasticsearch.dsl`), the recommended long-term approach for new projects or migrations is to `pip install elasticsearch` and use `from elasticsearch.dsl import ...` directly. The `elasticsearch-dsl` GitHub repository is now largely archived, with development continuing in the `elasticsearch-py` repository.","severity":"breaking","affected_versions":">=8.18.0"},{"fix":"Consult the official migration guide for 7.x to 8.x: `https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/client-dsl-migrating.html#_migrating_from_7_x_to_8_x`. Update `Document.create()` calls to `Document.save(op_type='create')` and adjust `connections.create_connection()` parameters.","message":"Migrating from `elasticsearch-dsl` 7.x to 8.x involves significant breaking changes. Key changes include the removal of `Document.create()` (replaced by `Document.save(op_type='create')`), changes in how `connections` are configured (`connections.create_connection()` is now preferred over `connections.configure()`), and updates to default serializers for `datetime` objects.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Ensure `elasticsearch_dsl.connections.create_connection(hosts=['your_host'])` (or similar for cloud/auth) is called at application startup before any `Document` operations or `Search` queries are made.","message":"Not properly initializing the `connections` object before interacting with Elasticsearch will lead to `ConnectionError` or `ImproperlyConfigured` exceptions. The `connections` object must be configured with at least host information.","severity":"gotcha","affected_versions":"all"},{"fix":"For fields that require both full-text search and exact matching/aggregation, define them as `Text(fields={'keyword': Keyword()})`. The `Text` part allows analysis, and the `keyword` sub-field provides an unanalyzed version.","message":"When defining document fields, using `Keyword()` without `Text()` for a field you intend to analyze (e.g., for full-text search) will prevent that field from being tokenized. Similarly, defining a `Text()` field without an explicit `Keyword()` sub-field makes it harder to perform exact match queries or aggregations on the raw string.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}