Script query - iterating through nested docs

I have the following nested property in my mapping:

"books": {
  "type": "nested",
  "properties": {
       "book_id": {
          "type": "keyword"
       },
       "book_name": {
           "type": "keyword"
       }
   }
}

But not all of the content in my index has books, so it might be present in the main doc or not.

If I want a query that iterates through each book inside my books property, to check if any of them don't have an ID, I thought about doing the following nested/script query:

{
  "query": {
    "nested": {
      "query": {
        "script": {
          "script":  """
            def hasBookWithoutId = false;
            if (doc != null) {
              for (book in doc['books']) {
                if (book['book_id'] == null) {
                  hasBookWithoutId = true;
                }
              }
            }
            return hasBookWithoutId;
          """
        }
      },
      "path": "books"
    }
  }
}

Doc seems to be taking the context of nested property books, which allows me to check if books exists in the main document, but how do I iterate it?

doc['books'] does not exist and I can't access doc.values().

1 Like