1

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

1 Answer 1

2

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"
              }
            }
          }
        }
      ]
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked thank you. Only needed to nest the outer bool under constant_score > filter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.