In [1]:
from datetime import datetime

In [2]:
from elasticsearch import Elasticsearch

In [3]:
# by default we connect to localhost:9200
es = Elasticsearch()

In [4]:
# datetimes will be serialized
es.index(index="my-index", doc_type="test-type", id=42, body={"any": "data", "timestamp": datetime.now()})


Out[4]:
{'_type': 'test-type',
 'created': False,
 '_index': 'my-index',
 '_version': 9,
 '_id': '42'}

In [5]:
doc = {
    'author': 'kimchy',
    "email":      "john@smith.com",
    "first_name": "John",
    "last_name":  "Smith",
    "info": {
        "bio":         "Eco-warrior and defender of the weak",
        "age":         25,
        "interests": [ "dolphins", "whales" ]
    },
    "join_date": "2014/05/01",
    "timestamp": datetime.now()
}

In [6]:
res = es.index(index="test-index", doc_type='goo', id=1, body=doc)
print(res['created'])


False

In [7]:
res = es.get(index="test-index", doc_type='goo', id=1)
print(res['_source'])


{'timestamp': '2015-03-10T13:44:47.509018', 'email': 'john@smith.com', 'info': {'bio': 'Eco-warrior and defender of the weak', 'interests': ['dolphins', 'whales'], 'age': 25}, 'author': 'kimchy', 'last_name': 'Smith', 'join_date': '2014/05/01', 'first_name': 'John'}

In [8]:
res = es.search(index="test-index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total'])


Got 2 Hits:

In [20]:
for hit in res['hits']['hits']:
    print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])


2010-10-10T10:10:10 kimchy: Elasticsearch: cool. bonsai cool.
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-20-ba18ddbe97fb> in <module>()
      1 for hit in res['hits']['hits']:
----> 2     print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])

KeyError: 'author'

In [ ]: