在 ONGR ElasticsearchDSL 中按距离对结果进行排序

Sorting results by distance in ONGR ElasticsearchDSL

我将 ONGR ElasticsearchDSL Bundle 与 Symfony 3 一起使用,通过 lat/lon 坐标搜索城市列表,如下所示:

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

虽然这为我提供了匹配城市的良好结果,但我不清楚如何根据与源点(在 $theSearch['location'] 中找到)的距离对这些城市进行排序,以便我得到它们 ordererd从最近到最远?!

这是使用 ElasticsearchDSL 的正确方法,包括您需要的排序。

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