Dennis
Dennis

Reputation: 415

Iterate over array update_by_query

I have an array called 'tags' in the source of all my Elasticsearch docs in a particular index. I am trying to lowercase all values in the tag array using a update_by_query painless script.

This seems like a simple operation, here is what I have tried:

POST my_index/_update_by_query
{
  "script": {
  "source": """
  for (int i = 0; i < ctx._source['tags'].length; ++i) {
   ctx._source['tags'][i].value = ctx._source['tags'][i].value.toLowerCase() 
    }
  """,
  "lang": "painless"
  },
  "query": {
    "match_all": {}
  }
}

I am getting a null pointer exception when executing the above code. I think I may have the syntax slightly off. Having lots of trouble getting this to work, and would appreciate any help.

Upvotes: 1

Views: 1297

Answers (1)

Dennis
Dennis

Reputation: 415

I fixed the issue...there were multiple small syntax errors but I needed to add an exists check:

POST my_index/_update_by_query
{
 "script": {
    "source": """
    if (ctx._source.containsKey('tags')) {
      for (int i = 0; i < ctx._source['tags'].length; ++i) {
        ctx._source['tags'][i] = ctx._source['tags'][i].toLowerCase() 
      }
    }
    """,
    "lang": "painless"
  },
  "query": {
    "match_all": {}
  }
}

Upvotes: 1

Related Questions