🏡 Home 📖 Chapter Home 👈 Prev 👉 Next

⚡  ElasticsearchBook is crafted by Jozef Sorocin (🟢 Book a consulting hour) and powered by:

Geo Recap

As we've established in From the Viewport to the Query, any rectangle or bounding box can be targeted using the geo_bounding_box query.

Similarly, any polygon (incl. polygon circles) can be targeted through the geo_polygon query.

But what if we want all points that lie within a certain distance from an origin point? Think the nearest restaurants, the closest Uber driver, etc. That's what the geo_distance query is for.

Use Case: Restaurants Within 0.5 Miles

I want to retrieve restaurants that serve pizza and lie within 0.5 miles of an origin geo point. I also want to give precedence to those that are closer to the origin:

Imaginary Restaurants in Midtown Manhattan. Map courtesy of http://geojson.io/

Imaginary Restaurants in Midtown Manhattan. Map courtesy of http://geojson.io/

Approach

Let's envelop them all in a must query:

POST restaurants/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "menu": "pizza"
          }
        },
        {
          "geo_distance": {
            "distance": "0.5mi",
            "location": [-73.9982, 40.7388]
          }
        },
        {
          "function_score": {
            "functions": [
              {
                "exp": {
                  "location": {
                    "origin": [-73.9982, 40.7388],
                    "scale": "0.5mi"
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}