Python Client Examples¶
Installation¶
Elasticsearch-py is the recommended Python client for working with Elasticsearch.
$ pip install elasticsearch
Connecting¶
HTTP:¶
from elasticsearch import Elasticsearch
try:
es = Elasticsearch(
['iad1-10202-0.es.objectrocket.com', 'iad1-10202-1.es.objectrocket.com', 'iad1-10202-2.es.objectrocket.com', 'iad1-10202-3.es.objectrocket.com'],
http_auth=('YOUR_USERNAME', 'YOUR_PASSWORD'),
port=10202,
)
print "Connected", es.info()
except Exception as ex:
print "Error:", ex
HTTPS:¶
Installation¶
Certifi is package for validating the trustworthiness of SSL certificates when connecting securely to your instance.
$ pip install certifi
from elasticsearch import Elasticsearch
import certifi
try:
es = Elasticsearch(
['iad1-10202-0.es.objectrocket.com', 'iad1-10202-1.es.objectrocket.com', 'iad1-10202-2.es.objectrocket.com', 'iad1-10202-3.es.objectrocket.com'],
http_auth=('YOUR_USERNAME', 'YOUR_PASSWORD'),
port=20202,
use_ssl=True,
verify_certs=True,
ca_certs=certifi.where(),
)
print "Connected", es.info()
except Exception as ex:
print "Error:", ex
Index a document¶
es.index(index='test_index', doc_type='post', id=1, body={
'author': 'John Doe',
'blog': 'Learning Elasticsearch',
'title': 'Using Python with Elasticsearch',
'tags': ['python', 'elasticsearch', 'tips'],
})
Get a document¶
es.get(index='test_index', id='1')
Search (DSL)¶
es.search(index='test_index', body={
'query': {
'match': {
'title': 'Python',
}
}
})
Delete a document¶
es.delete(index='test_index', doc_type='post', id=1)