Nested Query Help to find documents where all nested documents match a given criteria

Hi,

I was wondering if it is possible to find documents in ElasticSearch using a nested query where all nested documents within a document match a given criteria?

Thanks.

A nested query will return a document if any nested objected matches. But you're saying you only want to find documents where all nested objects match?

There may be more elegant ways of doing this, but one approach I can think of is by using a nested must_not clause inside another must_not clause. Or in other words: find documents that do not have a nested object that does not match the query.

For example, given this mapping and these documents:

PUT my_index
{
  "mappings": {
    "properties": {
      "my_nested_field": {
        "type": "nested",
        "properties": {
          "my_field": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

PUT my_index/_doc/1
{
  "my_nested_field": [
    {
      "my_field": "a"
    },
    {
      "my_field": "a"
    }
  ]
}

PUT my_index/_doc/2
{
  "my_nested_field": [
    {
      "my_field": "a"
    },
    {
      "my_field": "b"
    }
  ]
}

This is what that query would look like:

GET my_index/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "nested": {
            "path": "my_nested_field",
            "query": {
              "bool": {
                "must_not": [
                  {
                    "match": {
                      "my_nested_field.my_field": "a"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}
1 Like

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