# Script query - iterating through nested docs

**URL:** <https://discuss.elastic.co/t/script-query-iterating-through-nested-docs/268877>\
**Category:** Elasticsearch\
**Created:** [March 31, 2021, 8:20am UTC](https://discuss.elastic.co/t/script-query-iterating-through-nested-docs/268877 "2021-03-31T08:20:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bruno\_v](https://avatars.discourse-cdn.com/v4/letter/b/ee7513/32.png) [@bruno\_v](https://discuss.elastic.co/u/bruno_v)\
**Post date:** [March 31, 2021, 8:20am UTC](https://discuss.elastic.co/t/script-query-iterating-through-nested-docs/268877/1 "2021-03-31T08:20:14Z")

</div>

I have the following nested property in my mapping:

```auto
"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:

```auto
{
  "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().

---

<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:** [April 28, 2021, 8:21am UTC](https://discuss.elastic.co/t/script-query-iterating-through-nested-docs/268877/2 "2021-04-28T08:21:09Z")

</div>

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