9

This is my document

{
    "name": "andrew",
    "b": [{"x":"c1", "y": 0}, {"x":"c2", "y": 0}]
}

I want to find element in the array field "b" and update the entire object. I tried this script but it does not update. Any ideas?

{
    "script": "for (item in ctx._source.b) { if (item['x'] == x_id) { item = newobj; } };",
    "params": {
        "x_id": "c1",
        "newobj" : {"x":"c1", "y": 4222}
    },
    "lang":"groovy"
}

1 Answer 1

13

Use this instead:

{
  "script": "for (int i=0;i<ctx._source.b.size();i++) { item=ctx._source.b[i]; if (item['x'] == x_id) { ctx._source.b[i] = newobj} };",
  "params": {
    "x_id": "c1",
    "newobj": {
      "x": "c1",
      "y": 4222
    }
  },
  "lang": "groovy"
}
Sign up to request clarification or add additional context in comments.

2 Comments

what to use update API or update query API while executing ?
I hope update API works, If you want to update many docs using query you have to use update query API

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.