10

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?

1 Answer 1

21

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"]
             }
         }
      }) 
Sign up to request clarification or add additional context in comments.

2 Comments

docs don't mention addAll, this really helped
@Mozart What if the document is not present?. I want to create a document if it is not present and append to array if the document is present. Refer my exact question here - stackoverflow.com/questions/74489322/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.