Connect to server
Tags: #elastic #search #snippet
Author: Ebin Paulose

1. Prerequisites

  • python3
  • ubuntu 18.04
  • java1.8

2. Elasticsearch on local machine

Install Linux packages
1
$ sudo apt update
2
$ sudo apt-get install apt-transport-http
3
$ wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
4
$ sudo add-apt-repository "deb https://artifacts.elastic.co/packages/7.x/apt stable main"
5
$ sudo apt update
6
$ sudo apt install elasticsearch
Copied!
Check status of Elasticsearch server (Local)
1
$ sudo /etc/init.d/elasticsearch status
Copied!
Start Elasticsearch server (Local)
1
$ sudo /etc/init.d/elasticsearch start
Copied!
Note : Install Java 1.8 and set Java environment variables path

3. Elasticsearch on cloud

Step 1: Login to https://www.elastic.co/ and create a deployment
Step 2: On successful deployment get credentials
Step 3: Create Elasticsearch credentials JSON
Credentials Json format
1
{
2
"endpoint": "< Elasticsearch endpoint from elasticsearch cloud >",
3
"port": "< Port number as mentioned in elasticsearch cloud >",
4
"user": "< User as mentioned in elasticsearch cloud >",
5
"password": "< Elasticsearch cloud user password >",
6
"protocol": "https"
7
}
Copied!

4. Python connector for Elasticsearch

Input

Import library

1
from elasticsearchconnector import ElasticsearchConnector
Copied!

Model

1
instance = ElasticsearchConnector("sample_credentials.json")
Copied!

Send data to Elasticsearch server

1
# parameters = {'index':'< Name of the index >','type':' < Document name > '}
2
parameters = {'index':'students','type':'engineering'}
3
# data = { < Key value pairs > }
4
data = {"Name": "Poul", "Age":20, "address": "New york"}
5
result = instance.save_data(parameters,data)
Copied!

Search data from Elasticsearch server

1
# parameters = {'index':'< Name of the index >','type':' < Document name > '}
2
parameters = {'index':'students','type':'engineering'}
Copied!

Output

1
# Single search
2
q1 = {"query": {"match": {'Name':'Poul'}}}
3
result = instance.search_data(parameters,[q1],search_type='search')
4
print(result)
Copied!
1
# Multiple search
2
q1 = {"query": {"match": {'Name':'Poul'}}}
3
q2 = {"query": {"match": {'Age':27}}}
4
result = instance.search_data(parameters,[q1,q2],search_type='msearch')
5
print(result)
Copied!
Copy link
Edit on GitHub