You are here

public function SearchApiElasticsearchBackend::getAutocompleteSuggestions in Elasticsearch Connector 8.7

Same name and namespace in other branches
  1. 8 src/Plugin/search_api/backend/SearchApiElasticsearchBackend.php \Drupal\elasticsearch_connector\Plugin\search_api\backend\SearchApiElasticsearchBackend::getAutocompleteSuggestions()
  2. 8.5 src/Plugin/search_api/backend/SearchApiElasticsearchBackend.php \Drupal\elasticsearch_connector\Plugin\search_api\backend\SearchApiElasticsearchBackend::getAutocompleteSuggestions()
  3. 8.6 src/Plugin/search_api/backend/SearchApiElasticsearchBackend.php \Drupal\elasticsearch_connector\Plugin\search_api\backend\SearchApiElasticsearchBackend::getAutocompleteSuggestions()

Implements SearchApiAutocompleteInterface::getAutocompleteSuggestions().

Note that the interface is not directly implemented to avoid a dependency on search_api_autocomplete module.

Parameters

\Drupal\search_api\Query\QueryInterface $query: The query interface parameter.

\Drupal\search_api_autocomplete\SearchInterface $search: The search interface parameter.

mixed $incomplete_key: The incomplete key parameter.

string|null $user_input: The keywords input by the user so far.

Return value

array Returns autocomplete suggestion array.

File

src/Plugin/search_api/backend/SearchApiElasticsearchBackend.php, line 566

Class

SearchApiElasticsearchBackend
Elasticsearch Search API Backend definition.

Namespace

Drupal\elasticsearch_connector\Plugin\search_api\backend

Code

public function getAutocompleteSuggestions(QueryInterface $query, SearchInterface $search, $incomplete_key, $user_input) {
  try {
    $fields = $this
      ->getQueryFulltextFields($query);
    if (count($fields) > 1) {
      throw new \LogicException('Elasticsearch requires a single fulltext field for use with autocompletion! Please adjust your configuration.');
    }
    $query
      ->setOption('autocomplete', $incomplete_key);
    $query
      ->setOption('autocomplete_field', reset($fields));

    // Disable facets so it does not collide with auto-completion results.
    $query
      ->setOption('search_api_facets', FALSE);
    $result = $this
      ->search($query);
    $query
      ->postExecute($result);

    // Parse suggestions out of the response.
    $suggestions = [];
    $factory = new SuggestionFactory($user_input);
    $response = $result
      ->getExtraData('elasticsearch_response');
    if (isset($response['aggregations']['autocomplete']['buckets'])) {
      $suffix_start = strlen($incomplete_key);
      $buckets = $response['aggregations']['autocomplete']['buckets'];
      foreach ($buckets as $bucket) {
        $suggestions[] = $factory
          ->createFromSuggestionSuffix(substr($bucket['key'], $suffix_start), $bucket['doc_count']);
      }
    }
    return $suggestions;
  } catch (\Exception $e) {
    $this->logger
      ->error($e
      ->getMessage());
    return [];
  }
}