Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.83% covered (success)
94.83%
110 / 116
78.57% covered (warning)
78.57%
11 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
AnalysisFilter
94.83% covered (success)
94.83%
110 / 116
78.57% covered (warning)
78.57%
11 / 14
59.48
0.00% covered (danger)
0.00%
0 / 1
 findUsedFromField
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
 findUsedAnalysisComponentsInMappings
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
3.14
 findUsedAnalyzersInMappings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 findUsedNormalizersInMappings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 pushAnalysisComponentAliasesIntoField
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
8
 pushAnalyzerAliasesIntoMappings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 pushNormalizerAliasesIntoMappings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 pushAnalysisComponentAliasesIntoMappings
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
3.33
 filter
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 filterUnusedAnalysisChain
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
12
 recursiveKsort
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 calcDeduplicationAliases
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 deduplicateAnalysisConfig
95.24% covered (success)
95.24%
20 / 21
0.00% covered (danger)
0.00%
0 / 1
11
 filterAnalysis
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace CirrusSearch\Maintenance;
4
5use MediaWiki\Json\FormatJson;
6
7/**
8 * Filter unused and duplicate entries from search index configuration
9 */
10class AnalysisFilter {
11    /** @var string[] List of key's in mappings that reference analyzers */
12    private const ANALYZER_FIELDS = [ 'analyzer', 'search_analyzer', 'search_quote_analyzer' ];
13
14    /** @var string[] List of key's in mappings that reference analyzers */
15    private const NORMALIZER_FIELDS = [ 'normalizer' ];
16
17    /** @var string[] List of key's in mappings that must be recursively searched */
18    private const SUBFIELD_FIELDS = [ 'fields', 'properties' ];
19
20    /**
21     * Recursively finds used analysis components from search mappings
22     *
23     * @param array $properties a 'properties' or 'fields' list from the mappings
24     * @param string[] $fieldsToLookAt inspect these mapping properties
25     * @return Set The set of referenced analyzers
26     */
27    private function findUsedFromField( array $properties, array $fieldsToLookAt ) {
28        $analyzers = new Set();
29        foreach ( $properties as $name => $config ) {
30            foreach ( $fieldsToLookAt as $key ) {
31                if ( isset( $config[$key] ) ) {
32                    $analyzers->add( $config[$key] );
33                }
34            }
35            foreach ( self::SUBFIELD_FIELDS as $key ) {
36                if ( isset( $config[$key] ) ) {
37                    $analyzers->union( $this->findUsedFromField( $config[$key], $fieldsToLookAt ) );
38                }
39            }
40        }
41        return $analyzers;
42    }
43
44    /**
45     * @param array[] $mappings search mapping configuration
46     * @param string[] $fieldsToLookAt inspect these mapping properties
47     * @return Set The set of analyzer names referenced in $mappings
48     */
49    public function findUsedAnalysisComponentsInMappings( array $mappings, array $fieldsToLookAt ): Set {
50        $analyzers = new Set();
51        if ( isset( $mappings['properties'] ) ) {
52            // modern search, no index types
53            $analyzers->union(
54                $this->findUsedFromField( $mappings['properties'], $fieldsToLookAt ) );
55        } else {
56            // BC for parts still using index types
57            foreach ( $mappings as $config ) {
58                $analyzers->union(
59                    $this->findUsedFromField( $config['properties'], $fieldsToLookAt ) );
60            }
61        }
62        return $analyzers;
63    }
64
65    public function findUsedAnalyzersInMappings( array $mappings ): Set {
66        return $this->findUsedAnalysisComponentsInMappings( $mappings, self::ANALYZER_FIELDS );
67    }
68
69    public function findUsedNormalizersInMappings( array $mappings ): Set {
70        return $this->findUsedAnalysisComponentsInMappings( $mappings, self::NORMALIZER_FIELDS );
71    }
72
73    /**
74     * Recursively applies analyzer aliases to search mappings
75     *
76     * @param array $properties a 'properties' or 'fields' list from the mappings
77     * @param string[] $aliases Map from current analyzer name to replacement name
78     * @param string[] $fieldsToLookAt inspect these mapping properties
79     * @return array $properties with analyzer aliases applied
80     */
81    private function pushAnalysisComponentAliasesIntoField( array $properties, array $aliases, array $fieldsToLookAt ): array {
82        foreach ( $properties as &$config ) {
83            foreach ( $fieldsToLookAt as $key ) {
84                if ( isset( $config[$key] ) && isset( $aliases[$config[$key]] ) ) {
85                    $config[$key] = $aliases[$config[$key]];
86                }
87            }
88            foreach ( self::SUBFIELD_FIELDS as $key ) {
89                if ( isset( $config[$key] ) && is_array( $config[$key] ) ) {
90                    $config[$key] = $this->pushAnalysisComponentAliasesIntoField(
91                        $config[$key], $aliases, $fieldsToLookAt
92                    );
93                }
94            }
95        }
96        return $properties;
97    }
98
99    /**
100     * @param array[] $mappings search index mapping configuration
101     * @param array<string, string> $aliases Mapping from old name to new name for analyzers
102     * @return array Updated index mapping configuration
103     */
104    public function pushAnalyzerAliasesIntoMappings( array $mappings, array $aliases ): array {
105        return $this->pushAnalysisComponentAliasesIntoMappings( $mappings, $aliases, self::ANALYZER_FIELDS );
106    }
107
108    /**
109     * @param array[] $mappings search index mapping configuration
110     * @param array<string, string> $aliases Mapping from old name to new name for analyzers
111     * @return array Updated index mapping configuration
112     */
113    public function pushNormalizerAliasesIntoMappings( array $mappings, array $aliases ): array {
114        return $this->pushAnalysisComponentAliasesIntoMappings( $mappings, $aliases, self::NORMALIZER_FIELDS );
115    }
116
117    /**
118     * @param array[] $mappings search index mapping configuration
119     * @param array<string, string> $aliases Mapping from old name to new name for analyzers
120     * @param string[] $fieldsToLookAt inspect these mapping properties
121     * @return array Updated index mapping configuration
122     */
123    private function pushAnalysisComponentAliasesIntoMappings( array $mappings, array $aliases, array $fieldsToLookAt ): array {
124        if ( isset( $mappings['properties'] ) ) {
125            // modern search, no index types
126            $mappings['properties'] = $this->pushAnalysisComponentAliasesIntoField(
127                $mappings['properties'], $aliases, $fieldsToLookAt
128            );
129        } else {
130            // BC for parts still using index types
131            foreach ( $mappings as $mappingType => $config ) {
132                $mappings[$mappingType]['properties'] = $this->pushAnalysisComponentAliasesIntoField(
133                    $config['properties'], $aliases, $fieldsToLookAt
134                );
135            }
136        }
137        return $mappings;
138    }
139
140    private function filter( array $data, Set $keysToKeep ): array {
141        foreach ( $data as $k => $v ) {
142            if ( !$keysToKeep->contains( $k ) ) {
143                unset( $data[$k] );
144            }
145        }
146        return $data;
147    }
148
149    /**
150     * @param array $analysis The index.analysis field of the search index settings
151     * @param Set $usedAnalyzers Set of analyzers to keep configurations for
152     * @param Set $usedNormalizers Set of normalizers to keep configurations for
153     * @return array The $analysis array filtered to only pieces needed for $usedAnalyzers
154     */
155    public function filterUnusedAnalysisChain( $analysis, Set $usedAnalyzers, Set $usedNormalizers ) {
156        $sets = [
157            'analyzer' => $usedAnalyzers,
158            'normalizer' => $usedNormalizers,
159            'filter' => new Set(),
160            'char_filter' => new Set(),
161            'tokenizer' => new Set(),
162        ];
163        foreach ( $analysis['analyzer'] ?? [] as $name => $config ) {
164            if ( !$usedAnalyzers->contains( $name ) ) {
165                continue;
166            }
167            foreach ( [ 'filter', 'char_filter' ] as $k ) {
168                if ( isset( $config[$k] ) ) {
169                    $sets[$k]->addAll( $config[$k] );
170                }
171            }
172            if ( isset( $config['tokenizer'] ) ) {
173                $sets['tokenizer']->add( $config['tokenizer'] );
174            }
175        }
176
177        foreach ( $analysis['normalizer'] ?? [] as $name => $config ) {
178            if ( !$usedNormalizers->contains( $name ) ) {
179                continue;
180            }
181            foreach ( [ 'filter', 'char_filter' ] as $k ) {
182                if ( isset( $config[$k] ) ) {
183                    $sets[$k]->addAll( $config[$k] );
184                }
185            }
186        }
187
188        foreach ( $sets as $k => $used ) {
189            if ( isset( $analysis[$k] ) ) {
190                $analysis[$k] = $this->filter( $analysis[$k], $used );
191            }
192        }
193
194        return $analysis;
195    }
196
197    private function recursiveKsort( array $array ): array {
198        foreach ( $array as $k => $v ) {
199            if ( is_array( $v ) ) {
200                $array[$k] = $this->recursiveKsort( $v );
201            }
202        }
203        ksort( $array );
204        return $array;
205    }
206
207    private function calcDeduplicationAliases( array $input ): array {
208        $keysByContent = [];
209        foreach ( $input as $k => $v ) {
210            $sorted = $this->recursiveKsort( $v );
211            $content = FormatJson::encode( $sorted );
212            $keysByContent[$content][] = $k;
213        }
214        $aliases = [];
215        foreach ( $keysByContent as $keys ) {
216            // Min to give a stable winner for each group.
217            $winner = min( $keys );
218            foreach ( $keys as $key ) {
219                $aliases[$key] = $winner;
220            }
221        }
222        return $aliases;
223    }
224
225    /**
226     * Remove duplicate analysis chain elements and report aliases that need
227     * to be applied to mapping configuration.
228     *
229     * This is necessary for indices such as wikibase that eagerly create
230     * analysis chains for many languages. Quite a few languages result in the
231     * same elements and this deduplication can remove a large fraction of the
232     * configuration.
233     *
234     * @param array $analysis The index.analysis field of the search index settings
235     * @return array<string[]> list of (analyzer, normalizer) map from old component name to new name.
236     */
237    public function deduplicateAnalysisConfig( array $analysis ): array {
238        // Deduplicate children first to normalize analyzer configuration.
239        foreach ( [ 'tokenizer', 'filter', 'char_filter' ] as $k ) {
240            if ( !isset( $analysis[$k] ) ) {
241                continue;
242            }
243            $aliases = $this->calcDeduplicationAliases( $analysis[$k] );
244            $analysis[$k] = $this->filter( $analysis[$k], new Set( $aliases ) );
245
246            foreach ( [ 'analyzer', 'normalizer' ] as $component ) {
247                // Push deduplications into analyzers/normalizers that reference them
248                if ( !isset( $analysis[$component] ) ) {
249                    continue;
250                }
251                foreach ( $analysis[$component] as $name => $analyzerConfig ) {
252                    if ( !isset( $analyzerConfig[$k] ) ) {
253                        continue;
254                    }
255                    if ( is_array( $analyzerConfig[$k] ) ) {
256                        // filter, char_filter
257                        foreach ( $analyzerConfig[$k] as $i => $value ) {
258                            // TODO: in theory, all values should be set already?
259                            if ( isset( $aliases[$value] ) ) {
260                                $analysis[$component][$name][$k][$i] = $aliases[$value];
261                            }
262                        }
263                    } elseif ( isset( $aliases[$analyzerConfig[$k]] ) ) {
264                        // tokenizer
265                        $analysis[$component][$name][$k] = $aliases[$analyzerConfig[$k]];
266                    }
267                }
268            }
269        }
270
271        // Once the analyzer/normalizer configuration has been normalized by deduplication
272        // we can figure out which of the analyzers are duplicates as well.
273        return [
274            $this->calcDeduplicationAliases( $analysis['analyzer'] ?? [] ),
275            $this->calcDeduplicationAliases( $analysis['normalizer'] ?? [] ),
276        ];
277    }
278
279    /**
280     * Shrink the size of the search index configuration
281     *
282     * Removes analysis chain elements that are defined but never referenced
283     * from the mappings. Optionally deduplicates elements of the analysis
284     * chain.
285     *
286     * @param array $analysis search index analysis configuration
287     * @param array $mappings search index mapping configuration
288     * @param bool $deduplicate When true deduplicate the analysis chain
289     * @param string[] $protectedAnalyzers list of named analyzers that should not be removed.
290     * @param string[] $protectedNormalizers list of named normalizers that should not be removed.
291     * @return array [$settings, $mappings]
292     */
293    public function filterAnalysis(
294        array $analysis,
295        array $mappings,
296        bool $deduplicate = false,
297        array $protectedAnalyzers = [],
298        array $protectedNormalizers = []
299    ) {
300        if ( $deduplicate ) {
301            [ $analyzerAliases, $normalizerAliases ] = $this->deduplicateAnalysisConfig( $analysis );
302            $mappings = $this->pushAnalyzerAliasesIntoMappings( $mappings, $analyzerAliases );
303            $mappings = $this->pushNormalizerAliasesIntoMappings( $mappings, $normalizerAliases );
304        }
305        $usedAnalyzers = $this->findUsedAnalyzersInMappings( $mappings );
306        $usedNormalizers = $this->findUsedNormalizersInMappings( $mappings );
307        // protected analyzers may be renamed in the mappings, but this retains them in the config as well
308        // to ensure they are available for query-time.
309        $usedAnalyzers->addAll( $protectedAnalyzers );
310        $usedNormalizers->addAll( $protectedNormalizers );
311        $analysis = $this->filterUnusedAnalysisChain( $analysis, $usedAnalyzers, $usedNormalizers );
312        return [ $analysis, $mappings ];
313    }
314}