1. 背景介绍
有一些餐馆或酒店散步在你的周围,你想查询你附近的酒店。
2. ES model
{
"shop" : {
"mappings" : {
"properties" : {
"category_id" : {
"type" : "integer"
},
"category_name" : {
"type" : "keyword"
},
"id" : {
"type" : "integer"
},
"location" : {
"type" : "geo_point"
},
"name" : {
"type" : "text",
"analyzer" : "ik_max_word",
"search_analyzer" : "ik_smart"
}
}
}
}
}
重点在于 shop model mapping 中有一列是:location。
数据格式:
3. 距离计算
POST /shop/_search
{
"query": {
"match": {
"name": "和府"
}
},
"_source": "*",
"script_fields": {
"distance": {
"script": {
"source": "haversin(lat, lon, doc['location'].lat, doc['location'].lon)",
"lang": "expression",
"params": {"lat": 42.17, "lon": 117.12}
}
}
}
}
4. 根据距离升序排序
POST /shop/_search
{
"query": {
"match": {
"name": "和府"
}
},
"_source": "*",
"script_fields": {
"distance": {
"script": {
"source": "haversin(lat, lon, doc['location'].lat, doc['location'].lon)",
"lang": "expression",
"params": {"lat": 42.17, "lon": 117.12}
}
}
},
"sort": [
{
"_geo_distance": {
"location": {
"lat": 42.17,
"lon": 117.12
},
"order": "asc",
"unit": "km",
"distance_type": "arc"
}
}
]
}
|