Json Array of geo locations, get distance of all the location in json array of a Document


(Saikrishna Rangineni) #1

i have and document which contains array of locations with address and lat / long( geo_point).

{
"practiceLocations":[
{
"city":"ELKO",
"state":"NV",
"zipCode":"89801",
"locationCode":"8331",
"location":{
"lat":40.832383,
"lon":-115.734026
}
},
{
"city":"FAIRFIELD",
"state":"CA",
"zipCode":"94534",
"locationCode":"9715",
"location":{
"lat":38.2368397,
"lon":-122.0853558
}
},
{
"city":"SACRAMENTO",
"state":"CA",
"zipCode":"95816",
"country":"US",
"phoneNo":"8775150053",
"faxNo":"9164546926",
"locationCode":"5120",
"location":{
"lat":38.5729335,
"lon":-121.4690193
}
}
]
}

i want to get the location of all the locations in the practiceLocations array.

So i tries script_fields to calculate the distance from any lat/ long.

{
"fields": [
"_source"
],
"query" : { "match_all": {} },
"script_fields" : {
"distance" : {
"script" : "doc['practiceLocationAddress.location'].distanceInMiles(38,-118)"
}}

i'm able to get the first element distance in array from the mentioned lat long.

we have doc['field_name'].lats, doc['field_name'].lons to get the all the latitude and longitude in the array but i dint see and function which gives all the distances in array.


(Luis Rosales) #2

Same issue here! Can anyone help?


(Saikrishna Rangineni) #3

HI Luis,

I dint find any solution so i changed the document structure such that each document will have only lat, long instead of array .


#4

Change you mapping to nested type. Then use inner_hits:
{
"size": 10,
"_source": {
"include": "location"
},
"query": {
"bool": {
"filter": {
"nested": {
"path": "practiceLocations",
"query": {
"match_all": {}
},
"inner_hits": {
"size": 100,
"script_fields": {
"distance": {
"script": {
"inline": "if (!doc['practiceLocations.location'].empty) {doc['practiceLocations.location'].arcDistance(params.lat,params.lon) }",
"lang": "painless",
"params": {
"lat": 38.2368397,
"lon": -122.0853558
}
}
}
}
}
}
}
}
}
}


(system) #5