| endpoint | _connection |
|---|---|
| lang | python |
| es_version | 9.3 |
| client | elasticsearch==9.3.0 |
Use the Elasticsearch class from the elasticsearch package to
create a client. The simplest approach uses basic authentication
with a username and password:
from elasticsearch import Elasticsearch
client = Elasticsearch(
"http://localhost:9200",
basic_auth=("elastic", "your-password"),
)
info = client.info()
print(f"Connected to {info['cluster_name']} (v{info['version']['number']})")Install the client with pip:
pip install elasticsearch==9.3.0For production use, API keys are preferred over username/password. Pass the base64-encoded API key directly:
client = Elasticsearch(
"http://localhost:9200",
api_key="your-base64-api-key",
)Or use a tuple of (id, api_key) if you have them separately:
client = Elasticsearch(
"http://localhost:9200",
api_key=("key-id", "key-secret"),
)Configure timeouts, retries, and TLS for production deployments:
client = Elasticsearch(
"https://my-cluster.example.com:9243",
api_key="your-base64-api-key",
request_timeout=30,
max_retries=3,
retry_on_timeout=True,
ca_certs="/path/to/ca.crt",
)To verify the connection is working:
if client.ping():
print("Connected")
else:
print("Connection failed")