在Elasticsearch.js。
elsaticsearch版本为2.3.4
使用这样的代码
body: {
from: data['offset'] || 0
, size: data['limit'] || 20
, query: {
bool: {
must: {
range: {
state: {
gte: 0
}
}
}
, filter: {
geo_distance_range: {
from: data['from'] || '0km'
, to: data['to'] || '5km'
, location: {
lat: data['lat']
, lon: data['lon']
}
}
}
}
}
, sort: [{
_geo_distance: {
location: {
lat: data['lat']
, lon: data['lon']
}, order: 'asc'
, unit: 'm'
}
}]
, script_fields: {
distance: {
lang: "groovy",
script: "doc['location'].distanceInKm(" + data['lat'] + "," + data['lon'] + ")*1000"
}
}
}
运行它,只需获取
[
{
"_index": "stores_location_v1",
"_type": "location_info",
"_id": "65",
"_score": null,
"fields": {
"distance": [
632.513773747282
]
},
"sort": [
631.9282534390322
]
},
{
"_index": "stores_location_v1",
"_type": "location_info",
"_id": "100976",
"_score": null,
"fields": {
"distance": [
772.123560941117
]
},
"sort": [
656.1648199724189
]
},
{
"_index": "stores_location_v1",
"_type": "location_info",
"_id": "64",
"_score": null,
"fields": {
"distance": [
663.1312353690903
]
},
"sort": [
662.5164209175506
]
},
{
"_index": "stores_location_v1",
"_type": "location_info",
"_id": "100542",
"_score": null,
"fields": {
"distance": [
695.1804755172814
]
},
"sort": [
669.5809632061855
]
}
]
sort中_geo_distance计算的结果不等于使用script_fields中的distanceInKm方法计算的结果。
我想知道为什么会这样?那该怎么办?
有没有办法替换distanceInKm
基于m
的计算而不是km
然后* 1000。
这是失去准确性的部分原因吗?
而且,我只想计算一个点和另一个点之间的距离,应该如何计算?直接使用script_fields`` distanceInKm
方法?
答案 0 :(得分:0)
search-request-sort.html#geo-sorting
modules-scripting.html#_document_fields
只需使用distance_type
和arcDistance
同样适用于
sort: [{
_geo_distance: {
location: {
lat: data['lat']
, lon: data['lon']
}, order: 'asc'
, unit: 'm'
, "distance_type": "arc"
}
}]
, script_fields: {
distance: {
lang: "groovy",
script: "doc['location'].arcDistance(" + data['lat'] + "," + data['lon'] + ")"
}
}