Search code examples
sortingelasticsearchgeosymfony3ongr

Sorting results by distance in ONGR ElasticsearchDSL


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?!


Solution

  • 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);