You are here

public function SearchApiSearchService::search in Fast Autocomplete 7

Implements SearchServiceInterface::search().

Parameters

string $key: The key to use in the search.

string $language: The language to use in the search.

Return value

array The results array containing the resulting nids.

Overrides AbstractSearchService::search

File

src/SearchService/SearchApiSearchService.php, line 21

Class

SearchApiSearchService
Fast Autocomplete backend service class providing Search API search.

Namespace

Drupal\fac\SearchService

Code

public function search($key, $language) {
  $result = array();
  $settings = variable_get('fac_backend_service_settings', array());

  // Load the index and get the limit on results.
  $index = search_api_index_load($settings['index_id']);
  $limit = isset($settings['number_of_results']) ? $settings['number_of_results'] : 5;

  // Build the Search API query.
  $query = new \SearchApiQuery($index, array(
    'limit' => $limit,
    'conjunction' => isset($settings['conjunction']) ? $settings['conjunction'] : 'OR',
  ));

  // Add the keys and sort descending by relevance.
  $query
    ->keys($key)
    ->sort('search_api_relevance', 'DESC');
  $fields = isset($settings['full_text_fields']) ? $settings['full_text_fields'] : '';
  if (!empty($fields)) {
    $query
      ->fields($fields);
  }
  $indexed_fields = $index
    ->getFields();
  if (isset($indexed_fields['language'])) {
    $filter = $query
      ->createFilter('OR');
    $filter
      ->condition('language', $language, '=');
    $filter
      ->condition('language', LANGUAGE_NONE, '=');
    $query
      ->filter($filter);
  }
  if (!empty($settings['bundles']) && isset($indexed_fields['type'])) {
    $filter = $query
      ->createFilter('OR');
    foreach ($settings['bundles'] as $bundle) {
      $filter
        ->condition('type', $bundle, '=');
    }
    $query
      ->filter($filter);
  }

  // Allow other modules to modify the query.
  drupal_alter('fac_search_api_search_query', $query);
  $search_results = $query
    ->execute();
  $etids = array_keys($search_results['results']);

  // Build up the result array.
  foreach ($etids as $etid) {
    $result['items'][] = array(
      'entity_type' => $index->item_type,
      'etid' => $etid,
    );
  }
  return $result;
}