Adding new calculated field to an object inside an array (foreach)

My first post here. So please bear with me.

Sample document:

{
  "persons" : [
    {
      "id" : "1",
      "name" : "John Doe"
    },
    {
      "id" : "2",
      "name" : "Jane Doe"
    }
  ]
}

I would like to add a new field named "calcValue" to each person object as follows:
calcValue = id + '#' + name


Tried foreach processor but getting concurrent modification exception.

"processors": [
    {
      "foreach": {
        "field": "persons",
        "processor": {
          "script": {
            "source": "ctx.persons.add(params.calcValue)",
            "params": {
              "calcValue": "_ingest._value.id+'#'+_ingest._value.name"
            }
          }
        }
      }
    }

I understand why ConcurrentModificationException was raised but I am unable to get this working. Please can someone help.

I'd do something like this:

POST _ingest/pipeline/_simulate
{
  "docs": [
    {
      "_id": "foo",
      "_source": {
        "persons": [
          {
            "id": "1",
            "name": "John Doe"
          },
          {
            "id": "2",
            "name": "Jane Doe"
          }
        ]
      }
    }
  ],
  "pipeline": {
    "processors": [
      {
        "script": {
          "source": """
            int total = 0;
            for (int i = 0; i < ctx['persons'].length; ++i) {
              String text = ctx['persons'][i]['id']+"#"+ctx['persons'][i]['name'];
              ctx['persons'][i]['calcValue']=text;
            }
"""
        }
      }
    ]
  }
}

It gives:

{
  "docs": [
    {
      "doc": {
        "_index": "_index",
        "_type": "_type",
        "_id": "foo",
        "_source": {
          "persons": [
            {
              "name": "John Doe",
              "id": "1",
              "calcValue": "1#John Doe"
            },
            {
              "name": "Jane Doe",
              "id": "2",
              "calcValue": "2#Jane Doe"
            }
          ]
        },
        "_ingest": {
          "timestamp": "2018-04-13T13:04:46.213Z"
        }
      }
    }
  ]
}
1 Like

Thanks a lot Sir. You are a legend. :heart_eyes:

1 Like

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