Elasticsearch 使用地理位置搜索需要用到地理位置数据类型(Geo-point Data Type)和地理位置搜索功能(Geo-Location Search),具体实现步骤如下:
在 Elasticsearch 的 mapping 中,需要为地理位置字段定义地理位置数据类型。地理位置数据类型可以在属性字段上指定,例如:
PUT my_index
{
"mappings": {
"properties": {
"location": {
"type": "geo_point"
}
}
}
}
上述命令在名为 "my_index" 的索引中定义了一个名为 "location" 的地理位置字段,其数据类型为 "geo_point"。
在索引文档时,需要为地理位置字段插入地理位置数据。地理位置数据需要包含经度和纬度,可以使用以下格式:
PUT my_index/_doc/1
{
"location": {
"lat": 40.714,
"lon": -74.006
}
}
上述命令在 "my_index" 索引中插入了一份文档,其中 "location" 字段的经度为 40.714,纬度为 -74.006。
在执行搜索时,可以使用以下参数指定地理位置搜索:
geo_distance
:指定搜索的距离范围。distance_type
:指定距离计算的方式。sort
:按距离排序搜索结果。例如,以下命令将搜索名为 "my_index" 的索引中离经度为 40.715、纬度为 -74.011 的地点 5 公里范围内的文档,并按距离排序:
GET my_index/_search
{
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"geo_distance": {
"distance": "5km",
"location": {
"lat": 40.715,
"lon": -74.011
}
}
}
}
},
"sort": [
{
"_geo_distance": {
"location": {
"lat": 40.715,
"lon": -74.011
},
"order": "asc",
"unit": "km",
"distance_type": "plane"
}
}
]
}
上述命令将返回名为 "my_index" 的索引中距离经度为 40.715、纬度为 -74.011 的地点 5 公里范围内的文档,并按距离从近到远排序。
需要注意的是,地理位置搜索需要在查询时指定过滤器,因为地理位置搜索不会影响文档的相关性得分,只会影响文档的排序结果。