ElasticSearch Nested Query - exclude parent docume

2019-08-06 05:08发布

问题:

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"
          }
     ...

回答1:

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"
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}