ElasticSearch 2.x exists filter for nested field d

2019-07-31 19:17发布

问题:

I have the following mapping

{
  "properties": {
    "restaurant_name": {"type": "string"},
    "menu": {
      "type": "nested",
      "properties": {
        "name": {"type": "string"}
      }
    }
  }
}

I am trying to filter all those documents which have optional "menu" field exists

GET /restaurnats/_search
{
  "filter": {
    "query": {
      "bool": {
        "must": [
          {"exists" : { "field" : "menu" }}
        ]
      }
    }
  }
}

But, when I try the same query to filter those documents which have "restaurant_name", then it works fine. So why nested field check doesn't work? How to get it work?

回答1:

You need to use a nested query instead:

{
  "filter": {
    "query": {
      "nested": {
        "path": "menu",
        "query": {
          "bool": {
            "must": [
              {
                "exists": {
                  "field": "menu"
                }
              }
            ]
          }
        }
      }
    }
  }
}