Shades88
Shades88

Reputation: 8360

Return distance in geo distance query in elastic search 5.x

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?

Upvotes: 4

Views: 2493

Answers (1)

schellingerht
schellingerht

Reputation: 5806

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

Upvotes: 6

Related Questions