Skip to content

Commit 2da2305

Browse files
authored
Backport of lowercase normalizer PR #53882
A pre-configured normalizer for lower-casing. Closes #53872
1 parent 9f22c0d commit 2da2305

File tree

8 files changed

+150
-9
lines changed

8 files changed

+150
-9
lines changed

docs/reference/analysis/normalizers.asciidoc

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,13 @@ following: `arabic_normalization`, `asciifolding`, `bengali_normalization`,
1313
`persian_normalization`, `scandinavian_folding`, `serbian_normalization`,
1414
`sorani_normalization`, `uppercase`.
1515

16+
Elasticsearch ships with a `lowercase` built-in normalizer. For other forms of
17+
normalization a custom configuration is required.
18+
1619
[float]
1720
=== Custom normalizers
1821

19-
Elasticsearch does not ship with built-in normalizers so far, so the only way
20-
to get one is by building a custom one. Custom normalizers take a list of char
22+
Custom normalizers take a list of
2123
<<analysis-charfilters, character filters>> and a list of
2224
<<analysis-tokenfilters,token filters>>.
2325

docs/reference/mapping/params/normalizer.asciidoc

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,13 @@ produces a single token.
77

88
The `normalizer` is applied prior to indexing the keyword, as well as at
99
search-time when the `keyword` field is searched via a query parser such as
10-
the <<query-dsl-match-query,`match`>> query or via a term-level query
10+
the <<query-dsl-match-query,`match`>> query or via a term-level query
1111
such as the <<query-dsl-term-query,`term`>> query.
1212

13+
A simple normalizer called `lowercase` ships with elasticsearch and can be used.
14+
Custom normalizers can be defined as part of analysis settings as follows.
15+
16+
1317
[source,console]
1418
--------------------------------
1519
PUT index

