elasticsearch_search_api-1.0.x-dev/modules/elasticsearch_search_api_example/src/Search/ExampleElasticSearchResultParser.php
modules/elasticsearch_search_api_example/src/Search/ExampleElasticSearchResultParser.php
<?php
namespace Drupal\elasticsearch_search_api_example\Search;
use Drupal\elasticsearch_search_api\Search\ElasticSearchResultParser;
use Drupal\elasticsearch_search_api\Search\Facet\Control\CompositeFacetControlInterface;
use Drupal\elasticsearch_search_api\Search\FacetedSearchActionInterface;
use Drupal\elasticsearch_search_api\Search\SearchResult;
/**
* Parses a raw ElasticSearch response into a SearchResult object.
*/
class ExampleElasticSearchResultParser extends ElasticSearchResultParser {
/**
* Parses a raw ElasticSearch response into a SearchResult object.
*
* @param \Drupal\elasticsearch_search_api\Search\FacetedSearchActionInterface $searchAction
* The current search action.
* @param array $response
* The raw ElasticSearch response, as an array.
*
* @return \Drupal\elasticsearch_search_api\Search\SearchResult
* The parsed search result.
*/
public function parse(FacetedSearchActionInterface $searchAction, array $response): SearchResult {
$total = (int) $response['hits']['total']['value'];
$raw_hits = $response['hits']['hits'];
$facetCounts = [];
$aggs = $response['aggregations'] ?? [];
foreach ($searchAction->getAvailableFacets() as $facet) {
if (!isset($aggs[$facet])) {
$facetCounts[$facet] = [];
}
else {
$aggregation = $aggs[$facet];
$buckets = isset($aggregation['filtered']) ? $aggregation['filtered']['buckets'] : $aggregation['buckets'];
$facetCounts[$facet] = array_column($buckets, 'doc_count', 'key');
if (\Drupal::hasService('elasticsearch_search_api.facet_control.' . $facet)) {
$facetControlService = \Drupal::service('elasticsearch_search_api.facet_control.' . $facet);
if ($facetControlService instanceof CompositeFacetControlInterface) {
$facetCounts[$facet] = $facetControlService->parseResult($facetCounts[$facet]);
}
}
}
}
return new SearchResult($total, $raw_hits, $facetCounts);
}
}
