Search code examples
elasticsearchelasticsearch-dslelasticsearch-railselasticsearch-rubyelasticsearch-nested

ElasticSearch Nested Query - exclude parent document


Trying to exclude top-level documents where one of the child documents doesn't match the query.

For the example below, I'm trying to exclude all documents where one of its nested jobs has current: true, and matches with the company name: Elastic. But since one of the nested job documents matches with current: false and company name: Elastic, this document is returned. I am using a nested query with a must match on company name and a filter where current: false. How can I make it so that the below document is not returned?

 "name": "john doe",
      "jobs": [
        {
          "title": "Vice President",
          "current": true,
          "company": {
            "name": "Elastic"
          }
        },
        {
          "title": "CEO",
          "current": false,
           "company": {
             "name": "Elastic"
          }
     ...

Solution

  • How about this one? Note that I assumed you have a .keyword sub0field that is basically matching exactly on the upper case letter. If you have it differently, change the field name accordingly:

    {
      "query": {
        "bool": {
          "must_not": [
            {
              "nested": {
                "path": "jobs",
                "query": {
                  "bool": {
                    "must": [
                      {
                        "term": {
                          "jobs.current": {
                            "value": "true"
                          }
                        }
                      },
                      {
                        "term": {
                          "jobs.company.name.keyword": {
                            "value": "Elastic"
                          }
                        }
                      }
                    ]
                  }
                }
              }
            }
          ]
        }
      }
    }