You are here

public function SearchApiElasticsearchConnector::getAutocompleteSuggestions in Elasticsearch Connector 7.2

Same name and namespace in other branches
  1. 7.5 modules/elasticsearch_connector_search_api/service.inc \SearchApiElasticsearchConnector::getAutocompleteSuggestions()
  2. 7 modules/elasticsearch_connector_search_api/service.inc \SearchApiElasticsearchConnector::getAutocompleteSuggestions()

Implements SearchApiAutocompleteInterface::getAutocompleteSuggestions().

File

modules/elasticsearch_connector_search_api/service.inc, line 1986
Provides a Elasticsearch-based service class for the Search API using Elasticsearch Connector module.

Class

SearchApiElasticsearchConnector
Search service class.

Code

public function getAutocompleteSuggestions(SearchApiQueryInterface $query, SearchApiAutocompleteSearch $search, $incomplete_key, $user_input) {
  $suggestions = array();

  // Turn inputs to lower case, otherwise we get case sensivity problems.
  $incomp = drupal_strtolower($incomplete_key);
  $index = $query
    ->getIndex();
  $complete = $query
    ->getOriginalKeys();
  $query
    ->keys($user_input);
  try {
    $query
      ->setOption(self::PREFIX_SEARCH, TRUE);
    $query
      ->setOption(self::PREFIX_SEARCH_FIELDS, array_flip($query
      ->getFields()));
    $response = $this
      ->search($query, TRUE);

    // Postprocess the search results.
    $query
      ->postExecute($response);
  } catch (Exception $e) {
    watchdog('Elasticsearch Search API', check_plain($e
      ->getMessage()), array(), WATCHDOG_ERROR);
    return array();
  }
  $matches = array();
  if (isset($response['results'])) {
    $label_field = $index
      ->datasource()
      ->getMetadataWrapper()
      ->entityKey('label');
    $items = $index
      ->loadItems(array_keys($response['results']));
    foreach ($items as $id => $item) {
      $item_title = isset($response['results'][$id]['fields'][$label_field]) ? $response['results'][$id]['fields'][$label_field] : $index
        ->datasource()
        ->getItemLabel($item);
      $url_item = $index
        ->datasource()
        ->getItemUrl($item);
      if (!empty($search->options['custom']['link_suggestions'])) {
        $matches[$item_title] = array(
          'key' => $index
            ->datasource()
            ->getItemLabel($item),
          'user_input' => '',
          'suggestion_suffix' => $item_title,
          'render' => l($item_title, $url_item['path'], array(
            'html' => TRUE,
          )),
        );
      }
      else {
        $matches[$item_title] = array(
          'key' => $index
            ->datasource()
            ->getItemLabel($item),
          'user_input' => '',
          'suggestion_suffix' => $item_title,
          'render' => $item_title,
        );
      }
    }
    return $matches;
  }
}