public function SearchApiAlgoliaBackend::getAutocompleteSuggestions in Search API Algolia 8
Same name and namespace in other branches
- 3.0.x src/Plugin/search_api/backend/SearchApiAlgoliaBackend.php \Drupal\search_api_algolia\Plugin\search_api\backend\SearchApiAlgoliaBackend::getAutocompleteSuggestions()
- 2.0.x src/Plugin/search_api/backend/SearchApiAlgoliaBackend.php \Drupal\search_api_algolia\Plugin\search_api\backend\SearchApiAlgoliaBackend::getAutocompleteSuggestions()
Implements autocomplete compatible to AutocompleteBackendInterface.
Parameters
\Drupal\search_api\Query\QueryInterface $query: A query representing the completed user input so far.
\Drupal\search_api_autocomplete\SearchInterface $search: An object containing details about the search the user is on, and settings for the autocompletion. See the class documentation for details. Especially $search->options should be checked for settings, like whether to try and estimate result counts for returned suggestions.
string $incomplete_key: The start of another fulltext keyword for the search, which should be completed. Might be empty, in which case all user input up to now was considered completed. Then, additional keywords for the search could be suggested.
string $user_input: The complete user input for the fulltext search keywords so far.
Return value
\Drupal\search_api_autocomplete\Suggestion\SuggestionInterface[] An array of suggestions.
See also
\Drupal\search_api_autocomplete\AutocompleteBackendInterface
File
- src/
Plugin/ search_api/ backend/ SearchApiAlgoliaBackend.php, line 727
Class
- SearchApiAlgoliaBackend
- Class SearchApiAlgoliaBackend.
Namespace
Drupal\search_api_algolia\Plugin\search_api\backendCode
public function getAutocompleteSuggestions(QueryInterface $query, SearchInterface $search, $incomplete_key, $user_input) {
$suggestions = [];
if (class_exists(SuggestionFactory::class)) {
$factory = new SuggestionFactory($user_input);
}
$search_api_index = $query
->getIndex();
try {
$this
->connect($search_api_index, '_query');
$index = $this
->getAlgoliaIndex();
} catch (\Exception $e) {
$this
->getLogger()
->error('Failed to connect to Algolia index with suffix: @suffix, Error: @message', [
'@message' => $e
->getMessage(),
'@suffix' => '_query',
]);
return $suggestions;
}
$algolia_options = [
'attributesToRetrieve' => [
'query',
],
'analytics' => TRUE,
];
try {
$data = $index
->search($user_input, $algolia_options);
} catch (\Exception $e) {
$this
->getLogger()
->error('Failed to load autocomplete suggestions from Algolia. Query: @query, Error: @message', [
'@message' => $e
->getMessage(),
'@query' => $user_input,
]);
return $suggestions;
}
foreach ($data['hits'] ?? [] as $row) {
$suggestions[] = $factory
->createFromSuggestedKeys($row['query']);
}
return $suggestions;
}