Python Integrate with Elasticsearch

·

1 min read

Making use of open-source library to extend the functionality and data available

Pre-requites:

  • Elasticsearch & Kibana already setup

  • Python 3 & Above

In this tutorial, we will be using python to connect to elastic search. This is to demonstrate to use of elastic search as regular DB for the applications you use!

Let's start the python file by importing the elastic search library:

from elasticsearch import Elasticsearch

Thereafter, let's instantiate the elastic search client:

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

In order to read all the data from elastic search, you can simply put query:

# Read all data in an index
res = es.search(index='test', body={'query': {'match_all': {}}})
print('Got %d Hits:' % res['hits']['total']['value'])
for hit in res['hits']['hits']:
    print(hit['_source'])

The above query will read all the data in the index test

Not only to read, we can also update and insert data into the ES.

In order to add:

# Add data
doc = {
    'author': 'Smit Shah',
    'text': 'Connect to Elasticsearch'
}
res = es.index(index='test', id=1, body=doc)
print(res['result'])

To update:

# Update data
doc = {
    'author': 'Smit Shah',
    'text': 'Connect to Elasticsearch'
}
res = es.update(index='test', id=1, body={'doc': doc})
print(res['result'])

That is all for this tutorial.

Feel free to share your thoughts and feedback on comments or Twitter at @smit_shah_95