Home Navigation

Friday 7 July 2023

Connect to elasticsearch using python

 Based on your elasticsearch version, you have to install the Python Elasticsearch Client.

I am using elasticsearch version 7.10

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

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

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

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

Prepare your environment

python3 -m venv backend
source backend/bin/activate
pip3 install elasticsearch===7.10.1

Code

from elasticsearch import Elasticsearch
from elasticsearch.exceptions import RequestError

# Create an instance of Elasticsearch with TLS options
es = Elasticsearch(
'https://<user>:<password>@<host>:<port>',
ca_certs='<cert_file>'
)

print("=======================================================")

info = es.info()
print(info)
print("=======================================================")

# Test the connection and create an index
index_name = 'my_index'

try:
es.indices.create(index=index_name)
print(f"Index '{index_name}' created successfully.")
except RequestError as e:
if e.error == 'resource_already_exists_exception':
print(f"Index '{index_name}' already exists.")
else:
print(f"An error occurred while creating index '{index_name}': {e}")


document = {
'title': 'Example Document',
'content': 'This is the content of the document.'
}

# Add the document to the index
response = es.index(index=index_name, body=document)
print("=======================================================")
print(response)

Run

python3 app.py


Enjoy!


Ref: https://elasticsearch-py.readthedocs.io/en/v7.10.1/

https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/getting-started-python.html