Search code examples
elasticsearchelasticsearch-2.0elasticsearch-dsl

ElasticSearch 2.x exists filter for nested field doesn't work


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?


Solution

  • You need to use a nested query instead:

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