How to query for empty field or specific value


(André Herculano) #1

I'm trying to write a query to achieve the following result:

field1: value1 AND 
field2: value2 OR "" (empty)

I've tried the following but it always returns me empty results:

{
  "_source": ["field1", "field2"], 
  "query": {
    "bool": {
      "must": [
        {"match": { "field1": "value1" }},
        {
          "bool": {
            "should": [
              { 
                "match": {
                  "field2": "value2"
                }
              }
            ],
            "must_not": [
              {
                "exists": { "field": "field2" }
              }
            ]
          }
        }
      ]
    }
  }
}

I believe I'm making a query that contradicts itself.


(David Pilato) #2

I think you need to put the exists query inside the should clause as a new bool query with a must_not clause.


(André Herculano) #3

Hey @dadoonet thank you for your tip. That's what I ended up with.

{
  "query": {
    "bool": {
      "must": [
        {"match": { "field1": "value1" }},
        {
          "bool": {
            "should": [
              { "match": { "field2": "value2" }},
              {
                "bool": {
                  "must_not": [
                    { "exists": { "field": "field2" }}
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Your guess was correct.


(system) #4

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.