Sorting results by distance in ONGR ElasticsearchDSL

659 Views Asked by At

I'm using ONGR ElasticsearchDSL Bundle together with Symfony 3 to search through a list of citys by lat/lon coordinates, like so:

$repository = $this->elasticsearchManager->getRepository(CityDocument::class);
$search = $repository->createSearch();

$boolQuery = new BoolQuery();
$boolQuery->add(new MatchAllQuery());
$geoQuery = new GeoDistanceQuery('geo', '50km', $theSearch['location']);
$boolQuery->add($geoQuery, BoolQuery::FILTER);
$search->addQuery($boolQuery);
$documents = $repository->findDocuments($search);

While this gives me a good result with matching cities, I am unclear on how to sort those by distance from my source point (found in $theSearch['location']), so that I get them ordererd from closest to farthest?!

1

There are 1 best solutions below

3
On BEST ANSWER

This is the correct way to use ElasticsearchDSL including sort you need.

$repository = $this->elasticsearchManager->getRepository(CityDocument::class);
$search = $repository->createSearch();

$geoQuery = new GeoDistanceQuery('geo', '50km', $theSearch['location']);
$search->addQuery($geoQuery, BoolQuery::FILTER);

$sort = new FieldSort('_geo_distance', null, [
    'geo' => $geoLocation,
    'order' => 'asc',
    'unit' => 'km',
    'mode' => 'min',
    'distance_type' => 'arc'
]);
$search->addSort($sort);

$documents = $repository->findDocuments($search);