Elastic Search / Elasica php - OR query on field containing NULL not working

169 Views Asked by At

How can I query only documents where location_id is null or locations.country_id is in a set of given ids? This is the current query but it doesn't return me anything at all... If I remove the location_id from the query it works and returns me at least documents that match the country ids.

{
   "bool":{
      "must":[
         {
            "bool":{
               "must_not":[
                  {
                     "exists":{
                        "field":"location_id"
                     }
                  }
               ],
               "must":[
                  {
                     "terms":{
                        "locations.country_id":[
                           18
                        ]
                     }
                  }
               ]
            }
         }
      ]
   }
}
1

There are 1 best solutions below

6
jaspreet chahal On BEST ANSWER

In elasticsearch Must is AND and Should behaves like OR Your query translates to locationId is null AND locations.country_id In [set of ids]. Must needs to be replaced with should.

Query:

{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "location_id"
                }
              }
            ]
          }
        },
        {
          "terms": {
            "locations.country_id": [
              18
            ]
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}