shantanuo
shantanuo

Reputation: 32220

update an elasticsearch document

This code is working as expected. But instead of adding the third country as another document, I want to update the first document.

DELETE /test_index

PUT /test_index

PUT /test_index/doc/1
{
   "parent": [
      {
         "name": "India",
         "label": "IN"
      },
      {
         "name": "China",
         "label": "CN"
      }
   ]
}

PUT /test_index/doc/2
{
   "parent": [
      {
         "name": "Pakistan",
         "label": "PK"
      }
   ]
}

So that the Document ID 1 will have 3 countries India, China and Pakistan. I guess I need update API with doc_as_upsert parameter. But I am not sure how to write the JSON.

Upvotes: 1

Views: 1180

Answers (2)

shantanuo
shantanuo

Reputation: 32220

Adding to val's answer, I can use upsert if the document does not already exist.

POST /test_index/doc/1/_update
{
   "script": {
      "inline": "ctx._source.parent += ['name': name, 'label': label]",
      "params": {
         "name": "Pakistan",
         "label": "PK"
      }
   },
   "upsert": {"parent" : [{
      "name": "Pakistan",
      "label": "PK"
   }]
   }
}

UPDATE

Bulk API using upsert will look something like this...

POST /test_index/doc/_bulk
{ "update" : { "_id" : "1"} }
{ "script" : { "inline": "ctx._source.parent += ['name': name, 'label': label]", "lang" : "groovy", "params" : {"name" : "Pakistan", "label": "PK"}}, "upsert": {"parent" : [{"name": "Pakistan", "label": "PK" }] }}

Upvotes: 0

Val
Val

Reputation: 217564

You can make a scripted updated using the update API:

curl -XPOST 'localhost:9200/test_index/doc/1/_update' -d '{
    "script" : {
        "inline": "ctx._source.parent += ['name': name, 'label': label]",
        "params" : {
            "name" : "Pakistan",
            "label": "PK"
        }
    }
}'

UPDATE

If you want to use this in a bulk query, it is also possible

curl -XPOST 'localhost:9200/test_index/doc/_bulk' -d '
{ "update" : { "_id" : "1"} }
{ "script" : { "inline": "ctx._source.parent += ['name': name, 'label': label]", "lang" : "groovy", "params" : {"name" : "Pakistan", "label": "PK"}}}
'

Upvotes: 1

Related Questions