在弹性搜索结果中返回距离? [英] Return distance in elasticsearch results?
问题描述
我的问题类似于这个一个.
简单地说,有没有办法在不使用 _geo_distance 排序时返回地理距离?
Simply, is there a way to return the geo distance when NOT sorting with _geo_distance?
更新:澄清一下,我想要随机顺序的结果并包括距离.
Update: To clarify, I want the results in random order AND include distance.
推荐答案
是的,你可以,通过使用 脚本字段.
Yes you can, by using a script field.
例如,假设您的文档有一个名为 location
的地理点字段,您可以使用以下内容:
For instance, assuming your doc have a geo-point field called location
, you could use the following:
(注意 u0027
只是一个转义的单引号,所以 u0027locationu0027
实际上是 'location'
)
(note the u0027
is just an escaped single quote, so u0027locationu0027
is really '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[u0027locationu0027].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
字段,那么您可以指定如下:
If you want the _source
field to be returned as well, then you can specify that as follows:
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[u0027locationu0027].distanceInKm(lat,lon)"
}
}
}
'
这篇关于在弹性搜索结果中返回距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!