Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.48% covered (success)
90.48%
38 / 42
33.33% covered (danger)
33.33%
1 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
EntitySearchElastic
90.48% covered (success)
90.48%
38 / 42
33.33% covered (danger)
33.33%
1 / 3
7.04
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getElasticSearchQuery
85.71% covered (warning)
85.71%
18 / 21
0.00% covered (danger)
0.00%
0 / 1
2.01
 getRankedSearchResults
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
4.00
1<?php
2
3namespace Wikibase\Search\Elastic;
4
5use CirrusSearch\CirrusDebugOptions;
6use CirrusSearch\Search\SearchContext;
7use Elastica\Query\AbstractQuery;
8use Elastica\Query\MatchNone;
9use MediaWiki\Language\Language;
10use MediaWiki\Request\FauxRequest;
11use MediaWiki\Request\WebRequest;
12use Wikibase\DataModel\Entity\EntityIdParser;
13use Wikibase\Lib\LanguageFallbackChainFactory;
14use Wikibase\Repo\Api\EntitySearchException;
15use Wikibase\Repo\Api\EntitySearchHelper;
16use Wikibase\Search\Elastic\Query\LabelsCompletionQuery;
17
18/**
19 * Entity search implementation using ElasticSearch.
20 * Requires CirrusSearch extension and $wgEntitySearchUseCirrus to be on.
21 *
22 * @license GPL-2.0-or-later
23 * @author Stas Malyshev
24 */
25class EntitySearchElastic implements EntitySearchHelper {
26    /**
27     * Default rescore profile
28     */
29    public const DEFAULT_RESCORE_PROFILE = 'wikibase_prefix';
30
31    /**
32     * Name of the context for profile name resolution
33     */
34    public const CONTEXT_WIKIBASE_PREFIX = 'wikibase_prefix_search';
35
36    /**
37     * Name of the context for profile name resolution
38     */
39    public const CONTEXT_WIKIBASE_FULLTEXT = 'wikibase_fulltext_search';
40
41    /**
42     * Name of the context for profile name resolution
43     */
44    public const CONTEXT_WIKIBASE_IN_LABEL = 'wikibase_in_label_search';
45
46    /**
47     * Name of the profile type used to build the elastic query
48     */
49    public const WIKIBASE_PREFIX_QUERY_BUILDER = 'wikibase_prefix_querybuilder';
50
51    /**
52     * Name of the profile type used to build the elastic query
53     */
54    public const WIKIBASE_IN_LABEL_QUERY_BUILDER = 'wikibase_in_label_querybuilder';
55
56    /**
57     * Default query builder profile for prefix searches
58     */
59    public const DEFAULT_QUERY_BUILDER_PROFILE = 'default';
60
61    /**
62     * Default query builder profile for fulltext searches
63     *
64     */
65    public const DEFAULT_FULL_TEXT_QUERY_BUILDER_PROFILE = 'wikibase';
66
67    /**
68     * Replacement syntax for statement boosting
69     * @see \CirrusSearch\Profile\SearchProfileRepositoryTransformer
70     * and repo/config/ElasticSearchRescoreFunctions.php
71     */
72    public const STMT_BOOST_PROFILE_REPL = 'functions.*[type=term_boost].params[statement_keywords=_statementBoost_].statement_keywords';
73
74    /**
75     * Web request context.
76     * Used for implementing debug features such as cirrusDumpQuery.
77     * @var WebRequest
78     */
79    private $request;
80
81    /**
82     * @var CirrusDebugOptions
83     */
84    private $debugOptions;
85
86    /**
87     * @param LanguageFallbackChainFactory $languageChainFactory
88     * @param EntityIdParser $idParser
89     * @param Language $userLang User language for display
90     * @param array<string,string> $contentModelMap Maps entity type => content model name
91     * @param WebRequest|null $request Web request context
92     * @param CirrusDebugOptions|null $options
93     */
94    public function __construct(
95        private readonly LanguageFallbackChainFactory $languageChainFactory,
96        private readonly EntityIdParser $idParser,
97        private readonly Language $userLang,
98        private readonly array $contentModelMap,
99        ?WebRequest $request = null,
100        ?CirrusDebugOptions $options = null
101    ) {
102        $this->request = $request ?? new FauxRequest();
103        $this->debugOptions = $options ?? CirrusDebugOptions::fromRequest( $this->request );
104    }
105
106    /**
107     * Produce ES query that matches the arguments.
108     *
109     * @param string $text
110     * @param string $languageCode
111     * @param string $entityType
112     * @param bool $strictLanguage
113     * @param SearchContext $context
114     *
115     * @return AbstractQuery
116     */
117    protected function getElasticSearchQuery(
118        $text,
119        $languageCode,
120        $entityType,
121        $strictLanguage,
122        SearchContext $context
123    ) {
124        $context->setOriginalSearchTerm( $text );
125        if ( empty( $this->contentModelMap[$entityType] ) ) {
126            $context->setResultsPossible( false );
127            $context->addWarning( 'wikibasecirrus-search-bad-entity-type', $entityType );
128            return new MatchNone();
129        }
130        $profile = LabelsCompletionQuery::loadProfile(
131            $context->getConfig()->getProfileService(),
132            $this->languageChainFactory,
133            self::WIKIBASE_PREFIX_QUERY_BUILDER,
134            $context->getProfileContext(),
135            $context->getProfileContextParams(),
136            $languageCode
137        );
138        return LabelsCompletionQuery::build(
139            $text,
140            $profile,
141            $this->contentModelMap[$entityType],
142            $languageCode,
143            $strictLanguage,
144            EntitySearchUtils::entityIdParserNormalizer( $this->idParser )
145        );
146    }
147
148    /**
149     * @inheritDoc
150     */
151    public function getRankedSearchResults(
152        $text,
153        $languageCode,
154        $entityType,
155        $limit,
156        $strictLanguage,
157        ?string $profileContext = null
158    ) {
159        $searcher = new WikibaseEntitySearcher( 0, $limit, 'wikibase_prefix', 'wikibase-prefix', $this->debugOptions );
160        $searcher->getSearchContext()->setProfileContext(
161            $profileContext ?? self::CONTEXT_WIKIBASE_PREFIX,
162            [ 'language' => $languageCode ] );
163        $query = $this->getElasticSearchQuery( $text, $languageCode, $entityType, $strictLanguage,
164                $searcher->getSearchContext() );
165
166        $searcher->setResultsType( new EntityElasticTermResult(
167            $this->idParser,
168            $query instanceof LabelsCompletionQuery ? $query->getSearchLanguageCodes() : [],
169            'prefix',
170            $this->languageChainFactory->newFromLanguage( $this->userLang )
171        ) );
172
173        $result = $searcher->performSearch( $query );
174
175        if ( $result->isOK() ) {
176            $result = $result->getValue();
177        } else {
178            throw new EntitySearchException( $result );
179        }
180
181        if ( $searcher->isReturnRaw() ) {
182            $result = $searcher->processRawReturn( $result, $this->request );
183        }
184
185        return $result;
186    }
187
188}