4

I need to get distance from searched coordinates in elastic search using geo distance query. I tried this

curl -XGET 'http://127.0.0.1:9200/branch-master/master/_search?pretty=1'  -d '
{
   "script_fields" : {
      "distance" : {
         "params" : {
            "lat" : 18.00,
            "lon" : 72.00
         },
         "script" : "doc[\u0027location\u0027].distanceInKm(lat,lon)"
      }
   }
}
'

This is got from Return distance in elasticsearch results?

But this gives me error "unknown key for a start_object in [params]". I am not able understand what this is. Above solution seems to be for quite older version of ES. I am using ES 5.1. In the manual I couldn't find relavant solution for geo distance query. Could someone please help me?

Shades88
  • 7,934
  • 22
  • 88
  • 130

1 Answers1

6

The method distanceInKm was deprecated and is removed now (5.x). Use for example arcDistance instead. More information here: https://www.elastic.co/guide/en/elasticsearch/reference/current/breaking_50_scripting.html#_geopoint_scripts

The syntax is a little bit changed. This works for me in Elasticsearch 5.6.

{
    "script_fields": {
        "geo_distance": {
            "script": {
                "params": {
                    "lat": 18.00,
                    "lon": 72.00
                },
                "inline": "doc['location'].arcDistance(params.lat, params.lon)"
            }
        }
    }
}
schellingerht
  • 5,726
  • 2
  • 28
  • 56
  • 1
    Is this calculating distance from (lat, lon) in params from doc['location'] point? If I have two parameters with (lat, lon) pairs how would I calculate their distance? – haneulkim Jun 18 '20 at 01:19