pyes snippets

How to use ElasticSearch with Python

Tagged elasticsearch, python, pyes  Languages python

This is a short example on how to use ElasticSearch with Python.

First install pyes (pyes documentation).

Then run this code:

from pyes import *

index_name = 'xxx'
type_name = 'car'

conn = ES('', timeout=3.5)

docs = [
    {"name":"good",  "id":'1'},
    {"name":"bad", "id":'2'},
    {"name":"ugly", "id":'3'}

# Bulk index
for doc in docs:
    # index(doc, index, doc_type, id=None, parent=None, force_insert=False, op_type=None, bulk=False, version=None, querystring_args=None)
    conn.index(doc, index_name, type_name, id=doc['id'], bulk=True)

print conn.refresh()

# Search
def search(query):
    q = StringQuery(query, default_operator="AND")
    result =, indices=[index_name])
    for r in result:
        print r


You can also use CURL to verify that it works:

# Show index mapping
curl -vvv ""

# Delete index
curl -XDELETE -vvv ""

# Search
curl -vvv ""