The Geo Distance Query in Elasticsearch allows you to find documents with geo-points within a specified distance from a central location. This query is particularly useful for location-based searches, such as finding nearby restaurants or services within a certain radius.
Syntax
The basic syntax for a Geo Distance Query is as follows:
{
"query": {
"geo_distance": {
"distance": "10km",
"location_field": {
"lat": 40.7128,
"lon": -74.0060
}
}
}
}
For more details, refer to the official Elasticsearch documentation on Geo Distance Query.
Example Query
Here's an example query to find restaurants within 5 kilometers of Central Park in New York City:
GET /restaurants/_search
{
"query": {
"geo_distance": {
"distance": "5km",
"location": {
"lat": 40.7829,
"lon": -73.9654
}
}
}
}
Common Issues
- Incorrect data type: Ensure that the field you're querying is mapped as a
geo_point
type. - Unit confusion: Be explicit with distance units (e.g., "km", "mi", "m").
- Performance issues with large datasets: Consider using geo-hashing or bounding box filters for initial filtering.
Best Practices
- Use the
_source
parameter to return only necessary fields. - Combine with other queries for more refined results.
- Consider using
sort
with_geo_distance
for distance-based sorting. - Use
validation_method: IGNORE_MALFORMED
to handle invalid coordinates gracefully.
Frequently Asked Questions
Q: How can I sort results by distance in a Geo Distance Query?
A: You can add a sort clause to your query using _geo_distance
. For example:
"sort": [
{
"_geo_distance": {
"location": {
"lat": 40.7128,
"lon": -74.0060
},
"order": "asc",
"unit": "km"
}
}
]
Q: Can I use addresses instead of coordinates in a Geo Distance Query?
A: Elasticsearch doesn't directly support address-based queries. You need to geocode addresses to coordinates before querying. Consider using a geocoding service or storing both address and coordinates in your index.
Q: How does the Geo Distance Query handle the curvature of the Earth?
A: By default, Elasticsearch uses the arc distance calculation, which accounts for the Earth's curvature. For very small distances, you can use the plane
distance type for faster but less accurate results.
Q: Is there a maximum distance limit for Geo Distance Queries?
A: There's no hard limit, but extremely large distances (e.g., half the Earth's circumference) may lead to unexpected results. It's best to use reasonable distances based on your use case.
Q: How can I improve the performance of Geo Distance Queries on large datasets?
A: For large datasets, consider using geo-hashing or a bounding box filter as a pre-filter, then apply the Geo Distance Query on the reduced set. Also, ensure your geo_point fields are properly indexed.