在 Elasticsearch 5.x 中,您可以使用 "function_score" 查询结合 "distance" 函数来执行地理距离查询并返回距离信息
{
"query": {
"function_score": {
"query": {
"match_all": {}
},
"functions": [
{
"filter": {
"geo_distance": {
"distance": "10km",
"location": {
"lat": 40.7128,
"lon": -74.0060
}
}
},
"weight": 1
}
],
"score_mode": "sum",
"boost_mode": "replace"
}
},
"script_fields": {
"distance": {
"script": {
"lang": "painless",
"source": "doc['location'].distanceInKm(40.7128, -74.0060)"
}
}
},
"_source": ["_id", "name", "location"]
}
在这个查询中,我们首先使用 "function_score" 查询来过滤出距离给定坐标(纬度 40.7128,经度 -74.0060)10公里以内的文档。然后,我们使用 "script_fields" 参数来计算并返回每个文档与给定坐标之间的距离(以千米为单位)。
请注意,您需要将 "location" 字段映射为 "geo_point" 类型,以便在执行地理距离查询时正确处理它。在创建索引时,您可以使用以下映射:
{
"mappings": {
"properties": {
"location": {
"type": "geo_point"
}
}
}
}
这将确保 "location" 字段可以用于地理距离查询和脚本计算。
领取专属 10元无门槛券
手把手带您无忧上云