How to query for empty field or specific value

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.

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

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.

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