You are here

public function SearchQuery::execute in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/search/src/SearchQuery.php \Drupal\search\SearchQuery::execute()

Executes the search.

The complex conditions are applied to the query including score expressions and ordering.

Error and warning conditions can apply. Call getStatus() after calling this method to retrieve them.

Return value

\Drupal\Core\Database\StatementInterface|null A query result set containing the results of the query.

Overrides SelectExtender::execute

File

core/modules/search/src/SearchQuery.php, line 548

Class

SearchQuery
Search query extender and helper functions.

Namespace

Drupal\search

Code

public function execute() {
  if (!$this
    ->preExecute($this)) {
    return NULL;
  }

  // Add conditions to the query.
  $this
    ->join('search_dataset', 'd', '[i].[sid] = [d].[sid] AND [i].[type] = [d].[type] AND [i].[langcode] = [d].[langcode]');
  if (count($this->conditions)) {
    $this
      ->condition($this->conditions);
  }

  // Add default score (keyword relevance) if there are not any defined.
  if (empty($this->scores)) {
    $this
      ->addScore('i.relevance');
  }
  if (count($this->multiply)) {

    // Re-normalize scores with multipliers by dividing by the total of all
    // multipliers. The expressions were altered in addScore(), so here just
    // add the arguments for the total.
    $sum = array_sum($this->multiply);
    for ($i = 0; $i < count($this->multiply); $i++) {
      $this->scoresArguments[':total_' . $i] = $sum;
    }
  }

  // Add arguments for the keyword relevance normalization number.
  $normalization = 1.0 / $this->normalize;
  for ($i = 0; $i < $this->relevance_count; $i++) {
    $this->scoresArguments[':normalization_' . $i] = $normalization;
  }

  // Add all scores together to form a query field.
  $this
    ->addExpression('SUM(' . implode(' + ', $this->scores) . ')', 'calculated_score', $this->scoresArguments);

  // If an order has not yet been set for this query, add a default order
  // that sorts by the calculated sum of scores.
  if (count($this
    ->getOrderBy()) == 0) {
    $this
      ->orderBy('calculated_score', 'DESC');
  }

  // Add query metadata.
  $this
    ->addMetaData('normalize', $this->normalize)
    ->fields('i', [
    'type',
    'sid',
  ]);
  return $this->query
    ->execute();
}