How to Append to an Array in Elasticsearch Using Elasticsearch-Py

  • Home /
  • Blog Posts /
  • How to append to an Array in Elasticsearch using elasticsearch-py

If you are using the Official ElasticSearch Python library (Docs), and you want to create an index:

doc = {
    "something": "123a",
    "somethingelse": "456b",
    "timestamp": datetime.now(),
    "history": []
}
es.index(index="someindex", doc_type="somedoctype", id="someid", body=doc)

You can append items to the history each time, instead of overriding them, like this:

es.update(index="someindex", doc_type="somedoctype", id="someid",
    body={
        "script" : {
            "source": "ctx._source.history.addAll(params.history)",
            "lang": "painless",
            "params" : {
                "history" : ["item1","item2"]
            }
        }
    })

This uses scripted updates in Elasticsearch, for appending to an array.