# Update nested documents via painless

**URL:** <https://discuss.elastic.co/t/update-nested-documents-via-painless/330676>\
**Category:** Elasticsearch\
**Tags:** painless\
**Created:** [April 24, 2023, 4:12pm UTC](https://discuss.elastic.co/t/update-nested-documents-via-painless/330676 "2023-04-24T16:12:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tudor\_Plugaru](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tudor_plugaru/32/117748_2.png) [@Tudor\_Plugaru](https://discuss.elastic.co/u/Tudor_Plugaru)\
**Post date:** [April 24, 2023, 4:12pm UTC](https://discuss.elastic.co/t/update-nested-documents-via-painless/330676/1 "2023-04-24T16:12:47Z")

</div>

Hi,

Assuming we have the following mapping

```auto
"mappings": {
  "properties": {
    "id": {
      "type": "text",
    },
    "messages": {
      "type": "nested",
      "dynamic": "strict",
      "properties": {
        "id": {
          "type": "keyword"
        }
      }
    }
  }
}

```

We are using the `_bulk` and sending a bunch of UpdateRequest actions with a painless script like the following:

```auto
if (ctx._source.messages == null) {ctx._source.messages = new ArrayList();} ctx._source.messages.removeIf(c -> { c.id == params.message.id }); ctx._source.messages.add(params.message);

```

As you can see, if we have a new update for a given nested message with a specific `id`, we just remove the old version and add the new version.  
I am just wondering if this is the best approach in terms of performance on ES side, or it's worth extending the script to actually go field by field and update to the new value, or even check if the value of the nested message changed and only update it if it actually changed.

What is the overhead on ES side when doing full replacement instead of updating the fields? I know that when a document is updated, a new full version of the doc is created, but does this apply in this specific example?

Thanks.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [May 22, 2023, 4:13pm UTC](https://discuss.elastic.co/t/update-nested-documents-via-painless/330676/2 "2023-05-22T16:13:19Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
