Elasticsearch实现距离计算需要使用Geo Distance Query和Geo Distance Aggregation两个功能。这两个功能都基于地理位置信息(经纬度)进行计算。
{
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"geo_distance": {
"distance": "10km",
"pin.location": {
"lat": 40,
"lon": -70
}
}
}
}
}
}
其中,geo_distance
表示距离查询,pin.location
是文档中保存地理位置信息的字段名,lat
和lon
分别表示纬度和经度,distance
表示距离范围。
{
"aggs": {
"location_stats": {
"geo_distance": {
"field": "pin.location",
"origin": {
"lat": 40,
"lon": -70
},
"ranges": [
{
"to": 5000
},
{
"from": 5000,
"to": 10000
},
{
"from": 10000
}
]
}
}
}
}
其中,geo_distance
表示距离聚合,field
是文档中保存地理位置信息的字段名,origin
表示查询的中心点,ranges
表示距离范围。
需要注意的是,Elasticsearch使用的是Haversine公式来计算距离,该公式基于球面距离。同时,使用Geo Distance Query和Geo Distance Aggregation需要在索引映射中将地理位置信息定义为geo_point
类型。
推荐学习材料:官方文档。