Elasticsearch query null check for two fields with OR condition

126 views Asked by At

I want to alter the data in elastic search with a java 7 application running on jboss server. In elastic search index there are two fields called city_id and country_id. With new implementation I need to search for city_name is null or country_name null records and update them with relevant city_name and country_name.

POST index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "timestamp": {
              "gte": "2023-02-27 06:40:00"
            }
          }
        }
      ],
      "must_not": [
         {
          "exists": {
            "field": "city_name"
          }
        },
        {
          "exists": {
            "field": "country_name"
          }
        }
      ]
    }
  },
  "size": 3,
  "sort": [{
            "timestamp": {
                "order": "asc"
            }
        }
    ]
}

I'm using this search query. But with this its search for city_name and country_name both null records. I want to get OR (city_name OR country_name null) condition for this.

Can anyone please help me on this?

Thank you.

1

There are 1 answers

0
Seasers On

Since should is roughly equivalent to a boolean OR, according to this, you could try using a nested should -> bool -> must_not clause. Example:

{
    "query": {
        "bool": {
            "should": [{
                    "bool": {
                        "must_not": {
                            "exists": {
                                "field": "city_name"
                            }
                        }
                    }
                },
                {
                    "bool": {
                        "must_not": {
                            "exists": {
                                "field": "country_name"
                            }
                        }
                    }
                }
            ]
        }
    }
}