Sharath
Sharath

Reputation: 2428

Get the distance from each coordinates from the results in Elastic Search

I need to filter the records closest to the given coordinates. From the below query removing script_fields will work (gives the results).

Need to get the distance for each matched results.

GET story/_search
{
  "_source": [
    "title.english", "location"
  ],
  "query": {
    "bool": {
      "filter": [
        {
          "geo_distance": {
            "distance": "1000km",
            "location": {
              "lat": 57.3079700,
              "lon": 123.4977090
            }
          }
        }
      ]
    }
  },
  "script_fields": {
    "distance": {
      "script": "doc['location'].distanceInKm(57.3079700, 123.4977090)"
    }
  }
}

Below is the error

"failures" : [
      {
        "shard" : 1,
        "index" : "story",
        "node" : "asdf-asdf",
        "reason" : {
          "type" : "script_exception",
          "reason" : "runtime error",
          "script_stack" : [
            "doc['location'].distanceInKm(57.3079700, 123.4977090)",
            "               ^---- HERE"
          ],
          "script" : "doc['location'].distanceInKm(57.3079700, 123.4977090)",
          "lang" : "painless",
          "caused_by" : {
            "type" : "illegal_argument_exception",
            "reason" : "dynamic method [org.elasticsearch.index.fielddata.ScriptDocValues.GeoPoints, distanceInKm/2] not found"
          }
        }
      }
    ]
  },

Upvotes: 1

Views: 572

Answers (1)

Joe - Check out my books
Joe - Check out my books

Reputation: 16925

As @Sharath pointed out, distanceInKm is deprecated. These days you can use arcDistance and convert the value to km through dividing by 1000.

GET my-index-000001/_search
{
  ...
  "script_fields": {
    "distance": {
      "script": "doc['location'].arcDistance(57.3079700, 123.4977090) / 1000"
    }
  }
}

Here's the list of currently supported geo methods and here's the arcDistance source.

Upvotes: 2

Related Questions