Elastica

A PHP client for elasticsearch.

Fork me on GitHub

Sorting Hits

Sort By Distance

Assuming your indexed data includes a geo-point named pin.location you can implement a sort by distance using the following

Direct JSON request to elastic search

1
2
3
4
5
6
7
8
9
10
11
{
    "sort" : [
        {
            "_geo_distance" : {
                "pin.location" : [-70, 40],
                "order" : "asc",
                "unit" : "km"
            }
        }
    ]
}

Equivalent implementation in Elastica

1
2
3
4
5
6
7
8
9
10
11
12
13
$index = $elasticaClient->getIndex('someindex');
$elasticaQuery = new \Elastica\Query();

$elasticaQuery->addSort(
    ['_geo_distance' => [
      'pin.location' => [-70, 40],
      'order' => 'asc',
      'unit' => 'km']
    ]
);

$elasticaResultSet = $index->search($elasticaQuery);
$hits = $elasticaResultSet->getResults();