We are working on updating this book for the latest version. Some content might be out of date.
The geo_distance
agg is useful
for searches such as
to "find all pizza restaurants within 1km of me." The search results
should, indeed, be limited to the 1km radius specified by the user, but we can
add “another result found within 2km”:
GET /attractions/restaurant/_search { "query": { "filtered": { "query": { "match": { "name": "pizza" } }, "filter": { "geo_bounding_box": { "location": { "top_left": { "lat": 40,8, "lon": -74.1 }, "bottom_right": { "lat": 40.4, "lon": -73.7 } } } } } }, "aggs": { "per_ring": { "geo_distance": { "field": "location", "unit": "km", "origin": { "lat": 40.712, "lon": -73.988 }, "ranges": [ { "from": 0, "to": 1 }, { "from": 1, "to": 2 } ] } } }, "post_filter": { "geo_distance": { "distance": "1km", "location": { "lat": 40.712, "lon": -73.988 } } } }
The main query looks for restaurants with | |
The bounding box filters these results down to just those in the greater New York area. | |
The | |
Finally, the |
The response from the preceding request is as follows:
"hits": { "total": 1, "max_score": 0.15342641, "hits": [ { "_index": "attractions", "_type": "restaurant", "_id": "3", "_score": 0.15342641, "_source": { "name": "Mini Munchies Pizza", "location": [ -73.983, 40.719 ] } } ] }, "aggregations": { "per_ring": { "buckets": [ { "key": "*-1.0", "from": 0, "to": 1, "doc_count": 1 }, { "key": "1.0-2.0", "from": 1, "to": 2, "doc_count": 1 } ] } }
The | |
The aggregation includes the search result plus the other pizza restaurant within 2km of the user. |
In this example, we have counted the number of restaurants that fall
into each concentric ring. Of course, we could nest subaggregations under
the per_rings
aggregation to calculate the average price per ring, the
maximium popularity, and more.