Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
66.17% |
178 / 269 |
|
50.00% |
8 / 16 |
CRAP | |
0.00% |
0 / 1 |
FullTextQueryStringQueryBuilder | |
66.17% |
178 / 269 |
|
50.00% |
8 / 16 |
199.37 | |
0.00% |
0 / 1 |
__construct | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 | |||
build | |
69.67% |
85 / 122 |
|
0.00% |
0 / 1 |
31.16 | |||
isPathologicalWildcard | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
6 | |||
buildDegraded | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
6 | |||
buildSearchTextQuery | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
2 | |||
buildQueryString | |
90.91% |
10 / 11 |
|
0.00% |
0 / 1 |
2.00 | |||
getMultiTermRewriteMethod | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
switchSearchToExactForWildcards | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
6 | |||
switchSearchToExact | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
buildFullTextSearchFields | |
83.87% |
26 / 31 |
|
0.00% |
0 / 1 |
9.34 | |||
replaceAllPartsOfQuery | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 | |||
replacePartsOfQuery | |
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
5 | |||
buildHighlightQuery | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
buildPhraseRescoreQuery | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 | |||
isPhraseRescoreNeeded | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
5 | |||
maybeWrapWithTokenCountRouter | |
10.00% |
2 / 20 |
|
0.00% |
0 / 1 |
9.56 |
1 | <?php |
2 | |
3 | namespace CirrusSearch\Query; |
4 | |
5 | use CirrusSearch\Extra\Query\TokenCountRouter; |
6 | use CirrusSearch\Search\SearchContext; |
7 | use CirrusSearch\SearchConfig; |
8 | use Elastica\Query\MatchAll; |
9 | use MediaWiki\Logger\LoggerFactory; |
10 | |
11 | /** |
12 | * Builds an Elastica query backed by an elasticsearch QueryString query |
13 | * Has many warts and edge cases that are hardly desirable. |
14 | */ |
15 | class FullTextQueryStringQueryBuilder implements FullTextQueryBuilder { |
16 | /** |
17 | * @var SearchConfig |
18 | */ |
19 | protected $config; |
20 | |
21 | /** |
22 | * @var KeywordFeature[] |
23 | */ |
24 | private $features; |
25 | |
26 | /** |
27 | * @var string |
28 | */ |
29 | private $queryStringQueryString = ''; |
30 | |
31 | /** |
32 | * @var bool |
33 | */ |
34 | private $useTokenCountRouter; |
35 | |
36 | /** |
37 | * @param SearchConfig $config |
38 | * @param KeywordFeature[] $features |
39 | * @param array[] $settings currently ignored |
40 | */ |
41 | public function __construct( SearchConfig $config, array $features, array $settings = [] ) { |
42 | $this->config = $config; |
43 | $this->features = $features; |
44 | $this->useTokenCountRouter = $this->config->getElement( |
45 | 'CirrusSearchWikimediaExtraPlugin', 'token_count_router' ) === true; |
46 | } |
47 | |
48 | /** |
49 | * Search articles with provided term. |
50 | * |
51 | * @param SearchContext $searchContext |
52 | * @param string $term term to search |
53 | * searches that might be better? |
54 | */ |
55 | public function build( SearchContext $searchContext, $term ) { |
56 | $searchContext->addSyntaxUsed( 'full_text' ); |
57 | // Transform Mediawiki specific syntax to filters and extra |
58 | // (pre-escaped) query string |
59 | foreach ( $this->features as $feature ) { |
60 | $term = $feature->apply( $searchContext, $term ); |
61 | } |
62 | |
63 | if ( !$searchContext->areResultsPossible() ) { |
64 | return; |
65 | } |
66 | |
67 | $term = $searchContext->escaper()->escapeQuotes( $term ); |
68 | $term = trim( $term ); |
69 | |
70 | // Match quoted phrases including those containing escaped quotes. |
71 | // Those phrases can optionally be followed by ~ then a number (this is |
72 | // the phrase slop). That can optionally be followed by a ~ (this |
73 | // matches stemmed words in phrases). The following all match: |
74 | // "a", "a boat", "a\"boat", "a boat"~, "a boat"~9, |
75 | // "a boat"~9~, -"a boat", -"a boat"~9~ |
76 | $slop = $this->config->get( 'CirrusSearchPhraseSlop' ); |
77 | $matchQuotesRegex = '(?<![\]])(?<negate>-|!)?(?<main>"((?:[^"]|(?<=\\\)")+)"(?<slop>~\d+)?)(?<fuzzy>~)?'; |
78 | $query = self::replacePartsOfQuery( |
79 | $term, |
80 | "/$matchQuotesRegex/", |
81 | function ( $matches ) use ( $searchContext, $slop ) { |
82 | $negate = $matches[ 'negate' ][ 0 ] ? 'NOT ' : ''; |
83 | $main = $searchContext->escaper()->fixupQueryStringPart( $matches[ 'main' ][ 0 ] ); |
84 | |
85 | if ( !$negate && !isset( $matches[ 'fuzzy' ] ) && !isset( $matches[ 'slop' ] ) && |
86 | preg_match( '/^"([^"*]+)[*]"/', $main, $matches ) |
87 | ) { |
88 | $phraseMatch = new \Elastica\Query\MatchPhrasePrefix(); |
89 | $phraseMatch->setFieldQuery( "all.plain", $matches[1] ); |
90 | $searchContext->addNonTextQuery( $phraseMatch ); |
91 | $searchContext->addSyntaxUsed( 'phrase_match_prefix' ); |
92 | |
93 | $phraseHighlightMatch = new \Elastica\Query\QueryString(); |
94 | $phraseHighlightMatch->setQuery( $matches[1] . '*' ); |
95 | $phraseHighlightMatch->setFields( [ 'all.plain' ] ); |
96 | $searchContext->addNonTextHighlightQuery( $phraseHighlightMatch ); |
97 | |
98 | return []; |
99 | } |
100 | |
101 | if ( !isset( $matches[ 'fuzzy' ] ) ) { |
102 | if ( !isset( $matches[ 'slop' ] ) ) { |
103 | $main .= '~' . $slop[ 'precise' ]; |
104 | } |
105 | // Got to collect phrases that don't use the all field so we can highlight them. |
106 | // The highlighter locks phrases to the fields that specify them. It doesn't do |
107 | // that with terms. |
108 | return [ |
109 | 'escaped' => $negate . self::switchSearchToExact( $searchContext, $main, true ), |
110 | 'nonAll' => $negate . self::switchSearchToExact( $searchContext, $main, false ), |
111 | ]; |
112 | } |
113 | return [ 'escaped' => $negate . $main ]; |
114 | } ); |
115 | // Find prefix matches and force them to only match against the plain analyzed fields. This |
116 | // prevents prefix matches from getting confused by stemming. Users really don't expect stemming |
117 | // in prefix queries. |
118 | $maxWildcards = $this->config->get( 'CirrusSearchQueryStringMaxWildcards' ); |
119 | $query = self::replaceAllPartsOfQuery( $query, '/\w+\*(?:\w*\*?)*/u', |
120 | function ( $matches ) use ( $searchContext, $maxWildcards ) { |
121 | // hack to detect pathological wildcard |
122 | // relates to T102589 but elastic7 seems to have broken our fix by stopping |
123 | // to propagate the max_determinized_states param to the wildcard queries |
124 | // We might consider fixing this upstream again when switch to opensearch. |
125 | // In the meantine simply count the number of wildcard chars and mimic the previous |
126 | // if we detect such problematic queries |
127 | if ( self::isPathologicalWildcard( $matches[ 0 ][ 0 ], $maxWildcards ) ) { |
128 | $searchContext->addWarning( 'cirrussearch-regex-too-complex-error' ); |
129 | $searchContext->setResultsPossible( false ); |
130 | } |
131 | $term = $searchContext->escaper()->fixupQueryStringPart( $matches[ 0 ][ 0 ] ); |
132 | return [ |
133 | 'escaped' => self::switchSearchToExactForWildcards( $searchContext, $term ), |
134 | 'nonAll' => self::switchSearchToExactForWildcards( $searchContext, $term ) |
135 | ]; |
136 | } ); |
137 | |
138 | $escapedQuery = []; |
139 | $nonAllQuery = []; |
140 | $nearMatchQuery = []; |
141 | foreach ( $query as $queryPart ) { |
142 | if ( isset( $queryPart[ 'escaped' ] ) ) { |
143 | $escapedQuery[] = $queryPart[ 'escaped' ]; |
144 | $nonAllQuery[] = $queryPart['nonAll'] ?? $queryPart['escaped']; |
145 | continue; |
146 | } |
147 | if ( isset( $queryPart[ 'raw' ] ) ) { |
148 | $fixed = $searchContext->escaper()->fixupQueryStringPart( $queryPart[ 'raw' ] ); |
149 | $escapedQuery[] = $fixed; |
150 | $nonAllQuery[] = $fixed; |
151 | $nearMatchQuery[] = $queryPart[ 'raw' ]; |
152 | continue; |
153 | } |
154 | LoggerFactory::getInstance( 'CirrusSearch' )->warning( |
155 | 'Unknown query part: {queryPart}', |
156 | [ 'queryPart' => serialize( $queryPart ) ] |
157 | ); |
158 | } |
159 | |
160 | // Actual text query |
161 | $this->queryStringQueryString = |
162 | $searchContext->escaper()->fixupWholeQueryString( implode( ' ', $escapedQuery ) ); |
163 | $searchContext->setCleanedSearchTerm( $this->queryStringQueryString ); |
164 | |
165 | if ( $this->queryStringQueryString === '' ) { |
166 | $searchContext->addSyntaxUsed( 'filter_only' ); |
167 | $searchContext->setHighlightQuery( new MatchAll() ); |
168 | return; |
169 | } |
170 | |
171 | // Note that no escaping is required for near_match's match query. |
172 | $nearMatchQuery = implode( ' ', $nearMatchQuery ); |
173 | // If the near match is made only of spaces disable it. |
174 | if ( preg_match( '/^\s+$/', $nearMatchQuery ) === 1 ) { |
175 | $nearMatchQuery = ''; |
176 | } |
177 | |
178 | $queryStringRegex = |
179 | '(' . |
180 | // quoted strings |
181 | $matchQuotesRegex . |
182 | ')|(' . |
183 | // patterns that are seen before tokens. |
184 | '(^|\s)[+!-]\S' . |
185 | ')|(' . |
186 | // patterns seen after tokens. |
187 | '\S(?<!\\\\)~[0-9]?(\s|$)' . |
188 | ')|(' . |
189 | // patterns that are separated from tokens by whitespace |
190 | // on both sides. |
191 | '\s(AND|OR|NOT|&&|\\|\\|)\s' . |
192 | ')|(' . |
193 | // patterns that can be at the start of the string |
194 | '^NOT\s' . |
195 | ')|(' . |
196 | // patterns that can be inside tokens |
197 | // Note that question mark stripping has already been applied |
198 | '(?<!\\\\)[?*]' . |
199 | ')'; |
200 | if ( preg_match( "/$queryStringRegex/", $this->queryStringQueryString ) ) { |
201 | $searchContext->addSyntaxUsed( 'query_string' ); |
202 | } |
203 | $fields = array_merge( |
204 | self::buildFullTextSearchFields( $searchContext, 1, '.plain', true ), |
205 | self::buildFullTextSearchFields( $searchContext, |
206 | $this->config->get( 'CirrusSearchStemmedWeight' ), '', true ) ); |
207 | $nearMatchFields = self::buildFullTextSearchFields( $searchContext, |
208 | $this->config->get( 'CirrusSearchNearMatchWeight' ), '.near_match', true ); |
209 | $nearMatchFields = array_merge( $nearMatchFields, self::buildFullTextSearchFields( $searchContext, |
210 | $this->config->get( 'CirrusSearchNearMatchWeight' ) * 0.75, '.near_match_asciifolding', true ) ); |
211 | $searchContext->setMainQuery( $this->buildSearchTextQuery( $searchContext, $fields, $nearMatchFields, |
212 | $this->queryStringQueryString, $nearMatchQuery ) ); |
213 | |
214 | // The highlighter doesn't know about the weighting from the all fields so we have to send |
215 | // it a query without the all fields. This swaps one in. |
216 | if ( $this->config->getElement( 'CirrusSearchAllFields', 'use' ) ) { |
217 | $nonAllFields = array_merge( |
218 | self::buildFullTextSearchFields( $searchContext, 1, '.plain', false ), |
219 | self::buildFullTextSearchFields( $searchContext, |
220 | $this->config->get( 'CirrusSearchStemmedWeight' ), '', false ) ); |
221 | $nonAllQueryString = $searchContext->escaper() |
222 | ->fixupWholeQueryString( implode( ' ', $nonAllQuery ) ); |
223 | $searchContext->setHighlightQuery( |
224 | $this->buildHighlightQuery( $searchContext, $nonAllFields, $nonAllQueryString, 1 ) |
225 | ); |
226 | } else { |
227 | $nonAllFields = $fields; |
228 | } |
229 | |
230 | if ( $this->isPhraseRescoreNeeded( $searchContext ) ) { |
231 | $rescoreFields = $fields; |
232 | if ( !$this->config->getElement( 'CirrusSearchAllFields', 'use' ) ) { |
233 | $rescoreFields = $nonAllFields; |
234 | } |
235 | |
236 | $searchContext->setPhraseRescoreQuery( $this->buildPhraseRescoreQuery( |
237 | $searchContext, |
238 | $rescoreFields, |
239 | $this->queryStringQueryString, |
240 | $this->config->getElement( 'CirrusSearchPhraseSlop', 'boost' ) |
241 | ) ); |
242 | } |
243 | } |
244 | |
245 | private function isPathologicalWildcard( string $term, int $maxWildcard ): bool { |
246 | $ret = preg_match_all( "/[*?]+/", $term ); |
247 | if ( $ret === false ) { |
248 | // we failed the regex, out of caution fail the query |
249 | return true; |
250 | } |
251 | return $ret > $maxWildcard; |
252 | } |
253 | |
254 | /** |
255 | * Attempt to build a degraded query from the query already built into $context. Must be |
256 | * called *after* self::build(). |
257 | * |
258 | * @param SearchContext $searchContext |
259 | * @return bool True if a degraded query was built |
260 | */ |
261 | public function buildDegraded( SearchContext $searchContext ) { |
262 | if ( $this->queryStringQueryString === '' ) { |
263 | return false; |
264 | } |
265 | |
266 | $fields = array_merge( |
267 | self::buildFullTextSearchFields( $searchContext, 1, '.plain', true ), |
268 | self::buildFullTextSearchFields( $searchContext, |
269 | $this->config->get( 'CirrusSearchStemmedWeight' ), '', true ) |
270 | ); |
271 | |
272 | $searchContext->addSyntaxUsed( 'degraded_full_text' ); |
273 | $simpleQuery = new \Elastica\Query\Simple( [ 'simple_query_string' => [ |
274 | 'fields' => $fields, |
275 | 'query' => $this->queryStringQueryString, |
276 | 'default_operator' => 'AND', |
277 | // Disable all costly operators |
278 | 'flags' => 'OR|AND' |
279 | ] ] ); |
280 | $searchContext->setMainQuery( $simpleQuery ); |
281 | $searchContext->setHighlightQuery( $simpleQuery ); |
282 | |
283 | return true; |
284 | } |
285 | |
286 | /** |
287 | * Build the primary query used for full text search. This will be a |
288 | * QueryString query, and optionally a MultiMatch if a $nearMatchQuery |
289 | * is provided. |
290 | * |
291 | * @param SearchContext $searchContext |
292 | * @param string[] $fields |
293 | * @param string[] $nearMatchFields |
294 | * @param string $queryString |
295 | * @param string $nearMatchQuery |
296 | * @return \Elastica\Query\AbstractQuery |
297 | */ |
298 | protected function buildSearchTextQuery( |
299 | SearchContext $searchContext, |
300 | array $fields, |
301 | array $nearMatchFields, |
302 | $queryString, |
303 | $nearMatchQuery |
304 | ) { |
305 | $slop = $this->config->getElement( 'CirrusSearchPhraseSlop', 'default' ); |
306 | $queryForMostFields = $this->buildQueryString( $fields, $queryString, $slop ); |
307 | $searchContext->addSyntaxUsed( 'full_text_querystring', 5 ); |
308 | if ( !$nearMatchQuery ) { |
309 | return $queryForMostFields; |
310 | } |
311 | |
312 | // Build one query for the full text fields and one for the near match fields so that |
313 | // the near match can run unescaped. |
314 | $bool = new \Elastica\Query\BoolQuery(); |
315 | $bool->setMinimumShouldMatch( 1 ); |
316 | $bool->addShould( $queryForMostFields ); |
317 | $nearMatch = new \Elastica\Query\MultiMatch(); |
318 | $nearMatch->setFields( $nearMatchFields ); |
319 | $nearMatch->setQuery( $nearMatchQuery ); |
320 | $bool->addShould( $nearMatch ); |
321 | |
322 | return $bool; |
323 | } |
324 | |
325 | /** |
326 | * Builds the query using the QueryString, this is the default builder |
327 | * used by cirrus and uses a default AND between clause. |
328 | * The query 'the query' and the fields all and all.plain will be like |
329 | * (all:the OR all.plain:the) AND (all:query OR all.plain:query) |
330 | * |
331 | * @param string[] $fields |
332 | * @param string $queryString |
333 | * @param int $phraseSlop |
334 | * @return \Elastica\Query\QueryString |
335 | */ |
336 | private function buildQueryString( array $fields, $queryString, $phraseSlop ) { |
337 | $query = new \Elastica\Query\QueryString( $queryString ); |
338 | $query->setFields( $fields ); |
339 | $query->setPhraseSlop( $phraseSlop ); |
340 | $query->setDefaultOperator( 'AND' ); |
341 | $query->setAllowLeadingWildcard( (bool)$this->config->get( 'CirrusSearchAllowLeadingWildcard' ) ); |
342 | $query->setFuzzyPrefixLength( 2 ); |
343 | $query->setRewrite( $this->getMultiTermRewriteMethod() ); |
344 | $states = $this->config->get( 'CirrusSearchQueryStringMaxDeterminizedStates' ); |
345 | if ( isset( $states ) ) { |
346 | $query->setParam( 'max_determinized_states', $states ); |
347 | } |
348 | return $query; |
349 | } |
350 | |
351 | /** |
352 | * the rewrite method to use for multi term queries |
353 | * @return string |
354 | */ |
355 | protected function getMultiTermRewriteMethod() { |
356 | return 'top_terms_boost_1024'; |
357 | } |
358 | |
359 | /** |
360 | * Expand wildcard queries to the all.plain and title.plain fields if |
361 | * wgCirrusSearchAllFields[ 'use' ] is set to true. Fallback to all |
362 | * the possible fields otherwise. This prevents applying and compiling |
363 | * costly wildcard queries too many times. |
364 | * |
365 | * @param SearchContext $context |
366 | * @param string $term |
367 | * @return string |
368 | */ |
369 | private static function switchSearchToExactForWildcards( SearchContext $context, $term ) { |
370 | // Try to limit the expansion of wildcards to all the subfields |
371 | // We still need to add title.plain with a high boost otherwise |
372 | // match in titles be poorly scored (actually it breaks some tests). |
373 | if ( $context->getConfig()->getElement( 'CirrusSearchAllFields', 'use' ) ) { |
374 | $titleWeight = $context->getConfig()->getElement( 'CirrusSearchWeights', 'title' ); |
375 | $fields = []; |
376 | $fields[] = "title.plain:$term^{$titleWeight}"; |
377 | $fields[] = "all.plain:$term"; |
378 | $exact = implode( ' OR ', $fields ); |
379 | return "($exact)"; |
380 | } else { |
381 | return self::switchSearchToExact( $context, $term, false ); |
382 | } |
383 | } |
384 | |
385 | /** |
386 | * Build a QueryString query where all fields being searched are |
387 | * queried for $term, joined with an OR. This is primarily for the |
388 | * benefit of the highlighter, the primary search is typically against |
389 | * the special all field. |
390 | * |
391 | * @param SearchContext $context |
392 | * @param string $term |
393 | * @param bool $allFieldAllowed |
394 | * @return string |
395 | */ |
396 | private static function switchSearchToExact( SearchContext $context, $term, $allFieldAllowed ) { |
397 | $exact = implode( ' OR ', |
398 | self::buildFullTextSearchFields( $context, 1, ".plain:$term", $allFieldAllowed ) ); |
399 | return "($exact)"; |
400 | } |
401 | |
402 | /** |
403 | * Build fields searched by full text search. |
404 | * |
405 | * @param SearchContext $context |
406 | * @param float $weight weight to multiply by all fields |
407 | * @param string $fieldSuffix suffix to add to field names |
408 | * @param bool $allFieldAllowed can we use the all field? False for |
409 | * collecting phrases for the highlighter. |
410 | * @return string[] array of fields to query |
411 | */ |
412 | private static function buildFullTextSearchFields( |
413 | SearchContext $context, |
414 | $weight, |
415 | $fieldSuffix, |
416 | $allFieldAllowed |
417 | ) { |
418 | $searchWeights = $context->getConfig()->get( 'CirrusSearchWeights' ); |
419 | |
420 | if ( $allFieldAllowed && $context->getConfig()->getElement( 'CirrusSearchAllFields', 'use' ) ) { |
421 | if ( $fieldSuffix === '.near_match' ) { |
422 | // The near match fields can't shard a root field because field fields need it - |
423 | // thus no suffix all. |
424 | return [ "all_near_match^{$weight}" ]; |
425 | } |
426 | if ( $fieldSuffix === '.near_match_asciifolding' ) { |
427 | // The near match fields can't shard a root field because field fields need it - |
428 | // thus no suffix all. |
429 | return [ "all_near_match.asciifolding^{$weight}" ]; |
430 | } |
431 | return [ "all{$fieldSuffix}^{$weight}" ]; |
432 | } |
433 | |
434 | $fields = []; |
435 | // Only title and redirect support near_match so skip it for everything else |
436 | $titleWeight = $weight * $searchWeights[ 'title' ]; |
437 | $redirectWeight = $weight * $searchWeights[ 'redirect' ]; |
438 | if ( $fieldSuffix === '.near_match' || $fieldSuffix === '.near_match_asciifolding' ) { |
439 | $fields[] = "title{$fieldSuffix}^{$titleWeight}"; |
440 | $fields[] = "redirect.title{$fieldSuffix}^{$redirectWeight}"; |
441 | return $fields; |
442 | } |
443 | $fields[] = "title{$fieldSuffix}^{$titleWeight}"; |
444 | $fields[] = "redirect.title{$fieldSuffix}^{$redirectWeight}"; |
445 | $categoryWeight = $weight * $searchWeights[ 'category' ]; |
446 | $headingWeight = $weight * $searchWeights[ 'heading' ]; |
447 | $openingTextWeight = $weight * $searchWeights[ 'opening_text' ]; |
448 | $textWeight = $weight * $searchWeights[ 'text' ]; |
449 | $auxiliaryTextWeight = $weight * $searchWeights[ 'auxiliary_text' ]; |
450 | $fields[] = "category{$fieldSuffix}^{$categoryWeight}"; |
451 | $fields[] = "heading{$fieldSuffix}^{$headingWeight}"; |
452 | $fields[] = "opening_text{$fieldSuffix}^{$openingTextWeight}"; |
453 | $fields[] = "text{$fieldSuffix}^{$textWeight}"; |
454 | $fields[] = "auxiliary_text{$fieldSuffix}^{$auxiliaryTextWeight}"; |
455 | $namespaces = $context->getNamespaces(); |
456 | if ( !$namespaces || in_array( NS_FILE, $namespaces ) ) { |
457 | $fileTextWeight = $weight * $searchWeights[ 'file_text' ]; |
458 | $fields[] = "file_text{$fieldSuffix}^{$fileTextWeight}"; |
459 | } |
460 | return $fields; |
461 | } |
462 | |
463 | /** |
464 | * Walks through an array of query pieces, as built by |
465 | * self::replacePartsOfQuery, and replaecs all raw pieces by the result of |
466 | * self::replacePartsOfQuery when called with the provided regex and |
467 | * callable. One query piece may turn into one or more query pieces in the |
468 | * result. |
469 | * |
470 | * @param array[] $query The set of query pieces to apply against |
471 | * @param string $regex Pieces of $queryPart that match this regex will |
472 | * be provided to $callable |
473 | * @param callable $callable A function accepting the $matches from preg_match |
474 | * and returning either a raw or escaped query piece. |
475 | * @return array[] The set of query pieces after applying regex and callable |
476 | */ |
477 | private static function replaceAllPartsOfQuery( array $query, $regex, $callable ) { |
478 | $result = []; |
479 | foreach ( $query as $queryPart ) { |
480 | if ( isset( $queryPart[ 'raw' ] ) ) { |
481 | $result = array_merge( $result, |
482 | self::replacePartsOfQuery( $queryPart[ 'raw' ], $regex, $callable ) ); |
483 | } else { |
484 | $result[] = $queryPart; |
485 | } |
486 | } |
487 | return $result; |
488 | } |
489 | |
490 | /** |
491 | * Splits a query string into one or more sequential pieces. Each piece |
492 | * of the query can either be raw (['raw'=>'stuff']), or escaped |
493 | * (['escaped'=>'stuff']). escaped can also optionally include a nonAll |
494 | * query (['escaped'=>'stuff','nonAll'=>'stuff']). If nonAll is not set |
495 | * the escaped query will be used. |
496 | * |
497 | * Pieces of $queryPart that do not match the provided $regex are tagged |
498 | * as 'raw' and may see further parsing. $callable receives pieces of |
499 | * the string that match the regex and must return either a raw or escaped |
500 | * query piece. |
501 | * |
502 | * @param string $queryPart Raw piece of a user supplied query string |
503 | * @param string $regex Pieces of $queryPart that match this regex will |
504 | * be provided to $callable |
505 | * @param callable $callable A function accepting the $matches from preg_match |
506 | * and returning either a raw or escaped query piece. |
507 | * @return array[] The sequential set of quer ypieces $queryPart was |
508 | * converted into. |
509 | */ |
510 | private static function replacePartsOfQuery( $queryPart, $regex, $callable ) { |
511 | $destination = []; |
512 | $matches = []; |
513 | $offset = 0; |
514 | while ( preg_match( $regex, $queryPart, $matches, PREG_OFFSET_CAPTURE, $offset ) ) { |
515 | $startOffset = $matches[0][1]; |
516 | if ( $startOffset > $offset ) { |
517 | $destination[] = [ |
518 | 'raw' => substr( $queryPart, $offset, $startOffset - $offset ) |
519 | ]; |
520 | } |
521 | |
522 | $callableResult = call_user_func( $callable, $matches ); |
523 | if ( $callableResult ) { |
524 | $destination[] = $callableResult; |
525 | } |
526 | |
527 | $offset = $startOffset + strlen( $matches[0][0] ); |
528 | } |
529 | |
530 | if ( $offset < strlen( $queryPart ) ) { |
531 | $destination[] = [ |
532 | 'raw' => substr( $queryPart, $offset ), |
533 | ]; |
534 | } |
535 | |
536 | return $destination; |
537 | } |
538 | |
539 | /** |
540 | * Builds the highlight query |
541 | * @param SearchContext $context |
542 | * @param string[] $fields |
543 | * @param string $queryText |
544 | * @param int $slop |
545 | * @return \Elastica\Query\AbstractQuery |
546 | */ |
547 | protected function buildHighlightQuery( SearchContext $context, array $fields, $queryText, $slop ) { |
548 | return $this->buildQueryString( $fields, $queryText, $slop ); |
549 | } |
550 | |
551 | /** |
552 | * Builds the phrase rescore query |
553 | * @param SearchContext $context |
554 | * @param string[] $fields |
555 | * @param string $queryText |
556 | * @param int $slop |
557 | * @return \Elastica\Query\AbstractQuery |
558 | */ |
559 | protected function buildPhraseRescoreQuery( SearchContext $context, array $fields, $queryText, $slop ) { |
560 | return $this->maybeWrapWithTokenCountRouter( |
561 | $queryText, |
562 | $this->buildQueryString( $fields, '"' . $queryText . '"', $slop ) |
563 | ); |
564 | } |
565 | |
566 | /** |
567 | * Determines if a phrase rescore is needed |
568 | * @param SearchContext $searchContext |
569 | * @return bool true if we can a phrase rescore |
570 | */ |
571 | protected function isPhraseRescoreNeeded( SearchContext $searchContext ) { |
572 | // Only do a phrase match rescore if the query doesn't include |
573 | // any quotes and has a space or the token count router is |
574 | // active. |
575 | // Queries without spaces are either single term or have a |
576 | // phrase query generated. |
577 | // Queries with the quote already contain a phrase query and we |
578 | // can't build phrase queries out of phrase queries at this |
579 | // point. |
580 | if ( !$searchContext->isSpecialKeywordUsed() && |