0

I have some documents in OpenSearch with a field called location, which is a geo-point. I'm trying to write a sort script that takes into account the distance between the document's location, and some other arbitrary location. How do I calculate this distance inside the script? I found this answer from a few years ago, which uses the method distanceInKm. But when I tried it, it doesn't work. Here's my sort block:

  "sort": {
    "_script": {
      "type": "number",
      "order": "asc",
      "script": {
        "source": "return doc[\"location\"].distanceInKm(38.7819,-77.19);"
      }
    }
  }

(Yes, I realize that I don't need a script if I just want to sort by distance. This is a simplified example.)

From the response:

          "script_stack" : [
            "return doc[\"location\"].distanceInKm(38.7819,-77.19);",
            "                      ^---- HERE"
          ],
          "script" : "return doc[\"location\"].distanceInKm(38.7819,-77.19);",
          "lang" : "painless",
          "position" : {
            "offset" : 22,
            "start" : 0,
            "end" : 52
          },
          "caused_by" : {
            "type" : "illegal_argument_exception",
            "reason" : "dynamic method [org.opensearch.index.fielddata.ScriptDocValues.GeoPoints, distanceInKm/2] not found"
          }
Mike Baranczak
  • 8,291
  • 8
  • 47
  • 71

1 Answers1

2

It looks like distanceInKm and distanceInMiles were both replaced some time ago by arcDistance(double lat, double lon) and planeDistance(double lat, double lon) - and all distances are now returned in meters.

See here for an explanation of how these two are different.

Mike Baranczak
  • 8,291
  • 8
  • 47
  • 71