elasticsearch_search_api-1.0.x-dev/modules/elasticsearch_search_api_example/src/Search/Suggest/ExampleTitleSuggester.php

modules/elasticsearch_search_api_example/src/Search/Suggest/ExampleTitleSuggester.php
<?php

namespace Drupal\elasticsearch_search_api_example\Search\Suggest;

use Drupal\elasticsearch_connector\ElasticSearch\Parameters\Factory\IndexFactory;
use Drupal\elasticsearch_search_api\Search\SearchRepository;
use Drupal\elasticsearch_search_api\Search\Suggest\SuggesterInterface;
use Drupal\search_api\Entity\Index;

/**
 * Custom suggester for web.
 */
class ExampleTitleSuggester implements SuggesterInterface {

  /**
   * The index.
   *
   * @var \Drupal\search_api\Entity\Index
   */
  protected $index;

  /**
   * The search repository.
   *
   * @var \Drupal\elasticsearch_search_api\Search\SearchRepository
   */
  protected $repository;

  /**
   * WebTitleSuggester 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) {
    $index = IndexFactory::getIndexName($this->index);

    $response = $this->repository->query([
      'index' => $index,
      'body' => [
        "suggest" => [
          "text" => $text,
          "simple_phrase" => [
            "phrase" => [
              "field" => "title",
              "size" => 1,
              "gram_size" => 1,
              "direct_generator" => [
                [
                  "field" => "title",
                  "suggest_mode" => "missing",
                ],
              ],
            ],
          ],
        ],
      ],
    ]);
    $rawResponse = $response->getRawResponse();
    $rawSuggestions = $rawResponse['suggest']['simple_phrase'][0]['options'];

    return array_map(function ($rawSuggestion) {
      return $rawSuggestion['text'];
    }, $rawSuggestions);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc