elasticsearch_search_api-1.0.x-dev/src/Search/Suggest/TitleSuggester.php
src/Search/Suggest/TitleSuggester.php
<?php
namespace Drupal\elasticsearch_search_api\Search\Suggest;
use Drupal\elasticsearch_search_api\Search\SearchRepository;
use Drupal\elasticsearch_connector\ElasticSearch\Parameters\Factory\IndexFactory;
use Drupal\search_api\Entity\Index;
/**
* Adds a suggester to the 'title' field.
*/
class TitleSuggester implements SuggesterInterface {
/**
* The index.
*
* @var \Drupal\search_api\Entity\Index
*/
protected $index;
/**
* The search repository.
*
* @var \Drupal\elasticsearch_search_api\Search\SearchRepository
*/
protected $repository;
/**
* TitleSuggester constructor.
*
* @param \Drupal\search_api\Entity\Index $index
* The index.
* @param \Drupal\elasticsearch_search_api\Search\SearchRepository $repository
* The search repository.
*/
public function __construct(Index $index, SearchRepository $repository) {
$this->index = $index;
$this->repository = $repository;
}
/**
* {@inheritdoc}
*/
public function suggest(string $text, $suggest_mode = 'missing', $gram_size = 1) {
$index = IndexFactory::getIndexName($this->index);
$response = $this->repository->query([
'index' => $index,
'body' => [
"suggest" => [
"text" => $text,
"simple_phrase" => [
"phrase" => [
"field" => "title",
"size" => 1,
"gram_size" => $gram_size,
"direct_generator" => [
[
"field" => "title",
"suggest_mode" => $suggest_mode,
],
],
],
],
],
],
]);
$rawResponse = $response->getRawResponse();
$rawSuggestions = $rawResponse['suggest']['simple_phrase'][0]['options'];
return array_map(function ($rawSuggestion) {
return $rawSuggestion['text'];
}, $rawSuggestions);
}
}
