You are here

public static function SearchFactory::parseResult in Elasticsearch Connector 8.7

Same name and namespace in other branches
  1. 8.2 src/ElasticSearch/Parameters/Factory/SearchFactory.php \Drupal\elasticsearch_connector\ElasticSearch\Parameters\Factory\SearchFactory::parseResult()
  2. 8.5 src/ElasticSearch/Parameters/Factory/SearchFactory.php \Drupal\elasticsearch_connector\ElasticSearch\Parameters\Factory\SearchFactory::parseResult()
  3. 8.6 src/ElasticSearch/Parameters/Factory/SearchFactory.php \Drupal\elasticsearch_connector\ElasticSearch\Parameters\Factory\SearchFactory::parseResult()

Parse a Elasticsearch response into a ResultSetInterface.

TODO: Add excerpt handling.

Parameters

\Drupal\search_api\Query\QueryInterface $query: Search API query.

array $response: Raw response array back from Elasticsearch.

Return value

\Drupal\search_api\Query\ResultSetInterface The results of the search.

1 call to SearchFactory::parseResult()
SearchApiElasticsearchBackend::search in src/Plugin/search_api/backend/SearchApiElasticsearchBackend.php
Executes a search on this server.

File

src/ElasticSearch/Parameters/Factory/SearchFactory.php, line 42

Class

SearchFactory
Class SearchFactory.

Namespace

Drupal\elasticsearch_connector\ElasticSearch\Parameters\Factory

Code

public static function parseResult(QueryInterface $query, array $response) {
  $index = $query
    ->getIndex();

  // Set up the results array.
  $results = $query
    ->getResults();
  $results
    ->setExtraData('elasticsearch_response', $response);
  $results
    ->setResultCount($response['hits']['total']['value']);

  /** @var \Drupal\search_api\Utility\FieldsHelper $fields_helper */
  $fields_helper = \Drupal::getContainer()
    ->get('search_api.fields_helper');

  // Add each search result to the results array.
  if (!empty($response['hits']['hits'])) {
    foreach ($response['hits']['hits'] as $result) {
      $result_item = $fields_helper
        ->createItem($index, $result['_id']);
      $result_item
        ->setScore($result['_score']);

      // Set each item in _source as a field in Search API.
      foreach ($result['_source'] as $elasticsearch_property_id => $elasticsearch_property) {

        // Make everything a multifield.
        if (!is_array($elasticsearch_property)) {
          $elasticsearch_property = [
            $elasticsearch_property,
          ];
        }
        $field = $fields_helper
          ->createField($index, $elasticsearch_property_id, [
          'property_path' => $elasticsearch_property_id,
        ]);
        $field
          ->setValues($elasticsearch_property);
        $result_item
          ->setField($elasticsearch_property_id, $field);
      }
      $results
        ->addResultItem($result_item);
    }
  }
  return $results;
}