server/src/main/java/org/elasticsearch/index/analysis/AnalysisRegistry.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,6 @@ private Map<String, AnalyzerProvider<?>> buildAnalyzerFactories(IndexSettings in
299299

300300
private Map<String, AnalyzerProvider<?>> buildNormalizerFactories(IndexSettings indexSettings) throws IOException {
301301
final Map<String, Settings> normalizersSettings = indexSettings.getSettings().getGroups("index.analysis.normalizer");
302-
// TODO: Have pre-built normalizers
303302
return buildMapping(Component.NORMALIZER, indexSettings, normalizersSettings, normalizers, Collections.emptyMap());
304303
}
305304

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package org.elasticsearch.index.analysis;
21+
22+
import org.apache.lucene.analysis.Analyzer;
23+
import org.apache.lucene.analysis.LowerCaseFilter;
24+
import org.apache.lucene.analysis.TokenStream;
25+
import org.apache.lucene.analysis.Tokenizer;
26+
import org.apache.lucene.analysis.core.KeywordTokenizer;
27+
28+
/** Normalizer used to lowercase values */
29+
public final class LowercaseNormalizer extends Analyzer {
30+
31+
@Override
32+
protected TokenStreamComponents createComponents(String s) {
33+
final Tokenizer tokenizer = new KeywordTokenizer();
34+
TokenStream stream = new LowerCaseFilter(tokenizer);
35+
return new TokenStreamComponents(tokenizer, stream);
36+
}
37+
38+
@Override
39+
protected TokenStream normalize(String fieldName, TokenStream in) {
40+
return new LowerCaseFilter(in);
41+
}
42+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
21+
package org.elasticsearch.index.analysis;
22+
23+
import org.elasticsearch.common.settings.Settings;
24+
import org.elasticsearch.env.Environment;
25+
import org.elasticsearch.index.IndexSettings;
26+
27+
28+
/**
29+
* Builds an analyzer for normalization that lowercases terms.
30+
*/
31+
public class LowercaseNormalizerProvider extends AbstractIndexAnalyzerProvider<LowercaseNormalizer> {
32+
33+
private final LowercaseNormalizer analyzer;
34+
35+
public LowercaseNormalizerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings) {
36+
super(indexSettings, name, settings);
37+
this.analyzer = new LowercaseNormalizer();
38+
}
39+
40+
@Override
41+
public LowercaseNormalizer get() {
42+
return analyzer;
43+
}
44+
}

server/src/main/java/org/elasticsearch/indices/analysis/AnalysisModule.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import org.elasticsearch.index.analysis.CharFilterFactory;
3636
import org.elasticsearch.index.analysis.HunspellTokenFilterFactory;
3737
import org.elasticsearch.index.analysis.KeywordAnalyzerProvider;
38+
import org.elasticsearch.index.analysis.LowercaseNormalizerProvider;
3839
import org.elasticsearch.index.analysis.PreBuiltAnalyzerProviderFactory;
3940
import org.elasticsearch.index.analysis.PreConfiguredCharFilter;
4041
import org.elasticsearch.index.analysis.PreConfiguredTokenFilter;
@@ -250,7 +251,7 @@ private NamedRegistry<AnalysisProvider<AnalyzerProvider<?>>> setupAnalyzers(List
250251

251252
private NamedRegistry<AnalysisProvider<AnalyzerProvider<?>>> setupNormalizers(List<AnalysisPlugin> plugins) {
252253
NamedRegistry<AnalysisProvider<AnalyzerProvider<?>>> normalizers = new NamedRegistry<>("normalizer");
253-
// TODO: provide built-in normalizer providers?
254+
normalizers.register("lowercase", LowercaseNormalizerProvider::new);
254255
// TODO: pluggability?
255256
return normalizers;
256257
}

server/src/test/java/org/elasticsearch/index/analysis/AnalysisRegistryTests.java

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,13 @@
2020
package org.elasticsearch.index.analysis;
2121

2222
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
23+
2324
import org.apache.lucene.analysis.Analyzer;
2425
import org.apache.lucene.analysis.MockTokenFilter;
2526
import org.apache.lucene.analysis.TokenStream;
2627
import org.apache.lucene.analysis.Tokenizer;
2728
import org.apache.lucene.analysis.en.EnglishAnalyzer;
29+
import org.apache.lucene.analysis.reverse.ReverseStringFilter;
2830
import org.apache.lucene.analysis.standard.StandardAnalyzer;
2931
import org.apache.lucene.analysis.standard.StandardTokenizer;
3032
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
@@ -39,13 +41,15 @@
3941
import org.elasticsearch.indices.analysis.AnalysisModule.AnalysisProvider;
4042
import org.elasticsearch.indices.analysis.PreBuiltAnalyzers;
4143
import org.elasticsearch.plugins.AnalysisPlugin;
44+
import org.elasticsearch.plugins.Plugin;
4245
import org.elasticsearch.test.ESTestCase;
4346
import org.elasticsearch.test.IndexSettingsModule;
4447
import org.elasticsearch.test.VersionUtils;
4548

4649
import java.io.IOException;
4750
import java.util.Collections;
4851
import java.util.HashMap;
52+
import java.util.List;
4953
import java.util.Map;
5054

5155
import static java.util.Collections.emptyMap;
@@ -58,6 +62,7 @@
5862

5963
public class AnalysisRegistryTests extends ESTestCase {
6064
private AnalysisRegistry emptyRegistry;
65+
private AnalysisRegistry nonEmptyRegistry;
6166

6267
private static AnalyzerProvider<?> analyzerProvider(final String name) {
6368
return new PreBuiltAnalyzerProvider(name, AnalyzerScope.INDEX, new EnglishAnalyzer());
@@ -68,6 +73,16 @@ private static AnalysisRegistry emptyAnalysisRegistry(Settings settings) {
6873
emptyMap(), emptyMap(), emptyMap(), emptyMap());
6974
}
7075

76+
/**
77+
* Creates a reverse filter available for use in testNameClashNormalizer test
78+
*/
79+
public static class MockAnalysisPlugin extends Plugin implements AnalysisPlugin {
80+
@Override
81+
public List<PreConfiguredTokenFilter> getPreConfiguredTokenFilters() {
82+
return singletonList(PreConfiguredTokenFilter.singleton("reverse", true, ReverseStringFilter::new));
83+
}
84+
}
85+
7186
private static IndexSettings indexSettingsOfCurrentVersion(Settings.Builder settings) {
7287
return IndexSettingsModule.newIndexSettings("index", settings
7388
.put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
@@ -77,9 +92,13 @@ private static IndexSettings indexSettingsOfCurrentVersion(Settings.Builder sett
7792
@Override
7893
public void setUp() throws Exception {
7994
super.setUp();
80-
emptyRegistry = emptyAnalysisRegistry(Settings.builder()
95+
Settings settings = Settings.builder()
8196
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
82-
.build());
97+
.build();
98+
emptyRegistry = emptyAnalysisRegistry(settings);
99+
// Module loaded to register in-built normalizers for testing
100+
AnalysisModule module = new AnalysisModule(TestEnvironment.newEnvironment(settings), singletonList(new MockAnalysisPlugin()));
101+
nonEmptyRegistry = module.getAnalysisRegistry();
83102
}
84103

85104
public void testDefaultAnalyzers() throws IOException {
@@ -135,7 +154,29 @@ public Tokenizer create() {
135154
emptyMap(), emptyMap(), emptyMap()));
136155
assertEquals("analyzer [default] contains filters [my_filter] that are not allowed to run in all mode.", ex.getMessage());
137156
}
157+
158+
159+
public void testNameClashNormalizer() throws IOException {
160+
161+
// Test out-of-the-box normalizer works OK.
162+
IndexAnalyzers indexAnalyzers = nonEmptyRegistry.build(IndexSettingsModule.newIndexSettings("index", Settings.EMPTY));
163+
assertNotNull(indexAnalyzers.getNormalizer("lowercase"));
164+
assertThat(indexAnalyzers.getNormalizer("lowercase").normalize("field", "AbC").utf8ToString(), equalTo("abc"));
165+
166+
// Test that a name clash with a custom normalizer will favour the index's normalizer rather than the out-of-the-box
167+
// one of the same name. (However this "feature" will be removed with https://github.com/elastic/elasticsearch/issues/22263 )
168+
Settings settings = Settings.builder()
169+
// Deliberately bad choice of normalizer name for the job it does.
170+
.put("index.analysis.normalizer.lowercase.type", "custom")
171+
.putList("index.analysis.normalizer.lowercase.filter", "reverse")
172+
.build();
173+
174+
indexAnalyzers = nonEmptyRegistry.build(IndexSettingsModule.newIndexSettings("index", settings));
175+
assertNotNull(indexAnalyzers.getNormalizer("lowercase"));
176+
assertThat(indexAnalyzers.getNormalizer("lowercase").normalize("field","AbC").utf8ToString(), equalTo("CbA"));
177+
}
138178

179+
139180
public void testOverrideDefaultIndexAnalyzerIsUnsupported() {
140181
Version version = VersionUtils.randomVersionBetween(random(), Version.V_6_0_0_alpha1, Version.CURRENT);
141182
Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, version).build();

server/src/test/java/org/elasticsearch/index/mapper/KeywordFieldMapperTests.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -344,10 +344,18 @@ public void testEnableNorms() throws IOException {
344344
assertEquals(0, fieldNamesFields.length);
345345
}
346346

347-
public void testNormalizer() throws IOException {
347+
public void testCustomNormalizer() throws IOException {
348+
checkLowercaseNormalizer("my_lowercase");
349+
}
350+
351+
public void testInBuiltNormalizer() throws IOException {
352+
checkLowercaseNormalizer("lowercase");
353+
}
354+
355+
public void checkLowercaseNormalizer(String normalizerName) throws IOException {
348356
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
349357
.startObject("properties").startObject("field")
350-
.field("type", "keyword").field("normalizer", "my_lowercase").endObject().endObject()
358+
.field("type", "keyword").field("normalizer", normalizerName).endObject().endObject()
351359
.endObject().endObject());
352360

353361
DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));

0 commit comments

Comments
 (0)