Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 268
AO_ Avatar asked Dec 08 '22 14:12

AO_


1 Answers

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"]
             }
         }
      }) 
like image 134
Mushtu Avatar answered May 16 '23 08:05

Mushtu