Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

geolocation - Return distance in elasticsearch results?

My question is similar to this one.

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.

question from:https://stackoverflow.com/questions/9295118/return-distance-in-elasticsearch-results

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes you can, by using a script field.

For instance, assuming your doc have a geo-point field called location, you could use the following:

(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

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)"
      }
   }
}
'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...