Geo Distance Queries in Elasticsearch
Introduction
Geo Distance Queries are a powerful feature in Elasticsearch that allow you to find documents within a certain distance from a specific point. They are particularly useful for applications that deal with location-based data, such as finding nearby restaurants, stores, or any other point of interest.
Prerequisites
To follow along with this tutorial, you will need:
- Basic understanding of Elasticsearch
- Elasticsearch installed and running
- Some data with geo-coordinates indexed in Elasticsearch
Setting Up Geo-Coordinates
Before you can perform geo distance queries, you need to index documents with geo-coordinates. Elasticsearch provides a special data type called geo_point
for this purpose.
Example mapping with a geo_point field:
{ "properties": { "location": { "type": "geo_point" } } }
Indexing Documents
Let's index some documents with geo-coordinates:
Example documents:
{ "name": "Central Park", "location": { "lat": 40.785091, "lon": -73.968285 } }
{ "name": "Times Square", "location": { "lat": 40.758896, "lon": -73.985130 } }
Performing a Geo Distance Query
To find documents within a certain distance from a specific point, you can use the geo_distance
query. Here's an example:
Find documents within 2km of Times Square:
{ "query": { "bool": { "filter": { "geo_distance": { "distance": "2km", "location": { "lat": 40.758896, "lon": -73.985130 } } } } } }
Expected output:
{ "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": null, "hits": [ { "_index": "my_index", "_id": "2", "_score": null, "_source": { "name": "Times Square", "location": { "lat": 40.758896, "lon": -73.985130 } } } ] } }
Advanced Geo Distance Queries
Elasticsearch also supports more advanced geo distance queries. For example, you can specify the distance in different units such as miles, meters, or even nautical miles:
Find documents within 1 mile of Times Square:
{ "query": { "bool": { "filter": { "geo_distance": { "distance": "1mi", "location": { "lat": 40.758896, "lon": -73.985130 } } } } } }
Conclusion
Geo Distance Queries in Elasticsearch are a powerful tool for working with location-based data. By using the geo_distance
query, you can easily find documents within a specified distance from a given point. This tutorial covered the basics of setting up geo-coordinates, indexing documents, and performing geo distance queries.