WIP|FEATURE: Add field and sorting

Sort result by distance and provide distance to result items.
This commit is contained in:
Daniel Siepmann 2017-10-22 17:51:04 +02:00
parent 8d343ee97f
commit b1f81c0d3b
Signed by: Daniel Siepmann
GPG key ID: 33D6629915560EF4

View file

@ -65,6 +65,8 @@ class QueryFactory
$this->addBoosts($searchRequest, $query); $this->addBoosts($searchRequest, $query);
$this->addFilter($searchRequest, $query); $this->addFilter($searchRequest, $query);
$this->addFacets($searchRequest, $query); $this->addFacets($searchRequest, $query);
$this->addFields($searchRequest, $query);
$this->addSort($searchRequest, $query);
// Use last, as it might change structure of query. // Use last, as it might change structure of query.
// Better approach would be something like DQL to generate query and build result in the end. // Better approach would be something like DQL to generate query and build result in the end.
@ -148,6 +150,44 @@ class QueryFactory
} }
} }
protected function addFields(SearchRequestInterface $searchRequest, array &$query)
{
$query = ArrayUtility::arrayMergeRecursiveOverrule($query, [
'stored_fields' => [ '_source' ],
]);
$query = ArrayUtility::arrayMergeRecursiveOverrule($query, [
'script_fields' => [
'distance' => [
'script' => [
'params' => [
'lat' => 51.168098,
'lon' => 6.381384,
],
'lang' => 'painless',
'inline' => 'doc["location"].arcDistance(params.lat,params.lon) * 0.001',
],
],
],
]);
}
protected function addSort(SearchRequestInterface $searchRequest, array &$query)
{
$query = ArrayUtility::arrayMergeRecursiveOverrule($query, [
'sort' => [
'_geo_distance' => [
'location' => [
'lat' => 51.168098,
'lon' => 6.381384,
],
'order' => 'asc',
'unit' => 'km',
'distance_type' => 'plane',
],
],
]);
}
protected function addFilter(SearchRequestInterface $searchRequest, array &$query) protected function addFilter(SearchRequestInterface $searchRequest, array &$query)
{ {
if (! $searchRequest->hasFilter()) { if (! $searchRequest->hasFilter()) {
@ -172,21 +212,6 @@ class QueryFactory
]); ]);
} }
protected function addFacets(SearchRequestInterface $searchRequest, array &$query)
{
foreach ($searchRequest->getFacets() as $facet) {
$query = ArrayUtility::arrayMergeRecursiveOverrule($query, [
'aggs' => [
$facet->getIdentifier() => [
'terms' => [
'field' => $facet->getField(),
],
],
],
]);
}
}
protected function buildFilter(string $name, $value, array $config) : array protected function buildFilter(string $name, $value, array $config) : array
{ {
if ($config === []) { if ($config === []) {
@ -207,4 +232,19 @@ class QueryFactory
return [$config['field'] => $filter]; return [$config['field'] => $filter];
} }
protected function addFacets(SearchRequestInterface $searchRequest, array &$query)
{
foreach ($searchRequest->getFacets() as $facet) {
$query = ArrayUtility::arrayMergeRecursiveOverrule($query, [
'aggs' => [
$facet->getIdentifier() => [
'terms' => [
'field' => $facet->getField(),
],
],
],
]);
}
}
} }