4

Look here for a similar example:

https://stackoverflow.com/a/33247409/1575066

from elasticsearch import Elasticsearch
es = Elasticsearch("localhost:9200")
es.update(index='test',doc_type='test1',id='1',body={'doc' {'username':'Tom'},'doc_as_upsert':True})

But now imagine the goal is to append to an array or to increment a previous value (without having to get the document first).

If you go with official requests, this is in the documentation:

POST /website/pageviews/1/_update
{
   "script" : "ctx._source.views+=1",
   "upsert": {
       "views": 1
   }
}

I was wondering how to accomplish appending to an array (just simply adding to a default list). It appeared elasticsearch's own examples are easier than anything I can find specifically for Python.

I read a post before about people just using python requests for doing elasticsearch stuff, and I'm thinking there might be a point to it...

Community
  • 1
  • 1
PascalVKooten
  • 20,643
  • 17
  • 103
  • 160

1 Answers1

3

You can put your script inside the body parameter.

from elasticsearch import Elasticsearch

es = Elasticsearch()

es.update(
    index="test",
    doc_type="test1",
    id="1",
    body={"script": "ctx._source.tags+=new_tag",
          "params": {
             "new_tag" : "search"
            }
          }
    )

More on update api

Here tags is an array and I am appending search to it. Also you need to enable scripting for this or you can put script in a file and put that file inside config/scripts folder. Syntax might be different depending on ES version. Let me know if it does not work.

MasterScrat
  • 7,090
  • 14
  • 48
  • 80
ChintanShah25
  • 12,366
  • 3
  • 43
  • 44
  • There is a [`script`](http://elasticsearch-py.readthedocs.org/en/master/api.html#elasticsearch.Elasticsearch.update) parameter, also. Not sure how `params` are added, though – OneCricketeer Jan 27 '16 at 20:11
  • it is some `url encoded` thing, I have never used it, but you can use body param, from the docs, `body – The request definition using either script or partial doc` which works for me – ChintanShah25 Jan 27 '16 at 20:15
  • Yeah, using the body works. For the url encoded piece, it's probably something like this http://stackoverflow.com/a/5607708/2308683 – OneCricketeer Jan 27 '16 at 20:35