{"id":5616,"library":"elasticsearch8","title":"Elasticsearch Python Client (v8)","description":"The official Python client for Elasticsearch versions 8.x and later. It provides a low-level client for interacting with the Elasticsearch REST API, supporting both synchronous and asynchronous operations. The current version is 8.19.3, and it follows the Elasticsearch release cycle for major updates.","status":"active","version":"8.19.3","language":"en","source_language":"en","source_url":"https://github.com/elastic/elasticsearch-py","tags":["elasticsearch","database","search","client","async"],"install":[{"cmd":"pip install elasticsearch8","lang":"bash","label":"Standard Installation"},{"cmd":"pip install elasticsearch8[async]","lang":"bash","label":"Asynchronous Client (HTTPX)"}],"dependencies":[],"imports":[{"note":"Despite installing `elasticsearch8`, the package exposes its main client class via the `elasticsearch` namespace for consistency with previous major versions of the client.","wrong":"from elasticsearch8 import Elasticsearch","symbol":"Elasticsearch","correct":"from elasticsearch import Elasticsearch"},{"note":"Requires `pip install elasticsearch8[async]` for asynchronous support.","symbol":"AsyncElasticsearch","correct":"from elasticsearch import AsyncElasticsearch"}],"quickstart":{"code":"import os\nfrom elasticsearch import Elasticsearch\n\n# --- Configuration for connecting to Elasticsearch ---\n# For Elastic Cloud (recommended)\nCLOUD_ID = os.environ.get(\"ELASTIC_CLOUD_ID\", \"\")\nAPI_KEY = os.environ.get(\"ELASTIC_API_KEY\", \"\") # Base64 encoded API Key ID and Key\n\n# For self-managed Elasticsearch\nES_HOST = os.environ.get(\"ELASTICSEARCH_HOST\", \"http://localhost:9200\")\nES_USERNAME = os.environ.get(\"ELASTICSEARCH_USERNAME\", \"elastic\")\nES_PASSWORD = os.environ.get(\"ELASTICSEARCH_PASSWORD\", \"changeme\")\n\nclient = None\nif CLOUD_ID and API_KEY:\n    print(\"Connecting to Elastic Cloud...\")\n    client = Elasticsearch(\n        cloud_id=CLOUD_ID,\n        api_key=API_KEY,\n    )\nelif ES_HOST:\n    print(f\"Connecting to self-managed Elasticsearch at {ES_HOST}...\")\n    client = Elasticsearch(\n        hosts=[ES_HOST],\n        basic_auth=(ES_USERNAME, ES_PASSWORD),\n        verify_certs=False # CAUTION: Only for local dev/testing without proper CA config\n    )\nelse:\n    raise ValueError(\n        \"Elasticsearch connection details not provided. Set ELASTIC_CLOUD_ID/ELASTIC_API_KEY \"\n        \"or ELASTICSEARCH_HOST/ELASTICSEARCH_USERNAME/ELASTICSEARCH_PASSWORD environment variables.\"\n    )\n\n# --- Verify Connection ---\nif client.ping():\n    print(\"Successfully connected to Elasticsearch!\")\nelse:\n    print(\"Could not connect to Elasticsearch. Please check your configuration.\")\n    exit(1)\n\n# --- Index a Document ---\nindex_name = \"my-documents\"\ndoc_id = \"1\"\ndocument = {\n    \"author\": \"John Doe\",\n    \"text\": \"Elasticsearch is a powerful open-source search and analytics engine.\",\n    \"timestamp\": \"2024-05-15T12:00:00Z\"\n}\n\nprint(f\"Indexing document with ID '{doc_id}' into index '{index_name}'...\")\nresponse = client.index(index=index_name, id=doc_id, document=document)\nprint(f\"Indexed document: Result - {response['result']}\")\n\n# --- Search for Documents ---\nprint(f\"Searching for documents in index '{index_name}'...\")\nsearch_query = {\"match\": {\"text\": \"search engine\"}}\nresponse = client.search(index=index_name, query=search_query)\n\nprint(f\"Found {response['hits']['total']['value']} hits:\")\nfor hit in response['hits']['hits']:\n    print(f\"  ID: {hit['_id']}, Source: {hit['_source']}\")\n\n# --- Clean Up (Optional) ---\n# client.indices.delete(index=index_name, ignore=[400, 404])\n# print(f\"Index '{index_name}' deleted (if it existed).\")\n\nclient.close()\nprint(\"Client connection closed.\")","lang":"python","description":"This quickstart demonstrates how to connect to Elasticsearch (either Elastic Cloud or self-managed), index a simple document, and perform a basic search. It uses environment variables for secure credential management. Remember to replace placeholder credentials with your actual ones."},"warnings":[{"fix":"Always use `from elasticsearch import Elasticsearch` after `pip install elasticsearch8`.","message":"The PyPI package name is `elasticsearch8`, but the import statement remains `from elasticsearch import Elasticsearch`. Attempting `from elasticsearch8 import Elasticsearch` will result in a `ModuleNotFoundError`.","severity":"gotcha","affected_versions":"8.0.0+"},{"fix":"Review the official migration guide for `elasticsearch-py` v8.x. Update `request_timeout` to `timeout`, explicitly manage connection details instead of relying on sniffing, and ensure proper CA certificates are configured for production environments or set `verify_certs=False` (with caution) for development.","message":"Migration from `elasticsearch-py` v7 to `elasticsearch8` (v8.x) introduces several breaking changes. Key changes include: `request_timeout` parameter renamed to `timeout`, removal of automatic `sniffing` for cluster discovery, and `verify_certs` defaulting to `True` for enhanced security.","severity":"breaking","affected_versions":"8.0.0+"},{"fix":"Use `from elasticsearch import AsyncElasticsearch` and ensure your application's event loop is managed correctly. `httpx` is used as the underlying async HTTP client.","message":"For asynchronous operations, you must install the `[async]` extra (e.g., `pip install elasticsearch8[async]`) and import `AsyncElasticsearch` instead of `Elasticsearch`. The default client is synchronous.","severity":"gotcha","affected_versions":"8.0.0+"},{"fix":"For production, ensure your system trusts the CA certificate used by Elasticsearch. For development, you can temporarily disable verification with `verify_certs=False` in the client constructor, but this is highly insecure for production use.","message":"Certificate verification is enabled by default (`verify_certs=True`). If connecting to a self-signed or improperly configured HTTPS endpoint without a trusted CA certificate, you will encounter SSL errors.","severity":"gotcha","affected_versions":"8.0.0+"},{"fix":"Always provide appropriate authentication details. For Elastic Cloud, generate an API Key. For self-managed, ensure the provided username/password has necessary permissions. Avoid hardcoding credentials in code; use environment variables.","message":"When connecting to Elastic Cloud, prefer `cloud_id` and `api_key` for authentication. For self-managed instances, `hosts` and `basic_auth` (username/password) are common. Failing to provide correct authentication will lead to connection errors.","severity":"gotcha","affected_versions":"8.0.0+"},{"fix":"Remove `doc_type` from all client methods (e.g., `index`, `get`, `update`, `delete`). Elasticsearch 8.x operates on a single type per index, simplifying interactions.","message":"The `doc_type` parameter is largely removed or ignored in Elasticsearch v8, as documents no longer have types. Using it in client calls may raise warnings or errors.","severity":"deprecated","affected_versions":"8.0.0+"}],"env_vars":null,"last_verified":"2026-04-12T00:00:00.000Z","next_check":"2026-07-11T00:00:00.000Z"}