Install Python Elasticsearch Client on CentOS 7 and It’s Usage

  • 5
    Shares

python elasticsearch client
Python Elasticsearch Client

elasticsearch-py   is an official low-level client for Elasticsearch. Its goal is to provide common ground for all Elasticsearch-related code in Python. The full documentation is available at http://elasticsearch-py.rtfd.org/

 

Install elasticsearch-py and its Versioning

To use Elasticsearch with our all time favorite language; Python, it gets easier if we install elasticsearch-py package.

ansible@localhost$ pip install elasticsearch

Now we will be able to use this package to index and search data using Python.

The library is compatible with all Elasticsearch versions since 0.90.x but you have to use a matching major version:

For Elasticsearch 6.0 and later, use the major version 6 (6.x) of the library.

For Elasticsearch 5.0 and later, use the major version 5 (5.x) of the library.

And For Elasticsearch 2.0 and later, use the major version 2 (2.x) of the library, and so on.

The recommended way to set your requirements in your setup.py or requirements.txt is:

# 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

 

elasticsearch-py Example Usage

We have implemented elasticsearch python client to import Ansible Tower API data into ELK Stack. You can download full code from Github.

Sample Example Uses

# Import elasticsearch-py package
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()

# Connect to elasticsearch, by default connect to localhost:9200
es = Elasticsearch()
# Connect to hosts and http_auth using params
es = Elasticsearch([es_host], http_auth=(es_user, es_password))

# Create Index
doc_data = {
    'name': 'Devops',
    'timestamp': datetime.now(),
}
result = es.index(index="test-index", doc_type='test-type', id=1, body=doc_data)
print(result['created'])

# Get documents from index
result = es.get(index="test-index", doc_type='test-type', id=1)
print(result['_source'])

# Search documents from index
result = es.search(index="test-index", body={"query": {"match_all": {}}})
print(result)

References:
https://elasticsearch-py.readthedocs.io/en/master/
https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/index.html
https://github.com/elastic/elasticsearch-py
https://pypi.python.org/pypi/elasticsearch/5.0.0

 

 

Avinash Pawar

DevOps Practitioner interested in learning new technologies and interested in sharing the knowledge with others.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Avinash Pawar

DevOps Practitioner interested in learning new technologies and interested in sharing the knowledge with others.

Leave a Reply