Skip to content

Commit 572de4c

Browse files
committed
Added geo distance sort
1 parent bd821ac commit 572de4c

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/Options/GeoDistanceSort.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace Spameri\ElasticQuery\Options;
6+
7+
8+
/**
9+
* @see https://www.elastic.co/guide/en/elasticsearch/reference/7.3/search-request-body.html#geo-sorting
10+
*/
11+
readonly class GeoDistanceSort implements \Spameri\ElasticQuery\Entity\EntityInterface
12+
{
13+
14+
public function __construct(
15+
public string $field,
16+
public float $lat,
17+
public float $lon,
18+
public string $type = Sort::ASC,
19+
public string $unit = 'km',
20+
public string $mode = 'min',
21+
public string $distanceType = 'arc',
22+
)
23+
{
24+
if ( ! \in_array($type, [Sort::ASC, Sort::DESC], true)) {
25+
throw new \Spameri\ElasticQuery\Exception\InvalidArgumentException(
26+
'Sorting type ' . $type . ' is out of allowed range. See \Spameri\ElasticQuery\Options\Sort for reference.',
27+
);
28+
}
29+
}
30+
31+
32+
public function key(): string
33+
{
34+
return $this->field;
35+
}
36+
37+
38+
public function toArray(): array
39+
{
40+
return [
41+
'_geo_distance' => [
42+
$this->field => [
43+
$this->lat,
44+
$this->lon,
45+
],
46+
'order' => $this->type,
47+
"unit" => $this->unit,
48+
"mode" => $this->mode,
49+
"distance_type" => $this->distanceType,
50+
"ignore_unmapped" => true,
51+
],
52+
];
53+
}
54+
55+
}

0 commit comments

Comments
 (0)