Search code examples
elasticsearchelasticsearch-py

How to append to an array in Elasticsearch using elasticsearch-py


Using the Official ElasticSearch Python library (Docs)

I create an index:

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

I would like to append items to the history each time, instead of overriding them:

es.update(index="someindex", doc_type="somedoctype", id="someid",
          body={"doc": {
                "history": {
                    "123abc": "abc", "456def": "def", "timestamp": datetime.now()
                }
               }
          })

What do I have to change in the second code snippet to get it to append to the history array/list instead of overriding it each time?


Solution

  • You can use scripted updates in elasticsearch. For appending to array try something 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"]
                 }
             }
          })