Search code examples
pythonelasticsearchelasticsearch-dsl

elasticsearch_dsl search by geo location distance and get results and distance


I have an index the holds location data for stores.

When using python's elasticsearch_dsl I'd like to find the nearest stores for a given location, sorted by distance. Since ES already calculates the distance, is it possible to get it as a part of the search result?

Can it be achieved using elasticsearch_dsl in a single query? Or do I have to do post processing on the location lat,lon and calculate the distances manually?

Thanks.


Solution

  • You can sort by distance and you'd get the computed distance in the resulting hits.

    For instance:

    s = Search().sort(
        {
            "_geo_distance" : {
                "location" : {"lat": 40, "lon": -70},
                "order" : "asc",
                "unit" : "km",
                "distance_type" : "arc"
            }
        }
    )