annotate core/modules/search/src/SearchQuery.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\search;
Chris@0 4
Chris@0 5 use Drupal\Core\Database\Query\Condition;
Chris@0 6 use Drupal\Core\Database\Query\SelectExtender;
Chris@0 7 use Drupal\Core\Database\Query\SelectInterface;
Chris@0 8
Chris@0 9 /**
Chris@0 10 * Search query extender and helper functions.
Chris@0 11 *
Chris@0 12 * Performs a query on the full-text search index for a word or words.
Chris@0 13 *
Chris@0 14 * This query is used by search plugins that use the search index (not all
Chris@0 15 * search plugins do, as some use a different searching mechanism). It
Chris@0 16 * assumes you have set up a query on the {search_index} table with alias 'i',
Chris@0 17 * and will only work if the user is searching for at least one "positive"
Chris@0 18 * keyword or phrase.
Chris@0 19 *
Chris@0 20 * For efficiency, users of this query can run the prepareAndNormalize()
Chris@0 21 * method to figure out if there are any search results, before fully setting
Chris@0 22 * up and calling execute() to execute the query. The scoring expressions are
Chris@0 23 * not needed until the execute() step. However, it's not really necessary
Chris@0 24 * to do this, because this class's execute() method does that anyway.
Chris@0 25 *
Chris@0 26 * During both the prepareAndNormalize() and execute() steps, there can be
Chris@0 27 * problems. Call getStatus() to figure out if the query is OK or not.
Chris@0 28 *
Chris@0 29 * The query object is given the tag 'search_$type' and can be further
Chris@0 30 * extended with hook_query_alter().
Chris@0 31 */
Chris@0 32 class SearchQuery extends SelectExtender {
Chris@0 33
Chris@0 34 /**
Chris@0 35 * Indicates no positive keywords were in the search expression.
Chris@0 36 *
Chris@0 37 * Positive keywords are words that are searched for, as opposed to negative
Chris@0 38 * keywords, which are words that are excluded. To count as a keyword, a
Chris@0 39 * word must be at least
Chris@0 40 * \Drupal::config('search.settings')->get('index.minimum_word_size')
Chris@0 41 * characters.
Chris@0 42 *
Chris@0 43 * @see SearchQuery::getStatus()
Chris@0 44 */
Chris@0 45 const NO_POSITIVE_KEYWORDS = 1;
Chris@0 46
Chris@0 47 /**
Chris@0 48 * Indicates that part of the search expression was ignored.
Chris@0 49 *
Chris@0 50 * To prevent Denial of Service attacks, only
Chris@0 51 * \Drupal::config('search.settings')->get('and_or_limit') expressions
Chris@0 52 * (positive keywords, phrases, negative keywords) are allowed; this flag
Chris@0 53 * indicates that expressions existed past that limit and they were removed.
Chris@0 54 *
Chris@0 55 * @see SearchQuery::getStatus()
Chris@0 56 */
Chris@0 57 const EXPRESSIONS_IGNORED = 2;
Chris@0 58
Chris@0 59 /**
Chris@0 60 * Indicates that lower-case "or" was in the search expression.
Chris@0 61 *
Chris@0 62 * The word "or" in lower case was found in the search expression. This
Chris@0 63 * probably means someone was trying to do an OR search but used lower-case
Chris@0 64 * instead of upper-case.
Chris@0 65 *
Chris@0 66 * @see SearchQuery::getStatus()
Chris@0 67 */
Chris@0 68 const LOWER_CASE_OR = 4;
Chris@0 69
Chris@0 70 /**
Chris@0 71 * Indicates that no positive keyword matches were found.
Chris@0 72 *
Chris@0 73 * @see SearchQuery::getStatus()
Chris@0 74 */
Chris@0 75 const NO_KEYWORD_MATCHES = 8;
Chris@0 76
Chris@0 77 /**
Chris@0 78 * The keywords and advanced search options that are entered by the user.
Chris@0 79 *
Chris@0 80 * @var string
Chris@0 81 */
Chris@0 82 protected $searchExpression;
Chris@0 83
Chris@0 84 /**
Chris@0 85 * The type of search (search type).
Chris@0 86 *
Chris@0 87 * This maps to the value of the type column in search_index, and is usually
Chris@0 88 * equal to the machine-readable name of the plugin or the search page.
Chris@0 89 *
Chris@0 90 * @var string
Chris@0 91 */
Chris@0 92 protected $type;
Chris@0 93
Chris@0 94 /**
Chris@0 95 * Parsed-out positive and negative search keys.
Chris@0 96 *
Chris@0 97 * @var array
Chris@0 98 */
Chris@0 99 protected $keys = ['positive' => [], 'negative' => []];
Chris@0 100
Chris@0 101 /**
Chris@0 102 * Indicates whether the query conditions are simple or complex (LIKE).
Chris@0 103 *
Chris@0 104 * @var bool
Chris@0 105 */
Chris@0 106 protected $simple = TRUE;
Chris@0 107
Chris@0 108 /**
Chris@0 109 * Conditions that are used for exact searches.
Chris@0 110 *
Chris@0 111 * This is always used for the second step in the query, but is not part of
Chris@0 112 * the preparation step unless $this->simple is FALSE.
Chris@0 113 *
Chris@18 114 * @var Drupal\Core\Database\Query\ConditionInterface[]
Chris@0 115 */
Chris@0 116 protected $conditions;
Chris@0 117
Chris@0 118 /**
Chris@0 119 * Indicates how many matches for a search query are necessary.
Chris@0 120 *
Chris@0 121 * @var int
Chris@0 122 */
Chris@0 123 protected $matches = 0;
Chris@0 124
Chris@0 125 /**
Chris@0 126 * Array of positive search words.
Chris@0 127 *
Chris@0 128 * These words have to match against {search_index}.word.
Chris@0 129 *
Chris@0 130 * @var array
Chris@0 131 */
Chris@0 132 protected $words = [];
Chris@0 133
Chris@0 134 /**
Chris@0 135 * Multiplier to normalize the keyword score.
Chris@0 136 *
Chris@0 137 * This value is calculated by the preparation step, and is used as a
Chris@0 138 * multiplier of the word scores to make sure they are between 0 and 1.
Chris@0 139 *
Chris@0 140 * @var float
Chris@0 141 */
Chris@0 142 protected $normalize = 0;
Chris@0 143
Chris@0 144 /**
Chris@0 145 * Indicates whether the preparation step has been executed.
Chris@0 146 *
Chris@0 147 * @var bool
Chris@0 148 */
Chris@0 149 protected $executedPrepare = FALSE;
Chris@0 150
Chris@0 151 /**
Chris@0 152 * A bitmap of status conditions, described in getStatus().
Chris@0 153 *
Chris@0 154 * @var int
Chris@0 155 *
Chris@0 156 * @see SearchQuery::getStatus()
Chris@0 157 */
Chris@0 158 protected $status = 0;
Chris@0 159
Chris@0 160 /**
Chris@0 161 * The word score expressions.
Chris@0 162 *
Chris@0 163 * @var array
Chris@0 164 *
Chris@0 165 * @see SearchQuery::addScore()
Chris@0 166 */
Chris@0 167 protected $scores = [];
Chris@0 168
Chris@0 169 /**
Chris@0 170 * Arguments for the score expressions.
Chris@0 171 *
Chris@0 172 * @var array
Chris@0 173 */
Chris@0 174 protected $scoresArguments = [];
Chris@0 175
Chris@0 176 /**
Chris@0 177 * The number of 'i.relevance' occurrences in score expressions.
Chris@0 178 *
Chris@0 179 * @var int
Chris@0 180 */
Chris@0 181 protected $relevance_count = 0;
Chris@0 182
Chris@0 183 /**
Chris@0 184 * Multipliers for score expressions.
Chris@0 185 *
Chris@0 186 * @var array
Chris@0 187 */
Chris@0 188 protected $multiply = [];
Chris@0 189
Chris@0 190 /**
Chris@0 191 * Sets the search query expression.
Chris@0 192 *
Chris@0 193 * @param string $expression
Chris@0 194 * A search string, which can contain keywords and options.
Chris@0 195 * @param string $type
Chris@0 196 * The search type. This maps to {search_index}.type in the database.
Chris@0 197 *
Chris@0 198 * @return $this
Chris@0 199 */
Chris@0 200 public function searchExpression($expression, $type) {
Chris@0 201 $this->searchExpression = $expression;
Chris@0 202 $this->type = $type;
Chris@0 203
Chris@0 204 // Add query tag.
Chris@0 205 $this->addTag('search_' . $type);
Chris@0 206
Chris@0 207 // Initialize conditions and status.
Chris@0 208 $this->conditions = new Condition('AND');
Chris@0 209 $this->status = 0;
Chris@0 210
Chris@0 211 return $this;
Chris@0 212 }
Chris@0 213
Chris@0 214 /**
Chris@0 215 * Parses the search query into SQL conditions.
Chris@0 216 *
Chris@0 217 * Sets up the following variables:
Chris@0 218 * - $this->keys
Chris@0 219 * - $this->words
Chris@0 220 * - $this->conditions
Chris@0 221 * - $this->simple
Chris@0 222 * - $this->matches
Chris@0 223 */
Chris@0 224 protected function parseSearchExpression() {
Chris@0 225 // Matches words optionally prefixed by a - sign. A word in this case is
Chris@0 226 // something between two spaces, optionally quoted.
Chris@0 227 preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $this->searchExpression, $keywords, PREG_SET_ORDER);
Chris@0 228
Chris@0 229 if (count($keywords) == 0) {
Chris@0 230 return;
Chris@0 231 }
Chris@0 232
Chris@0 233 // Classify tokens.
Chris@0 234 $in_or = FALSE;
Chris@0 235 $limit_combinations = \Drupal::config('search.settings')->get('and_or_limit');
Chris@0 236 // The first search expression does not count as AND.
Chris@0 237 $and_count = -1;
Chris@0 238 $or_count = 0;
Chris@0 239 foreach ($keywords as $match) {
Chris@0 240 if ($or_count && $and_count + $or_count >= $limit_combinations) {
Chris@0 241 // Ignore all further search expressions to prevent Denial-of-Service
Chris@0 242 // attacks using a high number of AND/OR combinations.
Chris@0 243 $this->status |= SearchQuery::EXPRESSIONS_IGNORED;
Chris@0 244 break;
Chris@0 245 }
Chris@0 246
Chris@0 247 // Strip off phrase quotes.
Chris@0 248 $phrase = FALSE;
Chris@0 249 if ($match[2]{0} == '"') {
Chris@0 250 $match[2] = substr($match[2], 1, -1);
Chris@0 251 $phrase = TRUE;
Chris@0 252 $this->simple = FALSE;
Chris@0 253 }
Chris@0 254
Chris@0 255 // Simplify keyword according to indexing rules and external
Chris@0 256 // preprocessors. Use same process as during search indexing, so it
Chris@0 257 // will match search index.
Chris@0 258 $words = search_simplify($match[2]);
Chris@0 259 // Re-explode in case simplification added more words, except when
Chris@0 260 // matching a phrase.
Chris@0 261 $words = $phrase ? [$words] : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
Chris@0 262 // Negative matches.
Chris@0 263 if ($match[1] == '-') {
Chris@0 264 $this->keys['negative'] = array_merge($this->keys['negative'], $words);
Chris@0 265 }
Chris@0 266 // OR operator: instead of a single keyword, we store an array of all
Chris@0 267 // OR'd keywords.
Chris@0 268 elseif ($match[2] == 'OR' && count($this->keys['positive'])) {
Chris@0 269 $last = array_pop($this->keys['positive']);
Chris@0 270 // Starting a new OR?
Chris@0 271 if (!is_array($last)) {
Chris@0 272 $last = [$last];
Chris@0 273 }
Chris@0 274 $this->keys['positive'][] = $last;
Chris@0 275 $in_or = TRUE;
Chris@0 276 $or_count++;
Chris@0 277 continue;
Chris@0 278 }
Chris@0 279 // AND operator: implied, so just ignore it.
Chris@0 280 elseif ($match[2] == 'AND' || $match[2] == 'and') {
Chris@0 281 continue;
Chris@0 282 }
Chris@0 283
Chris@0 284 // Plain keyword.
Chris@0 285 else {
Chris@0 286 if ($match[2] == 'or') {
Chris@0 287 // Lower-case "or" instead of "OR" is a warning condition.
Chris@0 288 $this->status |= SearchQuery::LOWER_CASE_OR;
Chris@0 289 }
Chris@0 290 if ($in_or) {
Chris@0 291 // Add to last element (which is an array).
Chris@0 292 $this->keys['positive'][count($this->keys['positive']) - 1] = array_merge($this->keys['positive'][count($this->keys['positive']) - 1], $words);
Chris@0 293 }
Chris@0 294 else {
Chris@0 295 $this->keys['positive'] = array_merge($this->keys['positive'], $words);
Chris@0 296 $and_count++;
Chris@0 297 }
Chris@0 298 }
Chris@0 299 $in_or = FALSE;
Chris@0 300 }
Chris@0 301
Chris@0 302 // Convert keywords into SQL statements.
Chris@0 303 $has_and = FALSE;
Chris@0 304 $has_or = FALSE;
Chris@0 305 // Positive matches.
Chris@0 306 foreach ($this->keys['positive'] as $key) {
Chris@0 307 // Group of ORed terms.
Chris@0 308 if (is_array($key) && count($key)) {
Chris@0 309 // If we had already found one OR, this is another one AND-ed with the
Chris@0 310 // first, meaning it is not a simple query.
Chris@0 311 if ($has_or) {
Chris@0 312 $this->simple = FALSE;
Chris@0 313 }
Chris@0 314 $has_or = TRUE;
Chris@0 315 $has_new_scores = FALSE;
Chris@0 316 $queryor = new Condition('OR');
Chris@0 317 foreach ($key as $or) {
Chris@0 318 list($num_new_scores) = $this->parseWord($or);
Chris@0 319 $has_new_scores |= $num_new_scores;
Chris@0 320 $queryor->condition('d.data', "% $or %", 'LIKE');
Chris@0 321 }
Chris@0 322 if (count($queryor)) {
Chris@0 323 $this->conditions->condition($queryor);
Chris@0 324 // A group of OR keywords only needs to match once.
Chris@0 325 $this->matches += ($has_new_scores > 0);
Chris@0 326 }
Chris@0 327 }
Chris@0 328 // Single ANDed term.
Chris@0 329 else {
Chris@0 330 $has_and = TRUE;
Chris@0 331 list($num_new_scores, $num_valid_words) = $this->parseWord($key);
Chris@0 332 $this->conditions->condition('d.data', "% $key %", 'LIKE');
Chris@0 333 if (!$num_valid_words) {
Chris@0 334 $this->simple = FALSE;
Chris@0 335 }
Chris@0 336 // Each AND keyword needs to match at least once.
Chris@0 337 $this->matches += $num_new_scores;
Chris@0 338 }
Chris@0 339 }
Chris@0 340 if ($has_and && $has_or) {
Chris@0 341 $this->simple = FALSE;
Chris@0 342 }
Chris@0 343
Chris@0 344 // Negative matches.
Chris@0 345 foreach ($this->keys['negative'] as $key) {
Chris@0 346 $this->conditions->condition('d.data', "% $key %", 'NOT LIKE');
Chris@0 347 $this->simple = FALSE;
Chris@0 348 }
Chris@0 349 }
Chris@0 350
Chris@0 351 /**
Chris@0 352 * Parses a word or phrase for parseQuery().
Chris@0 353 *
Chris@0 354 * Splits a phrase into words. Adds its words to $this->words, if it is not
Chris@0 355 * already there. Returns a list containing the number of new words found,
Chris@0 356 * and the total number of words in the phrase.
Chris@0 357 */
Chris@0 358 protected function parseWord($word) {
Chris@0 359 $num_new_scores = 0;
Chris@0 360 $num_valid_words = 0;
Chris@0 361
Chris@0 362 // Determine the scorewords of this word/phrase.
Chris@0 363 $split = explode(' ', $word);
Chris@0 364 foreach ($split as $s) {
Chris@0 365 $num = is_numeric($s);
Chris@17 366 if ($num || mb_strlen($s) >= \Drupal::config('search.settings')->get('index.minimum_word_size')) {
Chris@0 367 if (!isset($this->words[$s])) {
Chris@0 368 $this->words[$s] = $s;
Chris@0 369 $num_new_scores++;
Chris@0 370 }
Chris@0 371 $num_valid_words++;
Chris@0 372 }
Chris@0 373 }
Chris@0 374
Chris@0 375 // Return matching snippet and number of added words.
Chris@0 376 return [$num_new_scores, $num_valid_words];
Chris@0 377 }
Chris@0 378
Chris@0 379 /**
Chris@0 380 * Prepares the query and calculates the normalization factor.
Chris@0 381 *
Chris@0 382 * After the query is normalized the keywords are weighted to give the results
Chris@0 383 * a relevancy score. The query is ready for execution after this.
Chris@0 384 *
Chris@0 385 * Error and warning conditions can apply. Call getStatus() after calling
Chris@0 386 * this method to retrieve them.
Chris@0 387 *
Chris@0 388 * @return bool
Chris@0 389 * TRUE if at least one keyword matched the search index; FALSE if not.
Chris@0 390 */
Chris@0 391 public function prepareAndNormalize() {
Chris@0 392 $this->parseSearchExpression();
Chris@0 393 $this->executedPrepare = TRUE;
Chris@0 394
Chris@0 395 if (count($this->words) == 0) {
Chris@0 396 // Although the query could proceed, there is no point in joining
Chris@0 397 // with other tables and attempting to normalize if there are no
Chris@0 398 // keywords present.
Chris@0 399 $this->status |= SearchQuery::NO_POSITIVE_KEYWORDS;
Chris@0 400 return FALSE;
Chris@0 401 }
Chris@0 402
Chris@0 403 // Build the basic search query: match the entered keywords.
Chris@0 404 $or = new Condition('OR');
Chris@0 405 foreach ($this->words as $word) {
Chris@0 406 $or->condition('i.word', $word);
Chris@0 407 }
Chris@0 408 $this->condition($or);
Chris@0 409
Chris@0 410 // Add keyword normalization information to the query.
Chris@0 411 $this->join('search_total', 't', 'i.word = t.word');
Chris@0 412 $this
Chris@0 413 ->condition('i.type', $this->type)
Chris@0 414 ->groupBy('i.type')
Chris@0 415 ->groupBy('i.sid');
Chris@0 416
Chris@0 417 // If the query is simple, we should have calculated the number of
Chris@0 418 // matching words we need to find, so impose that criterion. For non-
Chris@0 419 // simple queries, this condition could lead to incorrectly deciding not
Chris@0 420 // to continue with the full query.
Chris@0 421 if ($this->simple) {
Chris@0 422 $this->having('COUNT(*) >= :matches', [':matches' => $this->matches]);
Chris@0 423 }
Chris@0 424
Chris@0 425 // Clone the query object to calculate normalization.
Chris@0 426 $normalize_query = clone $this->query;
Chris@0 427
Chris@0 428 // For complex search queries, add the LIKE conditions; if the query is
Chris@0 429 // simple, we do not need them for normalization.
Chris@0 430 if (!$this->simple) {
Chris@0 431 $normalize_query->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type AND i.langcode = d.langcode');
Chris@0 432 if (count($this->conditions)) {
Chris@0 433 $normalize_query->condition($this->conditions);
Chris@0 434 }
Chris@0 435 }
Chris@0 436
Chris@0 437 // Calculate normalization, which is the max of all the search scores for
Chris@0 438 // positive keywords in the query. And note that the query could have other
Chris@0 439 // fields added to it by the user of this extension.
Chris@0 440 $normalize_query->addExpression('SUM(i.score * t.count)', 'calculated_score');
Chris@0 441 $result = $normalize_query
Chris@0 442 ->range(0, 1)
Chris@0 443 ->orderBy('calculated_score', 'DESC')
Chris@0 444 ->execute()
Chris@0 445 ->fetchObject();
Chris@0 446 if (isset($result->calculated_score)) {
Chris@0 447 $this->normalize = (float) $result->calculated_score;
Chris@0 448 }
Chris@0 449
Chris@0 450 if ($this->normalize) {
Chris@0 451 return TRUE;
Chris@0 452 }
Chris@0 453
Chris@0 454 // If the normalization value was zero, that indicates there were no
Chris@0 455 // matches to the supplied positive keywords.
Chris@0 456 $this->status |= SearchQuery::NO_KEYWORD_MATCHES;
Chris@0 457 return FALSE;
Chris@0 458 }
Chris@0 459
Chris@0 460 /**
Chris@0 461 * {@inheritdoc}
Chris@0 462 */
Chris@0 463 public function preExecute(SelectInterface $query = NULL) {
Chris@0 464 if (!$this->executedPrepare) {
Chris@0 465 $this->prepareAndNormalize();
Chris@0 466 }
Chris@0 467
Chris@0 468 if (!$this->normalize) {
Chris@0 469 return FALSE;
Chris@0 470 }
Chris@0 471
Chris@0 472 return parent::preExecute($query);
Chris@0 473 }
Chris@0 474
Chris@0 475 /**
Chris@0 476 * Adds a custom score expression to the search query.
Chris@0 477 *
Chris@0 478 * Score expressions are used to order search results. If no calls to
Chris@0 479 * addScore() have taken place, a default keyword relevance score will be
Chris@0 480 * used. However, if at least one call to addScore() has taken place, the
Chris@0 481 * keyword relevance score is not automatically added.
Chris@0 482 *
Chris@0 483 * Note that you must use this method to add ordering to your searches, and
Chris@0 484 * not call orderBy() directly, when using the SearchQuery extender. This is
Chris@0 485 * because of the two-pass system the SearchQuery class uses to normalize
Chris@0 486 * scores.
Chris@0 487 *
Chris@0 488 * @param string $score
Chris@0 489 * The score expression, which should evaluate to a number between 0 and 1.
Chris@0 490 * The string 'i.relevance' in a score expression will be replaced by a
Chris@0 491 * measure of keyword relevance between 0 and 1.
Chris@0 492 * @param array $arguments
Chris@0 493 * Query arguments needed to provide values to the score expression.
Chris@0 494 * @param float $multiply
Chris@0 495 * If set, the score is multiplied with this value. However, all scores
Chris@0 496 * with multipliers are then divided by the total of all multipliers, so
Chris@0 497 * that overall, the normalization is maintained.
Chris@0 498 *
Chris@0 499 * @return $this
Chris@0 500 */
Chris@0 501 public function addScore($score, $arguments = [], $multiply = FALSE) {
Chris@0 502 if ($multiply) {
Chris@0 503 $i = count($this->multiply);
Chris@0 504 // Modify the score expression so it is multiplied by the multiplier,
Chris@0 505 // with a divisor to renormalize. Note that the ROUND here is necessary
Chris@0 506 // for PostgreSQL and SQLite in order to ensure that the :multiply_* and
Chris@0 507 // :total_* arguments are treated as a numeric type, because the
Chris@0 508 // PostgreSQL PDO driver sometimes puts values in as strings instead of
Chris@0 509 // numbers in complex expressions like this.
Chris@0 510 $score = "(ROUND(:multiply_$i, 4)) * COALESCE(($score), 0) / (ROUND(:total_$i, 4))";
Chris@0 511 // Add an argument for the multiplier. The :total_$i argument is taken
Chris@0 512 // care of in the execute() method, which is when the total divisor is
Chris@0 513 // calculated.
Chris@0 514 $arguments[':multiply_' . $i] = $multiply;
Chris@0 515 $this->multiply[] = $multiply;
Chris@0 516 }
Chris@0 517
Chris@0 518 // Search scoring needs a way to include a keyword relevance in the score.
Chris@0 519 // For historical reasons, this is done by putting 'i.relevance' into the
Chris@0 520 // search expression. So, use string replacement to change this to a
Chris@0 521 // calculated query expression, counting the number of occurrences so
Chris@0 522 // in the execute() method we can add arguments.
Chris@0 523 while (($pos = strpos($score, 'i.relevance')) !== FALSE) {
Chris@0 524 $pieces = explode('i.relevance', $score, 2);
Chris@0 525 $score = implode('((ROUND(:normalization_' . $this->relevance_count . ', 4)) * i.score * t.count)', $pieces);
Chris@0 526 $this->relevance_count++;
Chris@0 527 }
Chris@0 528
Chris@0 529 $this->scores[] = $score;
Chris@0 530 $this->scoresArguments += $arguments;
Chris@0 531
Chris@0 532 return $this;
Chris@0 533 }
Chris@0 534
Chris@0 535 /**
Chris@0 536 * Executes the search.
Chris@0 537 *
Chris@0 538 * The complex conditions are applied to the query including score
Chris@0 539 * expressions and ordering.
Chris@0 540 *
Chris@0 541 * Error and warning conditions can apply. Call getStatus() after calling
Chris@0 542 * this method to retrieve them.
Chris@0 543 *
Chris@0 544 * @return \Drupal\Core\Database\StatementInterface|null
Chris@0 545 * A query result set containing the results of the query.
Chris@0 546 */
Chris@0 547 public function execute() {
Chris@0 548 if (!$this->preExecute($this)) {
Chris@0 549 return NULL;
Chris@0 550 }
Chris@0 551
Chris@0 552 // Add conditions to the query.
Chris@0 553 $this->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type AND i.langcode = d.langcode');
Chris@0 554 if (count($this->conditions)) {
Chris@0 555 $this->condition($this->conditions);
Chris@0 556 }
Chris@0 557
Chris@0 558 // Add default score (keyword relevance) if there are not any defined.
Chris@0 559 if (empty($this->scores)) {
Chris@0 560 $this->addScore('i.relevance');
Chris@0 561 }
Chris@0 562
Chris@0 563 if (count($this->multiply)) {
Chris@0 564 // Re-normalize scores with multipliers by dividing by the total of all
Chris@0 565 // multipliers. The expressions were altered in addScore(), so here just
Chris@0 566 // add the arguments for the total.
Chris@0 567 $sum = array_sum($this->multiply);
Chris@0 568 for ($i = 0; $i < count($this->multiply); $i++) {
Chris@0 569 $this->scoresArguments[':total_' . $i] = $sum;
Chris@0 570 }
Chris@0 571 }
Chris@0 572
Chris@0 573 // Add arguments for the keyword relevance normalization number.
Chris@0 574 $normalization = 1.0 / $this->normalize;
Chris@0 575 for ($i = 0; $i < $this->relevance_count; $i++) {
Chris@0 576 $this->scoresArguments[':normalization_' . $i] = $normalization;
Chris@0 577 }
Chris@0 578
Chris@0 579 // Add all scores together to form a query field.
Chris@0 580 $this->addExpression('SUM(' . implode(' + ', $this->scores) . ')', 'calculated_score', $this->scoresArguments);
Chris@0 581
Chris@0 582 // If an order has not yet been set for this query, add a default order
Chris@0 583 // that sorts by the calculated sum of scores.
Chris@0 584 if (count($this->getOrderBy()) == 0) {
Chris@0 585 $this->orderBy('calculated_score', 'DESC');
Chris@0 586 }
Chris@0 587
Chris@0 588 // Add query metadata.
Chris@0 589 $this
Chris@0 590 ->addMetaData('normalize', $this->normalize)
Chris@0 591 ->fields('i', ['type', 'sid']);
Chris@0 592 return $this->query->execute();
Chris@0 593 }
Chris@0 594
Chris@0 595 /**
Chris@0 596 * Builds the default count query for SearchQuery.
Chris@0 597 *
Chris@0 598 * Since SearchQuery always uses GROUP BY, we can default to a subquery. We
Chris@0 599 * also add the same conditions as execute() because countQuery() is called
Chris@0 600 * first.
Chris@0 601 */
Chris@0 602 public function countQuery() {
Chris@0 603 if (!$this->executedPrepare) {
Chris@0 604 $this->prepareAndNormalize();
Chris@0 605 }
Chris@0 606
Chris@0 607 // Clone the inner query.
Chris@0 608 $inner = clone $this->query;
Chris@0 609
Chris@0 610 // Add conditions to query.
Chris@0 611 $inner->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
Chris@0 612 if (count($this->conditions)) {
Chris@0 613 $inner->condition($this->conditions);
Chris@0 614 }
Chris@0 615
Chris@0 616 // Remove existing fields and expressions, they are not needed for a count
Chris@0 617 // query.
Chris@0 618 $fields =& $inner->getFields();
Chris@0 619 $fields = [];
Chris@0 620 $expressions =& $inner->getExpressions();
Chris@0 621 $expressions = [];
Chris@0 622
Chris@0 623 // Add sid as the only field and count them as a subquery.
Chris@18 624 $count = $this->connection->select($inner->fields('i', ['sid']), NULL);
Chris@0 625
Chris@0 626 // Add the COUNT() expression.
Chris@0 627 $count->addExpression('COUNT(*)');
Chris@0 628
Chris@0 629 return $count;
Chris@0 630 }
Chris@0 631
Chris@0 632 /**
Chris@0 633 * Returns the query status bitmap.
Chris@0 634 *
Chris@0 635 * @return int
Chris@0 636 * A bitmap indicating query status. Zero indicates there were no problems.
Chris@0 637 * A non-zero value is a combination of one or more of the following flags:
Chris@0 638 * - SearchQuery::NO_POSITIVE_KEYWORDS
Chris@0 639 * - SearchQuery::EXPRESSIONS_IGNORED
Chris@0 640 * - SearchQuery::LOWER_CASE_OR
Chris@0 641 * - SearchQuery::NO_KEYWORD_MATCHES
Chris@0 642 */
Chris@0 643 public function getStatus() {
Chris@0 644 return $this->status;
Chris@0 645 }
Chris@0 646
Chris@0 647 }