8

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

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

How can I execute the second 'must' criteria ONLY if the value ('a1' in this case) is not empty?

1
  • 6
    You better handle it at the time of query construction through the client. Commented Apr 25, 2015 at 16:28

2 Answers 2

11

You can achieve it using the following -

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "id": "1"
          }
        },
        {
          "bool": {
            "should": [
              {
                "missing": {
                  "field": "tags.name"
                }
              },
              {
                "match": {
                  "tags.name": "a1"
                }
              }
            ]
          }
        }
      ]
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I don't think "missing" can be used in the latest versions of elasticsearch. But one can use Conditional Clauses instead. https://www.elastic.co/guide/en/elasticsearch/reference/6.3/search-template.html#_conditional_clauses

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.