Geo Points in Elasticsearch
Introduction
Geo points in Elasticsearch are used to represent geographical locations with latitude and longitude coordinates. This is particularly useful for applications that need to store and query spatial data, such as mapping services, location-based searches, and geospatial analysis.
Creating an Index with Geo Points
To store geo points in Elasticsearch, you need to create an index with a mapping that includes a field of type geo_point
. Here is an example of how to create such an index:
PUT /locations { "mappings": { "properties": { "location": { "type": "geo_point" } } } }
This request creates an index named locations
with a location
field that can store geo points.
Indexing Documents with Geo Points
Once the index is created, you can index documents with geo point data. Here is an example:
POST /locations/_doc/1 { "location": { "lat": 40.7128, "lon": -74.0060 } }
This request indexes a document with a location
field representing the latitude and longitude of New York City.
Querying Geo Points
You can query documents based on their geo point data. For example, to find all documents within a certain distance from a specific location, you can use a geo_distance
query:
GET /locations/_search { "query": { "geo_distance": { "distance": "50km", "location": { "lat": 40.7128, "lon": -74.0060 } } } }
This query finds all documents within 50 kilometers of the specified latitude and longitude (New York City).
Sorting by Distance
You can also sort your search results by the distance from a specified geo point. Here is an example:
GET /locations/_search { "sort": [ { "_geo_distance": { "location": { "lat": 40.7128, "lon": -74.0060 }, "order": "asc", "unit": "km" } } ], "query": { "match_all": {} } }
This request sorts all documents by their distance from New York City, in ascending order.
Geo Bounding Box Query
A geo_bounding_box
query allows you to find documents that fall within a specified rectangular area. Here is an example:
GET /locations/_search { "query": { "geo_bounding_box": { "location": { "top_left": { "lat": 40.9176, "lon": -74.2591 }, "bottom_right": { "lat": 40.4774, "lon": -73.7004 } } } } }
This query finds all documents within the bounding box defined by the coordinates of the top-left and bottom-right corners.
Geo Polygon Query
A geo_polygon
query allows you to find documents that fall within a specified polygon. Here is an example:
GET /locations/_search { "query": { "geo_polygon": { "location": { "points": [ { "lat": 40.9176, "lon": -74.2591 }, { "lat": 40.4774, "lon": -74.2591 }, { "lat": 40.4774, "lon": -73.7004 }, { "lat": 40.9176, "lon": -73.7004 } ] } } } }
This query finds all documents within the polygon defined by the specified points.
Conclusion
Geo points in Elasticsearch provide powerful capabilities for storing and querying geographical data. By leveraging these features, you can build applications that require location-based functionality and geospatial analysis.