How to write query for a property which exists but can also not exist?

I have the next weird case: I have the fruitBox. This fruit box can have apples, pears, bananas. But it also can be empty, in this case it doesn't have any property for box.
Now lets say that i want to get from the Elasticsearch all the boxes with apples, pears and the ones that are empty.
For the boxes with fruits in it i have :
</>

{
      "bool": {
       "should": [
         {"match_phrase": {"fruit": "apple"}},
         {"match_phrase": {"fruit": "pear"}},
          ]
      }
    },

</>
Which works fine!
But if i add the condition to get also the empty boxes:
</>

    "bool": {
      "must_not": {
        "exists": {
          "field": "fruit"
        }
      }
}

</>
I get 0 hits.
Thank you!

Are you using KQL for this, or the ES query DSL directly? I believe the KQL way to do this is NOT fruitBox: * OR fruitBox: apple OR fruitBox: pear. With the query DSL you can add an inner bool to your should clause, so you can do something resembling should > bool > must_not > exists

1 Like

I was using DSL.
Thanks a lot!

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