I would like to sort results based on the minimum distance found from a few different geo_point
fields.
Here is a basic example:
Mapping:
{
"companies" : {
"mappings" : {
"_doc" : {
"properties" : {
"location" : {
"properties" : {
"lat" : {
"type" : "float"
},
"lon" : {
"type" : "float"
}
}
},
"service_cities" : {
"properties" : {
"location" : {
"properties" : {
"lat" : {
"type" : "float"
},
"lon" : {
"type" : "float"
}
}
}
}
}
}
}
}
}
}
What I would like to do is query the index with a lat, lon pair and get results sorted based on minimum geo_distance
from location
or any of the service_cities.location
s.
For example, if my index looked something like this:
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 2,
"max_score" : 1.0,
"hits" : [
{
"_index" : "companies",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
// New York City, NY
"location" : {
"lat" : 40.73061,
"lon" : -73.935242
},
"service_cities" : [
{
// Denver, CO
"location" : {
"lat" : 39.742043,
"lon" : -104.991531
}
}
]
}
},
{
"_index" : "companies",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
// Phoenix, AZ
"location" : {
"lat" : 33.448376,
"lon" : -112.074036
},
"service_cities" : [
{
// San Francisco, CA
"location" : {
"lat" : 37.773972,
"lon" : -122.431297
}
},
{
// Las Vegas, NV
"location" : {
"lat" : 36.114647,
"lon" : -115.172813
}
}
]
}
}
]
}
}
And I searched for the companies matching the coordinates of Denver, CO. I would expect the results to be doc2, doc1
since document 2 has a service city nearest to Denver.
However, if document 2 did not have that service city, I would expect the order to be doc1, doc2
since document 1 has a location or a service city closest to Denver.
From what I have read and played with, it seems like the best way to do this would be with using a script
in sort, as using multiple _geo_distance
entries in sort clearly does not work.
Any advice would be appreciated!