Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
60.45% covered (warning)
60.45%
81 / 134
12.50% covered (danger)
12.50%
1 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
LexemeFulltextResult
60.45% covered (warning)
60.45%
81 / 134
12.50% covered (danger)
12.50%
1 / 8
63.67
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getSourceFiltering
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 getFields
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getHighlightingConfiguration
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
2
 getFormIdResult
90.00% covered (success)
90.00%
18 / 20
0.00% covered (danger)
0.00%
0 / 1
5.03
 getFormRepresentationResult
88.24% covered (warning)
88.24%
15 / 17
0.00% covered (danger)
0.00%
0 / 1
4.03
 transformElasticsearchResult
95.74% covered (success)
95.74%
45 / 47
0.00% covered (danger)
0.00%
0 / 1
11
 createEmptyResult
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2namespace Wikibase\Lexeme\Search\Elastic;
3
4use CirrusSearch\Search\BaseCirrusSearchResultSet;
5use CirrusSearch\Search\BaseResultsType;
6use Elastica\ResultSet;
7use MediaWiki\Language\Language;
8use MediaWiki\Search\ISearchResultSet;
9use Wikibase\DataModel\Entity\EntityIdParser;
10use Wikibase\Lexeme\DataAccess\LexemeDescription;
11use Wikibase\Lib\Store\FallbackLabelDescriptionLookupFactory;
12use Wikibase\Search\Elastic\EntitySearchUtils;
13use Wikibase\Search\Elastic\Fields\StatementCountField;
14
15/**
16 * This result type implements the result for searching a Lexeme for fulltext search.
17 *
18 * @license GPL-2.0-or-later
19 * @author Stas Malyshev
20 */
21class LexemeFulltextResult extends BaseResultsType {
22
23    /**
24     * @var EntityIdParser
25     */
26    private $idParser;
27
28    /**
29     * Display language
30     * @var Language
31     */
32    private $displayLanguage;
33    /**
34     * @var FallbackLabelDescriptionLookupFactory
35     */
36    private $termLookupFactory;
37
38    /**
39     * @param EntityIdParser $idParser
40     * @param Language $displayLanguage User display language
41     * @param FallbackLabelDescriptionLookupFactory $termLookupFactory
42     *        Lookup factory for assembling descriptions
43     */
44    public function __construct(
45        EntityIdParser $idParser,
46        Language $displayLanguage,
47        FallbackLabelDescriptionLookupFactory $termLookupFactory
48    ) {
49        $this->idParser = $idParser;
50        $this->termLookupFactory = $termLookupFactory;
51        $this->displayLanguage = $displayLanguage;
52    }
53
54    /**
55     * Get the source filtering to be used loading the result.
56     *
57     * @return string[]
58     */
59    public function getSourceFiltering() {
60        return array_merge( parent::getSourceFiltering(), [
61                LemmaField::NAME,
62                LexemeLanguageField::NAME,
63                LexemeCategoryField::NAME,
64                FormsField::NAME,
65                StatementCountField::NAME,
66                // The web ui for fulltext search expects this to be returned.
67                // Longer term there should probably be some concept where the UI
68                // requests additional properties instead of baking it in at these
69                // lower levels for each fulltext results type.
70                'timestamp',
71        ] );
72    }
73
74    /**
75     * Get the fields to load.  Most of the time we'll use source filtering instead but
76     * some fields aren't part of the source.
77     *
78     * @return string[]
79     */
80    public function getFields() {
81        return [];
82    }
83
84    /**
85     * Get the highlighting configuration.
86     *
87     * @param array $highlightSource configuration for how to highlight the source.
88     *  Empty if source should be ignored.
89     * @return array|null highlighting configuration for elasticsearch
90     */
91    public function getHighlightingConfiguration( array $highlightSource ) {
92        $config = [
93            'pre_tags' => [ '' ],
94            'post_tags' => [ '' ],
95            'fields' => [],
96        ];
97        $config['fields']['title'] = [
98            'type' => 'experimental',
99            'fragmenter' => "none",
100            'number_of_fragments' => 0,
101            'matched_fields' => [ 'title.keyword' ]
102        ];
103        $config['fields']['lexeme_forms.id'] = [
104            'type' => 'experimental',
105            'fragmenter' => "none",
106            'number_of_fragments' => 0,
107            'options' => [
108                'skip_if_last_matched' => true,
109            ],
110        ];
111        $config['fields']["lemma"] = [
112            'type' => 'experimental',
113            'fragmenter' => "none",
114            'number_of_fragments' => 0,
115            'options' => [
116                'skip_if_last_matched' => true,
117            ],
118        ];
119        $config['fields']["lexeme_forms.representation"] = [
120            'type' => 'experimental',
121            'fragmenter' => "none",
122            'number_of_fragments' => 30,
123            'fragment_size' => 1000, // Hopefully this is enough
124            'options' => [
125                'skip_if_last_matched' => true,
126            ],
127        ];
128
129        return $config;
130    }
131
132    /**
133     * Produce raw result for Form ID match.
134     * @param string[][] $highlight Highlighter data
135     * @param array $sourceData Lexeme source data
136     * @return array|null Null if match is bad
137     */
138    private function getFormIdResult( $highlight, $sourceData ) {
139        $formId = $highlight['lexeme_forms.id'][0];
140        $formIdParsed = EntitySearchUtils::parseOrNull( $formId, $this->idParser );
141        if ( !$formIdParsed ) {
142            // Got some bad id?? Weird.
143            return null;
144        }
145        $repr = '';
146        $features = [];
147        foreach ( $sourceData['lexeme_forms'] as $form ) {
148            if ( $form['id'] === $formId ) {
149                // TODO: how we choose one?
150                $repr = $form['representation'][0];
151                // Convert features to EntityId's
152                $features = array_filter( array_map( function ( $featureId ) {
153                    return EntitySearchUtils::parseOrNull( $featureId, $this->idParser );
154                }, $form['features'] ) );
155                break;
156            }
157        }
158        if ( $repr === '' ) {
159            // Didn't find the right id? Weird, skip it.
160            return null;
161        }
162
163        return [
164            'formId' => $formId,
165            'representation' => $repr,
166            'features' => $features,
167        ];
168    }
169
170    /**
171     * Get data for specific form match from source data
172     * @param array[] $sourceForms 'forms' field of the source data
173     * @param string[] $highlight Highlighter data about match
174     * @return array|null Null if match is bad
175     */
176    private function getFormRepresentationResult( $sourceForms, $highlight ) {
177        foreach ( $sourceForms as $form ) {
178            $reprMatches = array_intersect( $form['representation'],
179                $highlight );
180            if ( !$reprMatches ) {
181                continue;
182            }
183            // matches the data
184            $formIdParsed = EntitySearchUtils::parseOrNull( $form['id'], $this->idParser );
185            if ( !$formIdParsed ) {
186                // Got some bad id?? Weird.
187                continue;
188            }
189            // Convert features to EntityId's
190            $featureIds = array_filter( array_map( function ( $featureId ) {
191                return EntitySearchUtils::parseOrNull( $featureId, $this->idParser );
192            }, $form['features'] ) );
193
194            return [
195                'formId' => $formIdParsed,
196                'representation' => reset( $reprMatches ),
197                'features' => $featureIds,
198            ];
199        }
200        // Didn't find anything
201        return null;
202    }
203
204    /**
205     * Convert search result from ElasticSearch result set to LexemeResultSet.
206     *
207     * The data inside the set are not rendered yet, but the set is configured with
208     * the label lookup that has necessary item labels already loaded.
209     *
210     * @param ResultSet $result ElasticSearch results
211     * @return ISearchResultSet
212     */
213    public function transformElasticsearchResult( ResultSet $result ) {
214        $rawResults = $entityIds = [];
215        foreach ( $result->getResults() as $r ) {
216            $rawResultKey = spl_object_hash( $r );
217            $sourceData = $r->getSource();
218            $entityId = EntitySearchUtils::parseOrNull( $sourceData['title'], $this->idParser );
219            if ( !$entityId ) {
220                // Can not parse entity ID - skip it
221                // TODO: what we do here if no language code?
222                // Not sure we want to index all lemma languages.
223                // Should we just fake the term language code?
224                continue;
225            }
226
227            $lemmaCode = LexemeTermResult::extractLanguageCode( $sourceData );
228
229            // Highlight part contains information about what has actually been matched.
230            $highlight = $r->getHighlights();
231
232            // we accept missing lemma fields (see T365692)
233            $lang = $sourceData['lexeme_language']['entity'] ?? '';
234            $category = $sourceData['lexical_category'] ?? '';
235
236            $features = [];
237            $lexemeData = [
238                'lexemeId' => $entityId,
239                // Having empty lemma is unusual, but in theory possible
240                'lemma' => empty( $sourceData['lemma'] ) ? '' : $sourceData['lemma'][0],
241                'lang' => $lang,
242                'langcode' => $lemmaCode,
243                'category' => $category,
244                'elasticResult' => $r
245            ];
246
247            if ( !empty( $highlight['lexeme_forms.id'] ) ) {
248                // If we matched Form ID, this means it's a match by ID
249
250                $idResult = $this->getFormIdResult( $highlight, $sourceData );
251                if ( !$idResult ) {
252                    continue;
253                }
254
255                $lexemeData = $idResult + $lexemeData;
256                $features = array_merge( $features, $idResult['features'] );
257            } elseif ( !empty( $highlight['lemma'] ) ) {
258                // TODO: make result display highlight this
259                $lexemeData['matchedLemma'] = $highlight['lemma'][0];
260            } elseif ( !empty( $highlight["lexeme_forms.representation"] ) ) {
261                // For now, find the first form that matches
262                $formResult = $this->getFormRepresentationResult( $sourceData['lexeme_forms'],
263                        $highlight['lexeme_forms.representation'] );
264                if ( $formResult ) {
265                    $lexemeData = $formResult + $lexemeData;
266                    $features = array_merge( $features, $formResult['features'] );
267                }
268            }
269
270            // Doing two-stage resolution here since we want to prefetch all labels for
271            // auxiliary entities before using them to construct descriptions.
272            $lexemeData['elastica_result_hash'] = $rawResultKey;
273            $rawResults[$entityId->getSerialization()] = $lexemeData;
274            $entityIds[$lang] = EntitySearchUtils::parseOrNull( $lang, $this->idParser );
275            $entityIds[$category] = EntitySearchUtils::parseOrNull( $category, $this->idParser );
276            foreach ( $features as $feature ) {
277                $entityIds[$feature->getSerialization()] = $feature;
278            }
279        }
280
281        if ( !$rawResults ) {
282            return new \CirrusSearch\Search\ResultSet();
283        }
284        // Create prefetched lookup
285        $termLookup = $this->termLookupFactory->newLabelDescriptionLookup( $this->displayLanguage,
286            array_filter( $entityIds ) );
287        $descriptionMaker = new LexemeDescription( $termLookup, $this->idParser,
288            $this->displayLanguage );
289
290        return new LexemeResultSet( $result, $this->displayLanguage, $descriptionMaker, $rawResults );
291    }
292
293    /**
294     * @return mixed Empty set of search results
295     */
296    public function createEmptyResult() {
297        return BaseCirrusSearchResultSet::emptyResultSet( false );
298    }
299
300}