You are here

public function SearchApiDbService::search in Search API Database Search 7

Executes a search on the server represented by this object.

Parameters

$query: The SearchApiQueryInterface object to execute.

Return value

array An associative array containing the search results, as required by SearchApiQueryInterface::execute().

Throws

SearchApiException If an error prevented the search from completing.

Overrides SearchApiServiceInterface::search

File

./service.inc, line 1181
Contains SearchApiDbService.

Class

SearchApiDbService
Indexes and searches items using the database.

Code

public function search(SearchApiQueryInterface $query) {
  $time_method_called = microtime(TRUE);
  $this->ignored = $this->warnings = array();
  $index = $query
    ->getIndex();
  if (empty($this->options['indexes'][$index->machine_name])) {
    throw new SearchApiException(t('Unknown index @id.', array(
      '@id' => $index->machine_name,
    )));
  }
  $fields = $this
    ->getFieldInfo($index);
  $db_query = $this
    ->createDbQuery($query, $fields);
  $time_processing_done = microtime(TRUE);
  $results = array(
    'results' => array(),
  );
  $skip_count = $query
    ->getOption('skip result count');
  if (!$skip_count) {
    $count_query = $db_query
      ->countQuery();
    $results['result count'] = $count_query
      ->execute()
      ->fetchField();
  }
  if ($skip_count || $results['result count']) {
    if ($query
      ->getOption('search_api_facets')) {
      $results['search_api_facets'] = $this
        ->getFacets($query, clone $db_query);
    }
    $query_options = $query
      ->getOptions();
    if (isset($query_options['offset']) || isset($query_options['limit'])) {
      $offset = isset($query_options['offset']) ? $query_options['offset'] : 0;
      $limit = isset($query_options['limit']) ? $query_options['limit'] : 1000000;
      $db_query
        ->range($offset, $limit);
    }
    $this
      ->setQuerySort($query, $db_query, $fields);
    $result = $db_query
      ->execute();
    foreach ($result as $row) {
      $results['results'][$row->item_id] = array(
        'id' => $row->item_id,
        'score' => $row->score / self::SCORE_MULTIPLIER,
      );
    }
    if ($skip_count) {
      $results['result count'] = !empty($results['results']);
    }
  }
  $time_queries_done = microtime(TRUE);
  $results['warnings'] = array_keys($this->warnings);
  $results['ignored'] = array_keys($this->ignored);
  $this
    ->postQuery($results, $query);
  $time_end = microtime(TRUE);
  $results['performance'] = array(
    'complete' => $time_end - $time_method_called,
    'preprocessing' => $time_processing_done - $time_method_called,
    'execution' => $time_queries_done - $time_processing_done,
    'postprocessing' => $time_end - $time_queries_done,
  );
  return $results;
}