How to write a conditional query using Elasticsearch?

I have a simple JSON request for Elasticsearch that looks like this:

"query": {
  "bool": {
    "must": { "match": { "id": "1" }} ,
    "must": { "match": { "tags.name": "a1"}}
   }
}

How can I fulfill the second criterion of "must" ONLY if the value ("a1" in this case) is not empty?

+4
source share
1 answer

You can achieve this using the following:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "id": "1"
          }
        },
        {
          "bool": {
            "should": [
              {
                "missing": {
                  "field": "tags.name"
                }
              },
              {
                "match": {
                  "tags.name": "a1"
                }
              }
            ]
          }
        }
      ]
    }
  }
}
+5
source

Source: https://habr.com/ru/post/1584644/


All Articles