AO_
AO_

Reputation: 2894

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?

Upvotes: 10

Views: 14022

Answers (1)

Mushtu
Mushtu

Reputation: 487

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"]
             }
         }
      }) 

Upvotes: 21

Related Questions