Sunday, 8 September 2019

Connect To Elasticsearch Using Python3 | Example of Python-Elasticsearch

How To Insert and search Data To/From Elasticsearch Using Python or Python3

# Prerequisites:

  • python3
  • ubuntu 18.04
  • java1.8
  • Create a project directory python-elasticsearch with two files main.py and requirement.txt

# Install Elasticsearch module

  • Write "elasticsearch" in requirement.txt and run following command in terminal
  • sudo pip3 install -r requirement.txt

# Install Elasticsearch on Ubuntu

  • sudo apt update
  • sudo apt-get install apt-transport-http
  • wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
  • sudo add-apt-repository "deb https://artifacts.elastic.co/packages/7.x/apt stable main"
  • sudo apt update
  • sudo apt install elasticsearch
  • To start Elasticsearch process
    sudo /etc/init.d/elasticsearch start
    sudo /etc/init.d/elasticsearch status
  • Test setup
    curl -X GET "http://localhost:9200/?pretty"

# Writing Python Code To Store And Fetch Data


# Import elasticsearch module
from elasticsearch import Elasticsearch 
#import json


# Method to store data in elasticsearch
def send_data_to_es(data):
 es=Elasticsearch(['localhost:9200'])
 res = es.index(index='employee',doc_type='devops',body=data)
 print(res)

# Method to get data from elasticsearch
def get_data_from_es():
 es=Elasticsearch(['localhost:9200'])
 r = es.search(index="employee", body={"query": {"match": {'Name':'john'}}})
 print(r)
 print(type(r))
 print(r["hits"]["hits"][0]["_source"])

# Main function from where the execution starts
if __name__== "__main__":
 # Define a dictoinary having required data to be stored in ES
 data = {"Name": "john", "Age":27, "address": "winterfell"}
 # Call method to store data in ES
 send_data_to_es(data)
 # Call method to get data from ES
 get_data_from_es()

# Running the code

To run the above code simply run the following command in the terminal from root directory of python-elasticsearch project
python3 main.py

# Output 


0 comments:

Post a Comment

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel