/
Searcher.php
1652 lines (1522 loc) 路 58 KB
/
Searcher.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace CirrusSearch;
use Elastica;
use CirrusSearch;
use CirrusSearch\Extra\Filter\SourceRegex;
use CirrusSearch\Search\Escaper;
use CirrusSearch\Search\Filters;
use CirrusSearch\Search\FullTextResultsType;
use CirrusSearch\Search\ResultsType;
use CirrusSearch\Search\RescoreBuilder;
use CirrusSearch\Search\SearchContext;
use ConfigFactory;
use Language;
use MediaWiki\Logger\LoggerFactory;
use MWNamespace;
use ObjectCache;
use SearchResultSet;
use Status;
use Title;
use UsageException;
use RequestContext;
use User;
/**
* Performs searches using Elasticsearch. Note that each instance of this class
* is single use only.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
class Searcher extends ElasticsearchIntermediary {
const SUGGESTION_HIGHLIGHT_PRE = '<em>';
const SUGGESTION_HIGHLIGHT_POST = '</em>';
const HIGHLIGHT_PRE = '<span class="searchmatch">';
const HIGHLIGHT_POST = '</span>';
const HIGHLIGHT_REGEX = '/<span class="searchmatch">.*?<\/span>/';
const MORE_LIKE_THESE_NONE = 0;
const MORE_LIKE_THESE_ONLY_WIKIBASE = 1;
/**
* Maximum title length that we'll check in prefix and keyword searches.
* Since titles can be 255 bytes in length we're setting this to 255
* characters.
*/
const MAX_TITLE_SEARCH = 255;
/**
* Maximum length, in characters, allowed in queries sent to searchText.
*/
const MAX_TEXT_SEARCH = 300;
/**
* Maximum offset depth allowed. Too deep will cause very slow queries.
* 100,000 feels plenty deep.
*/
const MAX_OFFSET = 100000;
/**
* @var integer search offset
*/
private $offset;
/**
* @var integer maximum number of result
*/
private $limit;
/**
* @var Language language of the wiki
*/
private $language;
/**
* @var ResultsType|null type of results. null defaults to FullTextResultsType
*/
private $resultsType;
/**
* @var string sort type
*/
private $sort = 'relevance';
/**
* @var string[] array of prefixes that should be prepended to suggestions. Can be added to externally and is added to
* during search syntax parsing.
*/
private $suggestPrefixes = array();
/**
* @var string[] array of suffixes that should be prepended to suggestions. Can be added to externally and is added to
* during search syntax parsing.
*/
private $suggestSuffixes = array();
// These fields are filled in by the particule search methods
/**
* @var string term to search.
*/
private $term;
/**
* @var \Elastica\Query\AbstractQuery|null main query. null defaults to \Elastica\Query\MatchAll
*/
private $query = null;
/**
* @var \Elastica\Filter\AbstractFilter[] filters that MUST hold true of all results
*/
private $filters = array();
/**
* @var \Elastica\Filter\AbstractFilter[] filters that MUST NOT hold true of all results
*/
private $notFilters = array();
private $suggest = null;
/**
* @var array[] of rescore configurations as used by elasticsearch. The query needs to be an Elastica query.
*/
private $rescore = array();
/**
* @var string index base name to use
*/
private $indexBaseName;
/**
* @var boolean is this a fuzzy query?
*/
private $fuzzyQuery = false;
/**
* @var null|\Elastica\Query\AbstractQuery query that should be used for highlighting if different from the
* query used for selecting.
*/
private $highlightQuery = null;
/**
* @var array[] configuration for highlighting the article source. Empty if source is ignored.
*/
private $highlightSource = array();
/**
* @var Escaper escapes queries
*/
private $escaper;
/**
* @var boolean limit the search to the local wiki. Defaults to false.
*/
private $limitSearchToLocalWiki = false;
/**
* @var boolean just return the array that makes up the query instead of searching
*/
private $returnQuery = false;
/**
* @var boolean return raw Elasticsearch result instead of processing it
*/
private $returnResult = false;
/**
* @var boolean return explanation with results
*/
private $returnExplain = false;
/**
* @var \Elastica\Query\Match[] queries that don't use Elastic's "query string" query, for more
* advanced searching (e.g. match_phrase_prefix for regular quoted strings).
*/
private $nonTextQueries = array();
/**
* @var \Elastica\Query\QueryString[] queries that don't use Elastic's "query string" query, for more
* advanced highlighting (e.g. match_phrase_prefix for regular quoted strings).
*/
private $nonTextHighlightQueries = array();
/**
* Search environment configuration
* @var SearchConfig
*/
private $config;
/**
* @var SearchContext
*/
private $searchContext;
/**
* Constructor
* @param Connection $conn
* @param int $offset Offset the results by this much
* @param int $limit Limit the results to this many
* @param SearchConfig|null $config Configuration settings
* @param int[]|null $namespaces Array of namespace numbers to search or null to search all namespaces.
* @param User|null $user user for which this search is being performed. Attached to slow request logs.
* @param string|boolean $index Base name for index to search from, defaults to wfWikiId()
*/
public function __construct( Connection $conn, $offset, $limit, SearchConfig $config = null, array $namespaces = null,
User $user = null, $index = false ) {
if ( is_null( $config ) ) {
// @todo connection has an embeded config ... reuse that? somehow should
// at least ensure they are the same.
$config = ConfigFactory::getDefaultInstance()->makeConfig( 'CirrusSearch' );
}
parent::__construct( $conn, $user, $config->get( 'CirrusSearchSlowSearch' ) );
$this->config = $config;
$this->offset = min( $offset, self::MAX_OFFSET );
$this->limit = $limit;
$this->indexBaseName = $index ?: $config->getWikiId();
$this->language = $config->get( 'ContLang' );
$this->escaper = new Escaper( $config->get( 'LanguageCode' ), $config->get( 'CirrusSearchAllowLeadingWildcard' ) );
$this->searchContext = new SearchContext( $this->config, $namespaces );
}
/**
* @param ResultsType $resultsType results type to return
*/
public function setResultsType( $resultsType ) {
$this->resultsType = $resultsType;
}
/**
* @param boolean $returnQuery just return the array that makes up the query instead of searching
*/
public function setReturnQuery( $returnQuery ) {
$this->returnQuery = $returnQuery;
}
/**
* @param boolean $dumpResult return raw Elasticsearch result instead of processing it
*/
public function setDumpResult( $dumpResult ) {
$this->returnResult = $dumpResult;
}
/**
* @param boolean $returnExplain return query explanation
*/
public function setReturnExplain( $returnExplain ) {
$this->returnExplain = $returnExplain;
}
/**
* Set the type of sort to perform. Must be 'relevance', 'title_asc', 'title_desc'.
* @param string $sort sort type
*/
public function setSort( $sort ) {
$this->sort = $sort;
}
/**
* Should this search limit results to the local wiki? If not called the default is false.
* @param boolean $limitSearchToLocalWiki should the results be limited?
*/
public function limitSearchToLocalWiki( $limitSearchToLocalWiki ) {
$this->limitSearchToLocalWiki = $limitSearchToLocalWiki;
}
/**
* Perform a "near match" title search which is pretty much a prefix match without the prefixes.
* @param string $search text by which to search
* @return Status status containing results defined by resultsType on success
*/
public function nearMatchTitleSearch( $search ) {
$this->checkTitleSearchRequestLength( $search );
// Elasticsearch seems to have trouble extracting the proper terms to highlight
// from the default query we make so we feed it exactly the right query to highlight.
$this->highlightQuery = new \Elastica\Query\MultiMatch();
$this->highlightQuery->setQuery( $search );
$this->highlightQuery->setFields( array(
'title.near_match', 'redirect.title.near_match',
'title.near_match_asciifolding', 'redirect.title.near_match_asciifolding',
) );
if ( $this->config->getElement( 'CirrusSearchAllFields', 'use' ) ) {
// Instead of using the highlight query we need to make one like it that uses the all_near_match field.
$allQuery = new \Elastica\Query\MultiMatch();
$allQuery->setQuery( $search );
$allQuery->setFields( array( 'all_near_match', 'all_near_match.asciifolding' ) );
$this->filters[] = new \Elastica\Filter\Query( $allQuery );
} else {
$this->filters[] = new \Elastica\Filter\Query( $this->highlightQuery );
}
return $this->search( 'near_match', $search );
}
/**
* Perform a prefix search.
* @param string $search text by which to search
* @return Status status containing results defined by resultsType on success
*/
public function prefixSearch( $search ) {
$this->checkTitleSearchRequestLength( $search );
if ( $search ) {
if ( $this->config->get( 'CirrusSearchPrefixSearchStartsWithAnyWord' ) ) {
$match = new \Elastica\Query\Match();
$match->setField( 'title.word_prefix', array(
'query' => $search,
'analyzer' => 'plain',
'operator' => 'and',
) );
$this->filters[] = new \Elastica\Filter\Query( $match );
} else {
// Elasticsearch seems to have trouble extracting the proper terms to highlight
// from the default query we make so we feed it exactly the right query to highlight.
$this->query = new \Elastica\Query\MultiMatch();
$this->query->setQuery( $search );
$weights = $this->config->get( 'CirrusSearchPrefixWeights' );
$this->query->setFields( array(
'title.prefix^' . $weights[ 'title' ],
'redirect.title.prefix^' . $weights[ 'redirect' ],
'title.prefix_asciifolding^' . $weights[ 'title_asciifolding' ],
'redirect.title.prefix_asciifolding^' . $weights[ 'redirect_asciifolding' ],
) );
}
} else {
$this->query = new \Elastica\Query\MatchAll();
}
// @todo: use dedicated rescore profiles for prefix search.
$this->searchContext->setBoostLinks( true );
return $this->search( 'prefix', $search );
}
/**
* @param string $suggestPrefix prefix to be prepended to suggestions
*/
public function addSuggestPrefix( $suggestPrefix ) {
$this->suggestPrefixes[] = $suggestPrefix;
}
/**
* Search articles with provided term.
* @param string $term term to search
* @param boolean $showSuggestion should this search suggest alternative searches that might be better?
* @return Status status containing results defined by resultsType on success
*/
public function searchText( $term, $showSuggestion ) {
$checkLengthStatus = $this->checkTextSearchRequestLength( $term );
if ( !$checkLengthStatus->isOk() ) {
return $checkLengthStatus;
}
// Transform Mediawiki specific syntax to filters and extra (pre-escaped) query string
$originalTerm = $term;
$searchContainedSyntax = false;
$this->term = $term;
$searchType = 'full_text';
// Handle title prefix notation
$prefixPos = strpos( $this->term, 'prefix:' );
if ( $prefixPos !== false ) {
$value = substr( $this->term, 7 + $prefixPos );
$value = trim( $value, '"' ); // Trim quotes in case the user wanted to quote the prefix
if ( strlen( $value ) > 0 ) {
$searchContainedSyntax = true;
$this->term = substr( $this->term, 0, max( 0, $prefixPos - 1 ) );
$this->suggestSuffixes[] = ' prefix:' . $value;
// Suck namespaces out of $value
$cirrusSearchEngine = new CirrusSearch();
$cirrusSearchEngine->setConnection( $this->connection );
$value = trim( $cirrusSearchEngine->replacePrefixes( $value ) );
$this->searchContext->setNamespaces( $cirrusSearchEngine->namespaces );
// If the namespace prefix wasn't the entire prefix filter then add a filter for the title
if ( strpos( $value, ':' ) !== strlen( $value ) - 1 ) {
$value = str_replace( '_', ' ', $value );
$prefixQuery = new \Elastica\Query\Match();
$prefixQuery->setFieldQuery( 'title.prefix', $value );
$this->filters[] = new \Elastica\Filter\Query( $prefixQuery );
}
}
}
$preferRecentDecayPortion = $this->config->get( 'CirrusSearchPreferRecentDefaultDecayPortion' );
$preferRecentHalfLife = $this->config->get( 'CirrusSearchPreferRecentDefaultHalfLife' );
$unspecifiedDecayPortion = $this->config->get( 'CirrusSearchPreferRecentUnspecifiedDecayPortion' );
// Matches "prefer-recent:" and then an optional floating point number <= 1 but >= 0 (decay
// portion) and then an optional comma followed by another floating point number >= 0 (half life)
$this->extractSpecialSyntaxFromTerm(
'/prefer-recent:(1|0?(?:\.\d+)?)?(?:,(\d*\.?\d+))? ?/',
function ( $matches ) use ( $unspecifiedDecayPortion, &$preferRecentDecayPortion, &$preferRecentHalfLife,
&$searchContainedSyntax ) {
if ( isset( $matches[ 1 ] ) && strlen( $matches[ 1 ] ) ) {
$preferRecentDecayPortion = floatval( $matches[ 1 ] );
} else {
$preferRecentDecayPortion = $unspecifiedDecayPortion;
}
if ( isset( $matches[ 2 ] ) ) {
$preferRecentHalfLife = floatval( $matches[ 2 ] );
}
$searchContainedSyntax = true;
return '';
}
);
$this->searchContext->setPreferRecentOptions( $preferRecentDecayPortion, $preferRecentHalfLife );
$this->extractSpecialSyntaxFromTerm(
'/^\s*local:/',
function ( $matches ) {
$this->limitSearchToLocalWiki( true );
return '';
}
);
// Handle other filters
$filters = $this->filters;
$notFilters = $this->notFilters;
$highlightSource = array();
$this->extractSpecialSyntaxFromTerm(
'/(?<not>-)?insource:\/(?<pattern>(?:[^\\\\\/]|\\\\.)+)\/(?<insensitive>i)? ?/',
function ( $matches ) use ( &$filters, &$notFilters, &$searchContainedSyntax, &$searchType, &$highlightSource ) {
if ( !$this->config->get( 'CirrusSearchEnableRegex' ) ) {
return;
}
$searchContainedSyntax = true;
$searchType = 'regex';
$insensitive = !empty( $matches[ 'insensitive' ] );
$filterDestination = &$filters;
if ( !empty( $matches[ 'not' ] ) ) {
$filterDestination = &$notFilters;
} else {
$highlightSource[] = array(
'pattern' => $matches[ 'pattern' ],
'locale' => $this->config->get( 'LanguageCode' ),
'insensitive' => $insensitive,
);
}
$regex = $this->config->getElement( 'CirrusSearchWikimediaExtraPlugin', 'regex' );
if ( $regex && in_array( 'use', $regex ) ) {
$filter = new SourceRegex( $matches[ 'pattern' ], 'source_text', 'source_text.trigram' );
if ( isset( $regex[ 'max_inspect' ] ) ) {
$filter->setMaxInspect( $regex[ 'max_inspect' ] );
} else {
$filter->setMaxInspect( 10000 );
}
$filter->setMaxDeterminizedStates( $this->config->get( 'CirrusSearchRegexMaxDeterminizedStates' ) );
if ( isset( $regex[ 'max_ngrams_extracted' ] ) ) {
$filter->setMaxNgramExtracted( $regex[ 'max_ngrams_extracted' ] );
}
$filter->setCaseSensitive( !$insensitive );
$filter->setLocale( $this->config->get( 'LanguageCode' ) );
$filterDestination[] = $filter;
} else {
// Without the extra plugin we need to use groovy to attempt the regex.
// Its less good but its something.
$script = <<<GROOVY
import org.apache.lucene.util.automaton.*;
sourceText = _source.get("source_text");
if (sourceText == null) {
false;
} else {
if (automaton == null) {
if (insensitive) {
locale = new Locale(language);
pattern = pattern.toLowerCase(locale);
}
regexp = new RegExp(pattern, RegExp.ALL ^ RegExp.AUTOMATON);
automaton = new CharacterRunAutomaton(regexp.toAutomaton());
}
if (insensitive) {
sourceText = sourceText.toLowerCase(locale);
}
automaton.run(sourceText);
}
GROOVY;
$filterDestination[] = new \Elastica\Filter\Script( new \Elastica\Script(
$script,
array(
'pattern' => '.*(' . $matches[ 'pattern' ] . ').*',
'insensitive' => $insensitive,
'language' => $this->config->get( 'LanguageCode' ),
// These null here creates a slot in which the script will shove
// an automaton while executing.
'automaton' => null,
'locale' => null,
),
'groovy'
) );
}
}
);
// Match filters that look like foobar:thing or foobar:"thing thing"
// The {7,15} keeps this from having horrible performance on big strings
$fuzzyQuery = $this->fuzzyQuery;
$isEmptyQuery = false;
$this->extractSpecialSyntaxFromTerm(
'/(?<key>[a-z\\-]{7,15}):\s*(?<value>"(?<quoted>(?:[^"]|(?<=\\\)")+)"|(?<unquoted>\S+)) ?/',
function ( $matches ) use ( &$filters, &$notFilters,
&$searchContainedSyntax, &$fuzzyQuery, &$highlightSource, &$isEmptyQuery ) {
$key = $matches['key'];
$quotedValue = $matches['value'];
$value = $matches['quoted'] !== ''
? str_replace( '\"', '"', $matches['quoted'] )
: $matches['unquoted'];
$filterDestination = &$filters;
$keepText = true;
if ( $key[ 0 ] === '-' ) {
$key = substr( $key, 1 );
$filterDestination = &$notFilters;
$keepText = false;
}
switch ( $key ) {
case 'boost-templates':
$boostTemplates = Util::parseBoostTemplates( $value );
$this->getSearchContext()->setBoostTemplatesFromQuery( $boostTemplates );
$searchContainedSyntax = true;
return '';
case 'hastemplate':
// We emulate template syntax here as best as possible,
// so things in NS_MAIN are prefixed with ":" and things
// in NS_TEMPLATE don't have a prefix at all. Since we
// don't actually index templates like that, munge the
// query here
if ( strpos( $value, ':' ) === 0 ) {
$value = substr( $value, 1 );
} else {
$title = Title::newFromText( $value );
if ( $title && $title->getNamespace() == NS_MAIN ) {
$value = Title::makeTitle( NS_TEMPLATE,
$title->getDBkey() )->getPrefixedText();
}
}
$filterDestination[] = $this->matchPage( 'template', $value );
$searchContainedSyntax = true;
return '';
case 'linksto':
$filterDestination[] = $this->matchPage( 'outgoing_link', $value, true );
$searchContainedSyntax = true;
return '';
case 'incategory':
$categories = array_slice( explode( '|', $value ), 0, $this->config->get( 'CirrusSearchMaxIncategoryOptions' ) );
$categoryFilters = $this->matchPageCategories( $categories );
if ( $categoryFilters === null ) {
$isEmptyQuery = true;
} else {
$filterDestination[] = $categoryFilters;
}
$searchContainedSyntax = true;
return '';
case 'insource':
$updateReferences = Filters::insource( $this->escaper, $this->getSearchContext(), $quotedValue );
$updateReferences( $fuzzyQuery, $filterDestination, $highlightSource, $searchContainedSyntax );
return '';
case 'intitle':
$updateReferences = Filters::intitle( $this->escaper, $this->getSearchContext(), $quotedValue );
$updateReferences( $fuzzyQuery, $filterDestination, $highlightSource, $searchContainedSyntax );
return $keepText ? "$quotedValue " : '';
default:
return $matches[0];
}
}
);
if ( $isEmptyQuery ) {
return Status::newGood( new SearchResultSet( true ) );
}
$this->filters = $filters;
$this->notFilters = $notFilters;
$this->searchContext->setSearchContainedSyntax( $searchContainedSyntax );
$this->fuzzyQuery = $fuzzyQuery;
$this->highlightSource = $highlightSource;
$this->term = $this->escaper->escapeQuotes( $this->term );
$this->term = trim( $this->term );
// Match quoted phrases including those containing escaped quotes
// Those phrases can optionally be followed by ~ then a number (this is the phrase slop)
// That can optionally be followed by a ~ (this matches stemmed words in phrases)
// The following all match: "a", "a boat", "a\"boat", "a boat"~, "a boat"~9, "a boat"~9~, -"a boat", -"a boat"~9~
$slop = $this->config->get('CirrusSearchPhraseSlop');
$query = self::replacePartsOfQuery( $this->term, '/(?<![\]])(?<negate>-|!)?(?<main>"((?:[^"]|(?<=\\\)")+)"(?<slop>~\d+)?)(?<fuzzy>~)?/',
function ( $matches ) use ( $slop ) {
$negate = $matches[ 'negate' ][ 0 ] ? 'NOT ' : '';
$main = $this->escaper->fixupQueryStringPart( $matches[ 'main' ][ 0 ] );
if ( !$negate && !isset( $matches[ 'fuzzy' ] ) && !isset( $matches[ 'slop' ] ) &&
preg_match( '/^"([^"*]+)[*]"/', $main, $matches ) ) {
$phraseMatch = new Elastica\Query\Match( );
$phraseMatch->setFieldQuery( "all.plain", $matches[1] );
$phraseMatch->setFieldType( "all.plain", "phrase_prefix" );
$this->nonTextQueries[] = $phraseMatch;
$phraseHighlightMatch = new Elastica\Query\QueryString( );
$phraseHighlightMatch->setQuery( $matches[1] . '*' );
$phraseHighlightMatch->setFields( array( 'all.plain' ) );
$this->nonTextHighlightQueries[] = $phraseHighlightMatch;
return array();
}
if ( !isset( $matches[ 'fuzzy' ] ) ) {
if ( !isset( $matches[ 'slop' ] ) ) {
$main = $main . '~' . $slop[ 'precise' ];
}
// Got to collect phrases that don't use the all field so we can highlight them.
// The highlighter locks phrases to the fields that specify them. It doesn't do
// that with terms.
return array(
'escaped' => $negate . $this->switchSearchToExact( $main, true ),
'nonAll' => $negate . $this->switchSearchToExact( $main, false ),
);
}
return array( 'escaped' => $negate . $main );
} );
// Find prefix matches and force them to only match against the plain analyzed fields. This
// prevents prefix matches from getting confused by stemming. Users really don't expect stemming
// in prefix queries.
$query = self::replaceAllPartsOfQuery( $query, '/\w+\*(?:\w*\*?)*/u',
function ( $matches ) {
$term = $this->escaper->fixupQueryStringPart( $matches[ 0 ][ 0 ] );
return array(
'escaped' => $this->switchSearchToExactForWildcards( $term ),
'nonAll' => $this->switchSearchToExactForWildcards( $term )
);
} );
$escapedQuery = array();
$nonAllQuery = array();
$nearMatchQuery = array();
foreach ( $query as $queryPart ) {
if ( isset( $queryPart[ 'escaped' ] ) ) {
$escapedQuery[] = $queryPart[ 'escaped' ];
if ( isset( $queryPart[ 'nonAll' ] ) ) {
$nonAllQuery[] = $queryPart[ 'nonAll' ];
} else {
$nonAllQuery[] = $queryPart[ 'escaped' ];
}
continue;
}
if ( isset( $queryPart[ 'raw' ] ) ) {
$fixed = $this->escaper->fixupQueryStringPart( $queryPart[ 'raw' ] );
$escapedQuery[] = $fixed;
$nonAllQuery[] = $fixed;
$nearMatchQuery[] = $queryPart[ 'raw' ];
continue;
}
LoggerFactory::getInstance( 'CirrusSearch' )->warning(
'Unknown query part: {queryPart}',
array( 'queryPart' => serialize( $queryPart ) )
);
}
// Actual text query
list( $queryStringQueryString, $this->fuzzyQuery ) =
$this->escaper->fixupWholeQueryString( implode( ' ', $escapedQuery ) );
// Note that no escaping is required for near_match's match query.
$nearMatchQuery = implode( ' ', $nearMatchQuery );
if ( $queryStringQueryString !== '' ) {
if ( preg_match( '/(?<!\\\\)[?*+~"!|-]|AND|OR|NOT/', $queryStringQueryString ) ) {
$this->searchContext->setSearchContainedSyntax( true );
// We're unlikey to make good suggestions for query string with special syntax in them....
$showSuggestion = false;
}
$fields = array_merge(
$this->buildFullTextSearchFields( 1, '.plain', true ),
$this->buildFullTextSearchFields( $this->config->get( 'CirrusSearchStemmedWeight' ), '', true ) );
$nearMatchFields = $this->buildFullTextSearchFields( $this->config->get( 'CirrusSearchNearMatchWeight' ),
'.near_match', true );
$this->query = $this->buildSearchTextQuery( $fields, $nearMatchFields,
$queryStringQueryString, $nearMatchQuery );
// The highlighter doesn't know about the weightinging from the all fields so we have to send
// it a query without the all fields. This swaps one in.
if ( $this->config->getElement( 'CirrusSearchAllFields', 'use' ) ) {
$nonAllFields = array_merge(
$this->buildFullTextSearchFields( 1, '.plain', false ),
$this->buildFullTextSearchFields( $this->config->get( 'CirrusSearchStemmedWeight' ), '', false ) );
list( $nonAllQueryString, /*_*/ ) = $this->escaper->fixupWholeQueryString( implode( ' ', $nonAllQuery ) );
$this->highlightQuery = $this->buildSearchTextQueryForFields( $nonAllFields, $nonAllQueryString, 1, false, true );
} else {
$nonAllFields = $fields;
}
// Only do a phrase match rescore if the query doesn't include any quotes and has a space.
// Queries without spaces are either single term or have a phrase query generated.
// Queries with the quote already contain a phrase query and we can't build phrase queries
// out of phrase queries at this point.
if ( $this->config->get( 'CirrusSearchPhraseRescoreBoost' ) > 1.0 &&
$this->config->get( 'CirrusSearchPhraseRescoreWindowSize' ) &&
!$this->searchContext->isSearchContainedSyntax() &&
strpos( $queryStringQueryString, '"' ) === false &&
strpos( $queryStringQueryString, ' ' ) !== false ) {
$rescoreFields = $fields;
if ( !$this->config->get( 'CirrusSearchAllFieldsForRescore' ) ) {
$rescoreFields = $nonAllFields;
}
$this->rescore[] = array(
'window_size' => $this->config->get( 'CirrusSearchPhraseRescoreWindowSize' ),
'query' => array(
'rescore_query' => $this->buildSearchTextQueryForFields( $rescoreFields,
'"' . $queryStringQueryString . '"', $this->config->getElement( 'CirrusSearchPhraseSlop', 'boost' ), true ),
'query_weight' => 1.0,
'rescore_query_weight' => $this->config->get( 'CirrusSearchPhraseRescoreBoost' ),
)
);
}
$showSuggestion = $showSuggestion && ($this->offset == 0);
if ( $showSuggestion ) {
$this->suggest = array(
'text' => $this->term,
'suggest' => $this->buildSuggestConfig( 'suggest' ),
);
}
$result = $this->search( $searchType, $originalTerm );
if ( !$result->isOK() && $this->isParseError( $result ) ) {
// Elasticsearch has reported a parse error and we've already logged it when we built the status
// so at this point all we can do is retry the query as a simple query string query.
$this->query = new \Elastica\Query\Simple( array( 'simple_query_string' => array(
'fields' => $fields,
'query' => $queryStringQueryString,
'default_operator' => 'AND',
) ) );
$this->rescore = array(); // Not worth trying in this state.
$result = $this->search( 'degraded_full_text', $originalTerm );
// If that doesn't work we're out of luck but it should. There no guarantee it'll work properly
// with the syntax we've built above but it'll do _something_ and we'll still work on fixing all
// the parse errors that come in.
}
} else {
$result = $this->search( $searchType, $originalTerm );
// No need to check for a parse error here because we don't actually create a query for
// Elasticsearch to parse
}
return $result;
}
/**
* Builds a match query against $field for $title. $title is munged to make title matching better more
* intuitive for users.
* @param string $field field containing the title
* @param string $title title query text to match against
* @param boolean $underscores true if the field contains underscores instead of spaces. Defaults to false.
* @return \Elastica\Filter\Query for matching $title to $field
*/
public function matchPage( $field, $title, $underscores = false ) {
if ( $underscores ) {
$title = str_replace( ' ', '_', $title );
} else {
$title = str_replace( '_', ' ', $title );
}
$match = new \Elastica\Query\Match();
$match->setFieldQuery( $field, $title );
return new \Elastica\Filter\Query( $match );
}
/**
* Builds an or between many categories that the page could be in.
* @param string[] $categories categories to match
* @return \Elastica\Filter\BoolFilter|null A null return value means all values are filtered
* and an empty result set should be returned.
*/
public function matchPageCategories( $categories ) {
$filter = new \Elastica\Filter\BoolFilter();
$ids = array();
$names = array();
foreach ( $categories as $category ) {
if ( substr( $category, 0, 3 ) === 'id:' ) {
$id = substr( $category, 3 );
if ( ctype_digit( $id ) ) {
$ids[] = $id;
}
} else {
$names[] = $category;
}
}
foreach ( Title::newFromIds( $ids ) as $title ) {
$names[] = $title->getText();
}
if ( !$names ) {
return null;
}
foreach( $names as $name ) {
$filter->addShould( $this->matchPage( 'category.lowercase_keyword', $name ) );
}
return $filter;
}
/**
* Find articles that contain similar text to the provided title array.
* @param Title[] $titles array of titles of articles to search for
* @param int $options bitset of options:
* MORE_LIKE_THESE_NONE
* MORE_LIKE_THESE_ONLY_WIKIBASE - filter results to only those containing wikibase items
* @return Status<ResultSet>
*/
public function moreLikeTheseArticles( array $titles, $options = Searcher::MORE_LIKE_THESE_NONE ) {
sort( $titles, SORT_STRING );
$pageIds = array();
foreach ( $titles as $title ) {
$pageIds[] = $title->getArticleID();
}
// If no fields has been set we return no results.
// This can happen if the user override this setting with field names that
// are not allowed in $this->config->get( 'CirrusSearchMoreLikeThisAllowedFields (see Hooks.php)
if( !$this->config->get( 'CirrusSearchMoreLikeThisFields' ) ) {
return Status::newGood( new SearchResultSet( true ) /* empty */ );
}
// more like this queries are quite expensive and are suspected to be
// triggering latency spikes. This allows redirecting more like this
// queries to a different cluster
$cluster = $this->config->get( 'CirrusSearchMoreLikeThisCluster' );
if ( $cluster ) {
$this->connection = Connection::getPool( $this->config, $cluster );
}
$this->searchContext->setSearchContainedSyntax( true );
$moreLikeThisFields = $this->config->get( 'CirrusSearchMoreLikeThisFields' );
$moreLikeThisUseFields = $this->config->get( 'CirrusSearchMoreLikeThisUseFields' );
sort( $moreLikeThisFields );
$this->query = new \Elastica\Query\MoreLikeThis();
$this->query->setParams( $this->config->get( 'CirrusSearchMoreLikeThisConfig' ) );
$this->query->setFields( $moreLikeThisFields );
// The 'all' field cannot be retrieved from _source
// We have to extract the text content before.
if( in_array( 'all', $moreLikeThisFields ) ) {
$moreLikeThisUseFields = false;
}
if ( !$moreLikeThisUseFields && $moreLikeThisFields != array( 'text' ) ) {
// Run a first pass to extract the text field content because we want to compare it
// against other fields.
$text = array();
$found = $this->get( $pageIds, array( 'text' ) );
if ( !$found->isOk() ) {
return $found;
}
$found = $found->getValue();
if ( count( $found ) === 0 ) {
// If none of the pages are in the index we can't find articles like them
return Status::newGood( new SearchResultSet() /* empty */ );
}
foreach ( $found as $foundArticle ) {
$text[] = $foundArticle->text;
}
sort( $text, SORT_STRING );
$this->query->setLikeText( implode( ' ', $text ) );
}
// @todo: use setIds when T104560 is done
$this->query->setParam( 'ids', $pageIds );
if ( $options & Searcher::MORE_LIKE_THESE_ONLY_WIKIBASE ) {
$this->filters[] = new \Elastica\Filter\Exists( 'wikibase_item' );
}
// highlight snippets are not great so it's worth running a match all query
// to save cpu cycles
$this->highlightQuery = new \Elastica\Query\MatchAll();
return $this->search(
'more_like',
implode( ', ', $titles ),
$this->config->get( 'CirrusSearchMoreLikeThisTTL' )
);
}
/**
* Get the page with $id. Note that the result is a status containing _all_ pages found.
* It is possible to find more then one page if the page is in multiple indexes.
* @param int[] $pageIds array of page ids
* @param string[]|true|false $sourceFiltering source filtering to apply
* @return Status containing pages found, containing an empty array if not found,
* or an error if there was an error
*/
public function get( array $pageIds, $sourceFiltering ) {
$indexType = $this->pickIndexTypeFromNamespaces();
return Util::doPoolCounterWork(
'CirrusSearch-Search',
$this->user,
function() use ( $pageIds, $sourceFiltering, $indexType ) {
try {
$this->start( "get of {indexType}.{pageIds}", array(
'indexType' => $indexType,
'pageIds' => array_map( 'intval', $pageIds ),
'queryType' => 'get',
) );
// Shard timeout not supported on get requests so we just use the client side timeout
$this->connection->setTimeout( $this->config->getElement( 'CirrusSearchClientSideSearchTimeout', 'default' ) );
$pageType = $this->connection->getPageType( $this->indexBaseName, $indexType );
$query = new \Elastica\Query( new \Elastica\Query\Ids( null, $pageIds ) );
$query->setParam( '_source', $sourceFiltering );
$query->addParam( 'stats', 'get' );
$resultSet = $pageType->search( $query, array( 'search_type' => 'query_and_fetch' ) );
return $this->success( $resultSet->getResults() );
} catch ( \Elastica\Exception\NotFoundException $e ) {
// NotFoundException just means the field didn't exist.
// It is up to the caller to decide if that is an error.
return $this->success( array() );
} catch ( \Elastica\Exception\ExceptionInterface $e ) {
return $this->failure( $e );
}
});
}
/**
* @param string $name
* @return Status
*/
public function findNamespace( $name ) {
return Util::doPoolCounterWork(
'CirrusSearch-NamespaceLookup',
$this->user,
function() use ( $name ) {
try {
$this->start( "lookup namespace for {namespaceName}", array(
'namespaceName' => $name,
'query' => $name,
'queryType' => 'namespace',
) );
$pageType = $this->connection->getNamespaceType( $this->indexBaseName );
$match = new \Elastica\Query\Match();
$match->setField( 'name', $name );
$query = new \Elastica\Query( $match );
$query->setParam( '_source', false );
$query->addParam( 'stats', 'namespace' );
$resultSet = $pageType->search( $query, array( 'search_type' => 'query_and_fetch' ) );
return $this->success( $resultSet->getResults() );
} catch ( \Elastica\Exception\ExceptionInterface $e ) {
return $this->failure( $e );
}
});
}
/**
* @param string $regex
* @param callable $callback
*/
private function extractSpecialSyntaxFromTerm( $regex, $callback ) {
$this->term = preg_replace_callback( $regex,
function ( $matches ) use ( $callback ) {
$result = $callback( $matches );
if ( $result === '' ) {
$this->suggestPrefixes[] = $matches[ 0 ];
}
return $result;
},
$this->term
);
}
/**
* @param array[] $query
* @param string $regex
* @param callable $callable
* @return array[]
*/
private static function replaceAllPartsOfQuery( array $query, $regex, $callable ) {
$result = array();
foreach ( $query as $queryPart ) {
if ( isset( $queryPart[ 'raw' ] ) ) {
$result = array_merge( $result, self::replacePartsOfQuery( $queryPart[ 'raw' ], $regex, $callable ) );
continue;
}
$result[] = $queryPart;
}
return $result;
}
/**
* @param string $queryPart
* @param string $regex
* @param callable $callable
* @return array[]
*/
private static function replacePartsOfQuery( $queryPart, $regex, $callable ) {
$destination = array();
$matches = array();
$offset = 0;
while ( preg_match( $regex, $queryPart, $matches, PREG_OFFSET_CAPTURE, $offset ) ) {
$startOffset = $matches[ 0 ][ 1 ];
if ( $startOffset > $offset ) {
$destination[] = array( 'raw' => substr( $queryPart, $offset, $startOffset - $offset ) );
}
$callableResult = call_user_func( $callable, $matches );
if ( $callableResult ) {