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