Accessing nested array of objects in elastic search throws null pointer exception using painless script

Here is the schema:

"mappings": {
    "_doc": {
      "properties": {
        "createdAt": {
          "type": "date"
        },
        "files": {
          "type": "nested",
          "properties": {
            "name": {"type": "text"},
            "contentType": {"type": "text"}
          }
        }
      }
    }
  }
}

if i try to run a painless script to iterate through the document:

{
   "script": {
      "inline": """
      int total = 0;
      for (int i = 0; i < ctx._source.files.length; ++i) {
            if (ctx._source.files[i].name== "1") {
            ctx._source.files.add(params.object)
          
          }
        """
   }
}
}

It throws me null pointer exception on "ctx._source.files"

Any idea why does it happen? and how to access nested array of objects in ES 6.7

You don't provide the context in which you want to use your script. I'm assuming you want to do an Update by Query or something like that?

One problem with your script is that you don't check whether every document actually contains a files object. I think the null pointer you're seeing is because of at least one document without any files.

Another problem with your script is that you're concurrently trying to change the files list while you're iterating over it. That will also lead to problems.

Here's how I would write the script:

"""
      if (ctx._source.files != null) {
        def list = [];
        
        for (file in ctx._source.files) {
          if ("1".equals(file.name)) {
            list.add(params.object)
          }
        }
        
        for (item in list) {
          ctx._source.files.add(item)
        }
      }
"""

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