Distance calculation

Hi,

I am trying to calculate the distance

please find the below

PUT my_index
{
"mappings": {
"doc": {
"properties": {
"location": {
"type": "geo_point"
}
}
}
}

POST my_index/doc
{
"location": [
{
"lat": 33.235508,
"lon": -84.265779
},
{
"lat": 33.959574,
"lon": -84.531721
}
]

}

GET my_index/_search
{
"script_fields": {
"geo_distance": {
"script": {
"source":"doc['location'].planeDistance(33.818445,-84.555139)"
}
}
}
}

I am getting only one record calculated distance, instead of two records.

Could you please help on this

1 Like

I'm not a painless user but I guess you need to iterate over the location field as it's an array?

I have tried iterate location field, but getting an exception

"GET my_index/_search
{
"from": 0,
"size": 30,
"query": {
"match_all": {}
},
"script_fields":
{

"distance": {
  "script": {
    "inline":  "def l = new ArrayList(); def geopoint;for(int i=0; i < doc['location'].length;i++){ geopoint = doc['location'][i]; l.add(geopoint.planeDistance(33.818445,-84.555139))} return l;"
  }
}

}
}"

exception:-

"script": "def l = new ArrayList(); def geopoint;for(int i=0; i < doc['location'].length;i++){ geopoint = doc['location'][i]; l.add(geopoint.planeDistance(33.818445,-84.555139))} return l;",
"lang": "painless",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Unable to find dynamic method [planeDistance] with [2] arguments for class [org.elasticsearch.common.geo.GeoPoint]."

Hey David,

I have tried iterate location field, but getting an exception

exception:-

"script": "def l = new ArrayList(); def geopoint;for(int i=0; i < doc['location'].length;i++){ geopoint = doc['location'][i]; l.add(geopoint.planeDistance(33.818445,-84.555139))} return l;",
"lang": "painless",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Unable to find dynamic method [planeDistance] with [2] arguments for class [org.elasticsearch.common.geo.GeoPoint]."

Could you please help us

I wonder if you should call something like this instead?

GeoDistance.PLANE.calculate(geopoint.lat(), geopoint.lon(), 33.818445, -84.555139, DistanceUnit.METERS);

But again, i'm not expert on Painless.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.