Home > Back-end >  Elasticsearch filter increases results instead of reducing them
Elasticsearch filter increases results instead of reducing them

Time:08-02

I am trying to build the following filter logic:

at least one geolocation must be truthy
AND
The status must be equal to 1.

Right now when I add the term query for status the number of results increases, where as it is expected for it to be the same. All records in the sample index I am using have status equal to 1.

GET /my-index/_search
{
   "query":{
      "bool":{
         "filter":{
            "bool":{
               "must":[
                  {
                     "term":{
                        "status": "1"
                     }
                  }
               ],
               "should":[
                  {
                     "geo_distance":{
                        "distance":"24km",
                        "locations":{
                           "lat":11.11,
                           "lon":13.52
                        }
                     }
                  },
                  {
                     "geo_distance":{
                        "distance":"24km",
                        "locations":{
                           "lat":81.11,
                           "lon":43.52
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}

CodePudding user response:

U can do two things.

Filter Should (I would choose)

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "status": "1"
          }
        }
      ],
      "should": [
        {
          "geo_distance": {
            "distance": "24km",
            "locations": {
              "lat": 11.11,
              "lon": 13.52
            }
          }
        },
        {
          "geo_distance": {
            "distance": "24km",
            "locations": {
              "lat": 81.11,
              "lon": 43.52
            }
          }
        }
      ]
    }
  }
}

Use minimum_should_match

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "status": "1"
          }
        }
      ],
      "minimum_should_match": 1,
      "should": [
        {
          "geo_distance": {
            "distance": "24km",
            "locations": {
              "lat": 11.11,
              "lon": 13.52
            }
          }
        },
        {
          "geo_distance": {
            "distance": "24km",
            "locations": {
              "lat": 81.11,
              "lon": 43.52
            }
          }
        }
      ]
    }
  }
}
  • Related