Connecting to Elasticsearch with Python
In this example, we will use Python Elasticsearch client library.
- Prerequisites
You need to install Python on your machine. Depending on your operating system, download and install python. Note: This sample code uses Python3.
- Installation
Install Python Easticseaerch client package using pip
pip3 install elasticsearch
- Connecting to cluster
1 2 3 4 5 6 7 8 9 10 11 | es = Elasticsearch( ["xxx.xxx.xxx.xxx", "xxx.xxx.xxx.xxx", "xxx.xxx.xxx.xxx"], http_auth=("icelasticsearch","password"), scheme="https", port=9200 ) |
# SSL client authentication using client_cert and client_key
from ssl import create_default_context
1 2 3 4 5 6 7 8 | context = create_default_context(cafile='/Users/kinleetshering/Downloads/kcluster/cluster-ca-certificate.pem') es = Elasticsearch( ["xxx.xxx.xxx.xxx", "xxx.xxx.xxx.xxx", "xxx.xxx.xxx.xxx"], http_auth=("icelasticsearch","password"), scheme="https", port=9201, ssl_context=context ) |
- Indexing
1 2 3 4 5 6 7 8 9 10 11 | document = { "description": "this is a test", "timestamp": datetime.now() } es.index(index=index, doc_type="test", id=doc_id, body=document) print("Indexed document to index \"" + index + "\" with id " + str(doc_id)) |
- Getting a document
1 2 3 4 5 6 7 8 9 | result = es.get(index=index, doc_type="test", id=doc_id) retrieved_document = result['_source'] print("Retrieved document: {Id: " + result['_id'] + ", Description: " + retrieved_document['description'] + ", Timestamp: " + retrieved_document['timestamp'] + "}") |
Full Sample code
Replace public IP, username and password with your real setting
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | from datetime import datetime from ssl import create_default_context from elasticsearch import Elasticsearch context = create_default_context(cafile='/Users/kinleetshering/Downloads/kcluster/cluster-ca-certificate.pem') es = Elasticsearch( ["xxx.xxx.xxx.xxx", "xxx.xxx.xxx.xxx", "xxx.xxx.xxx.xxx"], http_auth=("icelasticsearch","password"), scheme="https", port=9201, ssl_context=context ) document = { "description": "this is a test", "timestamp": datetime.now() } index = "testing" doc_id = 1 es.index(index=index, doc_type="test", id=doc_id, body=document) print("Indexed document to index \"" + index + "\" with id " + str(doc_id)) result = es.get(index=index, doc_type="test", id=doc_id) retrieved_document = result['_source'] print("Retrieved document: {Id: " + result['_id'] + ", Description: " + retrieved_document['description'] + ", Timestamp: " + retrieved_document['timestamp'] + "}") |
Submit Comment