Python Client Examples ====================== .. meta:: :description: Example code for connecting to Elasticsearch in python with elasticsearch-py Installation ------------ `Elasticsearch-py `_ is the recommended Python client for working with Elasticsearch. .. code-block:: bash $ pip install elasticsearch Connecting ------------ HTTP: ~~~~~~ .. code-block:: python 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. .. code-block:: bash $ pip install certifi .. code-block:: python 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 ----------------- .. code-block:: python 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 --------------- .. code-block:: python es.get(index='test_index', id='1') Search (DSL) ----------------------- .. code-block:: python es.search(index='test_index', body={ 'query': { 'match': { 'title': 'Python', } } }) Delete a document ----------------- .. code-block:: python es.delete(index='test_index', doc_type='post', id=1)