public function SearchApiElasticsearchBackend::getAutocompleteSuggestions in Elasticsearch Connector 8.6
Same name and namespace in other branches
- 8.7 src/Plugin/search_api/backend/SearchApiElasticsearchBackend.php \Drupal\elasticsearch_connector\Plugin\search_api\backend\SearchApiElasticsearchBackend::getAutocompleteSuggestions()
- 8 src/Plugin/search_api/backend/SearchApiElasticsearchBackend.php \Drupal\elasticsearch_connector\Plugin\search_api\backend\SearchApiElasticsearchBackend::getAutocompleteSuggestions()
- 8.5 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.
File
- src/
Plugin/ search_api/ backend/ SearchApiElasticsearchBackend.php, line 550
Class
- SearchApiElasticsearchBackend
- Elasticsearch Search API Backend definition.
Namespace
Drupal\elasticsearch_connector\Plugin\search_api\backendCode
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 autocompletion 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($user_input);
$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 array();
}
}