答案 0 :(得分:42)
是的,您可以使用script field。
例如,假设您的文档有一个名为location
的地理点字段,您可以使用以下内容:
(请注意,\u0027
只是一个转义单引号,所以\u0027location\u0027
确实是'location'
)
curl -XGET 'http://127.0.0.1:9200/geonames/_search?pretty=1' -d '
{
"script_fields" : {
"distance" : {
"params" : {
"lat" : 2.27,
"lon" : 50.3
},
"script" : "doc[\u0027location\u0027].distanceInKm(lat,lon)"
}
}
}
'
# [Thu Feb 16 11:20:29 2012] Response:
# {
# "hits" : {
# "hits" : [
# {
# "_score" : 1,
# "fields" : {
# "distance" : 466.844095463887
# },
# "_index" : "geonames_1318324623",
# "_id" : "6436641_en",
# "_type" : "place"
# },
... etc
如果您还希望返回_source
字段,则可以按如下方式指定:
curl -XGET 'http://127.0.0.1:9200/geonames/_search?pretty=1' -d '
{
"fields" : [ "_source" ],
"script_fields" : {
"distance" : {
"params" : {
"lat" : 2.27,
"lon" : 50.3
},
"script" : "doc[\u0027location\u0027].distanceInKm(lat,lon)"
}
}
}
'
答案 1 :(得分:9)
DrTech给出了很好的答案......这里是Elasticsearch 5.x的更新版本,脚本语言是无痛的。我还添加了" store_fields"在结果中包含_source
:
curl -XGET 'http://127.0.0.1:9200/geonames/_search?pretty=1' -d '
{
"stored_fields" : [ "_source" ],
"script_fields" : {
"distance" : {
"script" : {
"inline": "doc['location'].arcDistance(params.lat,params.lon) * 0.001",
"lang": "painless",
"params": {
"lat": 2.27,
"lon": 50.3
}
}
}
}
}'
答案 2 :(得分:7)
要返回与所有默认字段/来源一样的距离,您也可以这样做:
为了避免按距离排序(主要是),您只需按_score(或任何您想要的结果排序)排序。
{
"sort": [
"_score",
{
"_geo_distance": {
"location": {
"lat": 40.715,
"lon": -73.998
},
"order": "asc",
"unit": "km",
"distance_type": "plane"
}
}
]
}
答案 3 :(得分:3)
由于 ES 1.3 默认情况下禁用MVEL,因此请使用如下查询:
GET some-index/_search
{
"sort": [
{
"_geo_distance": {
"geo_location": "47.1, 8.1",
"order": "asc",
"unit": "m"
}
}
],
"query": {
"match_all": {}
},
"script_fields" : {
"distance" : {
"lang": "groovy",
"params" : {
"lat" : 47.1,
"lon" : 8.1
},
"script" : "doc[\u0027geo_location\u0027].distanceInKm(lat,lon)"
}
}
}
请参阅:"lang": "groovy",
部分