Conditional filtering in Elasticsearch

Abd00s

I have an index with three fields type which is an integer, coordinates which is a geopoint and title which is a string. I want to query for matches on title. Then I want to filter my results conditionally. Records that are of type 2 should be included if they fall within a 15 km radius. Those that are not of type 2 should only be included if they fall within a 7.5 km radius. The query below does not achieve this; I rather included it to give some idea of the structure of my index. This query returns matching records that are of type 2 and fall within 15 km. I'd want this query to be expanded to also include matching records that aren't of type 2 (namely, 1), but only if they fall within 7.5 km. Is this achievable in a single ES query?

Pseudocode of my filtering conditions logic:

if type == 2
    filter
        distance: 15 km
else
    filter
        distance 7.5 km

Query:

{
  "query": {
    "filtered": {
      "query": {
        "match": {
          "title": "my search terms"
        }
      }, 
      "filter": {
        "and": [
          {
            "geo_distance": {
              "distance": "15km", 
              "coordinates": [
                -79.3931, 
                43.6709
              ]
            }
          }, 
          {
            "term": {
              "type": "2"
            }
          }
        ]
      }
    }
  }
}

ES 2.3

Val

You can achieve what you want like this:

{
  "query": {
    "bool": {
      "must": {
        "match": {
          "title": "my search terms"
        }
      },
      "should": [
        {
          "bool": {
            "must": [
              {
                "geo_distance": {
                  "distance": "15km",
                  "coordinates": [
                    -79.3931,
                    43.6709
                  ]
                }
              },
              {
                "term": {
                  "type": "2"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "geo_distance": {
                  "distance": "7.5km",
                  "coordinates": [
                    -79.3931,
                    43.6709
                  ]
                }
              }
            ],
            "must_not": {
              "term": {
                "type": "2"
              }
            }
          }
        }
      ]
    }
  }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related