Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check multiple fields exists

The Elasticsearch Query DSL allows me to find documents that has certain field exists:

GET /_search
{
    "query": {
        "exists" : { "field" : "firstname" }
    }
}

But it seems only work for one field exists, how to check 2 fields exist? For example, I'd like to find users that has both firstname and lastname fields exist.

like image 547
Leo Zhang Avatar asked Jan 27 '23 12:01

Leo Zhang


1 Answers

You can do that by wrapping the two exists in filter clause or must clause as below:

{
  "query": {
    "bool": {
      "filter": [
        {
          "exists": {
            "field": "firstname"
          }
        },
        {
          "exists": {
            "field": "lastname"
          }
        }
      ]
    }
  }
}

Using in filter clause will give the same output as by must clause. The only difference will be the one with filter will not calculate score while the one with must will calculate score. Use as per your needs. For more on this read this.

Using must:

{
  "query": {
    "bool": {
      "must": [
        {
          "exists": {
            "field": "firstname"
          }
        },
        {
          "exists": {
            "field": "lastname"
          }
        }
      ]
    }
  }
}
like image 193
Nishant Avatar answered Feb 01 '23 11:02

Nishant