Skip to content

Apache Lucene open-source search software

Add ThaiRepeatFilter to handle Thai Maiyamok (ๆ) reduplication (#16719) (#16720)

Kamthorn Krairaksab7c2c202ba69
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 31465cb63d4..c77499b2f48 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -127,6 +127,9 @@ New Features
pre-tokenization character normalization and token-level normalization in ThaiAnalyzer.
(Kamthorn Krairaksa)
+* GITHUB#16720: Add ThaiRepeatFilter and ThaiRepeatFilterFactory to expand Thai repetition
+ mark (Maiyamok) with exact OffsetAttribute and highlighter compatibility. (Kamthorn Krairaksa)
+
* GITHUB#16241: Add HangulCompositionCharFilter to analysis-nori for opt-in composition of
modern Hangul conjoining jamo before KoreanTokenizer. (Mingi Jeong)
diff --git a/lucene/analysis/common/src/java/module-info.java b/lucene/analysis/common/src/java/module-info.java
index ac8be52b084..003d5169725 100644
--- a/lucene/analysis/common/src/java/module-info.java
+++ b/lucene/analysis/common/src/java/module-info.java
@@ -265,6 +265,7 @@ module org.apache.lucene.analysis.common {
org.apache.lucene.analysis.te.TeluguNormalizationFilterFactory,
org.apache.lucene.analysis.te.TeluguStemFilterFactory,
org.apache.lucene.analysis.th.ThaiNormalizationFilterFactory,
+ org.apache.lucene.analysis.th.ThaiRepeatFilterFactory,
org.apache.lucene.analysis.tr.TurkishLowerCaseFilterFactory,
org.apache.lucene.analysis.util.ElisionFilterFactory;
provides org.apache.lucene.analysis.TokenizerFactory with
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiAnalyzer.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiAnalyzer.java
index 715237810af..8cbaa177a95 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiAnalyzer.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiAnalyzer.java
@@ -95,7 +95,7 @@ public final class ThaiAnalyzer extends StopwordAnalyzerBase {
*
* @return {@link org.apache.lucene.analysis.Analyzer.TokenStreamComponents} built from a {@link
* ThaiTokenizer} filtered with {@link LowerCaseFilter}, {@link DecimalDigitFilter}, {@link
- * ThaiNormalizationFilter} and {@link StopFilter}
+ * ThaiNormalizationFilter}, {@link ThaiRepeatFilter} and {@link StopFilter}
*/
@Override
protected TokenStreamComponents createComponents(String fieldName) {
@@ -103,6 +103,7 @@ public final class ThaiAnalyzer extends StopwordAnalyzerBase {
TokenStream result = new LowerCaseFilter(source);
result = new DecimalDigitFilter(result);
result = new ThaiNormalizationFilter(result);
+ result = new ThaiRepeatFilter(result);
result = new StopFilter(result, stopwords);
return new TokenStreamComponents(source, result);
}
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiRepeatFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiRepeatFilter.java
new file mode 100644
index 00000000000..1ef37ff70ae
--- /dev/null
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiRepeatFilter.java
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.th;
+
+import java.io.IOException;
+import org.apache.lucene.analysis.TokenFilter;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
+import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
+import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
+import org.apache.lucene.util.CharsRefBuilder;
+
+/**
+ * A {@link TokenFilter} that handles Thai Maiyamok (ๆ, U+0E46), which denotes word repetition
+ * (reduplication).
+ *
+ * <p>When a standalone Maiyamok token is encountered, it is replaced with the preceding term. When
+ * a token with trailing Maiyamok is encountered, trailing Maiyamok characters are stripped and
+ * duplicate token(s) are emitted.
+ */
+public final class ThaiRepeatFilter extends TokenFilter {
+
+ /** Thai Maiyamok character (ๆ) */
+ public static final char MAIYAMOK = '\u0E46';
+
+ private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
+ private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
+ private final PositionIncrementAttribute posIncAtt =
+ addAttribute(PositionIncrementAttribute.class);
+
+ private final CharsRefBuilder lastTerm = new CharsRefBuilder();
+ private int pendingRepeats = 0;
+ private int repeatIndex = 0;
+ private int[] repeatStarts = new int[4];
+ private int[] repeatEnds = new int[4];
+ private State savedState;
+
+ /**
+ * Creates a new ThaiRepeatFilter.
+ *
+ * @param input the input {@link TokenStream}
+ */
+ public ThaiRepeatFilter(TokenStream input) {
+ super(input);
+ }
+
+ @Override
+ public boolean incrementToken() throws IOException {
+ if (pendingRepeats > 0) {
+ restoreState(savedState);
+ termAtt.copyBuffer(lastTerm.chars(), 0, lastTerm.length());
+ posIncAtt.setPositionIncrement(1);
+ offsetAtt.setOffset(repeatStarts[repeatIndex], repeatEnds[repeatIndex]);
+ repeatIndex++;
+ pendingRepeats--;
+ return true;
+ }
+
+ while (input.incrementToken()) {
+ char[] buffer = termAtt.buffer();
+ int len = termAtt.length();
+ int origStart = offsetAtt.startOffset();
+ int origEnd = offsetAtt.endOffset();
+
+ // Case 1: Token consists entirely of Maiyamok characters (e.g. "ๆ" or "ๆๆ")
+ if (isAllMaiyamok(buffer, len)) {
+ if (lastTerm.length() == 0) {
+ // No preceding token (dangling Maiyamok at stream start); discard
+ continue;
+ }
+ int count = len;
+ termAtt.copyBuffer(lastTerm.chars(), 0, lastTerm.length());
+ if (count > 1) {
+ int firstEnd = Math.min(origEnd, origStart + 1);
+ offsetAtt.setOffset(origStart, firstEnd);
+ ensureRepeatCapacity(count - 1);
+ for (int i = 0; i < count - 1; i++) {
+ int s = Math.min(origEnd, origStart + 1 + i);
+ int e = (i == count - 2) ? origEnd : Math.min(origEnd, s + 1);
+ repeatStarts[i] = s;
+ repeatEnds[i] = e;
+ }
+ savedState = captureState();
+ pendingRepeats = count - 1;
+ repeatIndex = 0;
+ }
+ return true;
+ }
+
+ // Case 2: Token has trailing Maiyamok attached (e.g. "เร็วๆ")
+ int maiyamokCount = 0;
+ while (len - 1 - maiyamokCount >= 0 && buffer[len - 1 - maiyamokCount] == MAIYAMOK) {
+ maiyamokCount++;
+ }
+ if (maiyamokCount > 0) {
+ int baseLen = len - maiyamokCount;
+ termAtt.setLength(baseLen);
+ lastTerm.copyChars(termAtt.buffer(), 0, termAtt.length());
+
+ int baseEnd = Math.max(origStart, origEnd - maiyamokCount);
+ offsetAtt.setOffset(origStart, baseEnd);
+
+ ensureRepeatCapacity(maiyamokCount);
+ for (int i = 0; i < maiyamokCount; i++) {
+ int s = Math.min(origEnd, baseEnd + i);
+ int e = (i == maiyamokCount - 1) ? origEnd : Math.min(origEnd, s + 1);
+ repeatStarts[i] = s;
+ repeatEnds[i] = e;
+ }
+
+ savedState = captureState();
+ pendingRepeats = maiyamokCount;
+ repeatIndex = 0;
+ return true;
+ }
+
+ // Normal token without Maiyamok
+ lastTerm.copyChars(buffer, 0, len);
+ return true;
+ }
+
+ return false;
+ }
+
+ private void ensureRepeatCapacity(int count) {
+ if (count > repeatStarts.length) {
+ repeatStarts = new int[count];
+ repeatEnds = new int[count];
+ }
+ }
+
+ private static boolean isAllMaiyamok(char[] buffer, int len) {
+ if (len == 0) {
+ return false;
+ }
+ for (int i = 0; i < len; i++) {
+ if (buffer[i] != MAIYAMOK) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public void reset() throws IOException {
+ super.reset();
+ lastTerm.clear();
+ pendingRepeats = 0;
+ repeatIndex = 0;
+ savedState = null;
+ }
+}
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiRepeatFilterFactory.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiRepeatFilterFactory.java
new file mode 100644
index 00000000000..aab00e0deea
--- /dev/null
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/th/ThaiRepeatFilterFactory.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.th;
+
+import java.util.Map;
+import org.apache.lucene.analysis.TokenFilterFactory;
+import org.apache.lucene.analysis.TokenStream;
+
+/**
+ * Factory for {@link ThaiRepeatFilter}.
+ *
+ * <pre><code class="language-xml">
+ * &lt;fieldType name="text_th" class="solr.TextField" positionIncrementGap="100"&gt;
+ * &lt;analyzer&gt;
+ * &lt;tokenizer class="solr.ThaiTokenizerFactory"/&gt;
+ * &lt;filter class="solr.ThaiRepeatFilterFactory"/&gt;
+ * &lt;/analyzer&gt;
+ * &lt;/fieldType&gt;</code></pre>
+ *
+ * @since 11.0.0
+ * @lucene.spi {@value #NAME}
+ */
+public class ThaiRepeatFilterFactory extends TokenFilterFactory {
+
+ /** SPI name */
+ public static final String NAME = "thaiRepeat";
+
+ /** Creates a new ThaiRepeatFilterFactory */
+ public ThaiRepeatFilterFactory(Map<String, String> args) {
+ super(args);
+ if (!args.isEmpty()) {
+ throw new IllegalArgumentException("Unknown parameters: " + args);
+ }
+ }
+
+ /** Default ctor for compatibility with SPI */
+ public ThaiRepeatFilterFactory() {
+ throw defaultCtorException();
+ }
+
+ @Override
+ public TokenStream create(TokenStream input) {
+ return new ThaiRepeatFilter(input);
+ }
+}
diff --git a/lucene/analysis/common/src/resources/META-INF/services/org.apache.lucene.analysis.TokenFilterFactory b/lucene/analysis/common/src/resources/META-INF/services/org.apache.lucene.analysis.TokenFilterFactory
index b5b276803bf..8952a837f93 100644
--- a/lucene/analysis/common/src/resources/META-INF/services/org.apache.lucene.analysis.TokenFilterFactory
+++ b/lucene/analysis/common/src/resources/META-INF/services/org.apache.lucene.analysis.TokenFilterFactory
@@ -125,5 +125,6 @@ org.apache.lucene.analysis.core.FlattenGraphFilterFactory
org.apache.lucene.analysis.te.TeluguNormalizationFilterFactory
org.apache.lucene.analysis.te.TeluguStemFilterFactory
org.apache.lucene.analysis.th.ThaiNormalizationFilterFactory
+org.apache.lucene.analysis.th.ThaiRepeatFilterFactory
org.apache.lucene.analysis.tr.TurkishLowerCaseFilterFactory
org.apache.lucene.analysis.util.ElisionFilterFactory
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiAnalyzer.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiAnalyzer.java
index 58565d23293..c4aeeda47bc 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiAnalyzer.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiAnalyzer.java
@@ -147,6 +147,13 @@ public class TestThaiAnalyzer extends BaseTokenStreamTestCase {
analyzer.close();
}
+ public void testMaiyamok() throws Exception {
+ Analyzer analyzer = new ThaiAnalyzer(CharArraySet.EMPTY_SET);
+ assertAnalyzesTo(analyzer, "วิ่งเร็วๆ", new String[] {"วิ่ง", "เร็ว", "เร็ว"});
+ assertAnalyzesTo(analyzer, "พูดมากๆ นะ", new String[] {"พูด", "มาก", "มาก", "นะ"});
+ analyzer.close();
+ }
+
/** LUCENE-4253, #14730: Test that common content words in compounds are not over-filtered */
public void testCompoundAndContentWordsNotOverFiltered() throws Exception {
Analyzer analyzer = new ThaiAnalyzer();
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiRepeatFilter.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiRepeatFilter.java
new file mode 100644
index 00000000000..758f3d98280
--- /dev/null
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiRepeatFilter.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.th;
+
+import java.io.IOException;
+import java.io.StringReader;
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.Tokenizer;
+import org.apache.lucene.tests.analysis.BaseTokenStreamTestCase;
+import org.apache.lucene.tests.analysis.MockTokenizer;
+
+/** Test case for {@link ThaiRepeatFilter}. */
+public class TestThaiRepeatFilter extends BaseTokenStreamTestCase {
+
+ public void testStandaloneMaiyamok() throws IOException {
+ // Standalone token "ๆ" after "เร็ว"
+ TokenStream ts = whitespaceMockTokenizer("เร็ว ๆ");
+ ts = new ThaiRepeatFilter(ts);
+ assertTokenStreamContents(
+ ts, new String[] {"เร็ว", "เร็ว"}, new int[] {0, 5}, new int[] {4, 6});
+ }
+
+ public void testAttachedMaiyamok() throws IOException {
+ // Attached "ๆ" at the end of word "เร็วๆ"
+ TokenStream ts = whitespaceMockTokenizer("เร็วๆ");
+ ts = new ThaiRepeatFilter(ts);
+ assertTokenStreamContents(
+ ts, new String[] {"เร็ว", "เร็ว"}, new int[] {0, 4}, new int[] {4, 5});
+ }
+
+ public void testMultipleMaiyamok() throws IOException {
+ // Double Maiyamok "มากๆๆ"
+ TokenStream ts = whitespaceMockTokenizer("มากๆๆ");
+ ts = new ThaiRepeatFilter(ts);
+ assertTokenStreamContents(
+ ts, new String[] {"มาก", "มาก", "มาก"}, new int[] {0, 3, 4}, new int[] {3, 4, 5});
+
+ // Separate tokens "มาก ๆ ๆ"
+ ts = whitespaceMockTokenizer("มาก ๆ ๆ");
+ ts = new ThaiRepeatFilter(ts);
+ assertTokenStreamContents(
+ ts, new String[] {"มาก", "มาก", "มาก"}, new int[] {0, 4, 6}, new int[] {3, 5, 7});
+ }
+
+ public void testInSentence() throws IOException {
+ TokenStream ts = whitespaceMockTokenizer("เด็ก ๆ กำลัง วิ่ง เล่น");
+ ts = new ThaiRepeatFilter(ts);
+ assertTokenStreamContents(
+ ts,
+ new String[] {"เด็ก", "เด็ก", "กำลัง", "วิ่ง", "เล่น"},
+ new int[] {0, 5, 7, 13, 18},
+ new int[] {4, 6, 12, 17, 22});
+ }
+
+ public void testLeadingDanglingMaiyamok() throws IOException {
+ // Maiyamok at stream start with no preceding token
+ TokenStream ts = whitespaceMockTokenizer("ๆ ครับ");
+ ts = new ThaiRepeatFilter(ts);
+ assertTokenStreamContents(ts, new String[] {"ครับ"});
+ }
+
+ public void testEmpty() throws IOException {
+ TokenStream ts = whitespaceMockTokenizer("");
+ ts = new ThaiRepeatFilter(ts);
+ assertTokenStreamContents(ts, new String[] {});
+ }
+
+ public void testWithThaiTokenizer() throws IOException {
+ assumeTrue(
+ "JRE does not support Thai dictionary-based BreakIterator", ThaiTokenizer.DBBI_AVAILABLE);
+ Tokenizer tokenizer = new ThaiTokenizer();
+ tokenizer.setReader(new StringReader("วิ่งเร็วๆ"));
+ TokenStream ts = new ThaiRepeatFilter(tokenizer);
+ assertTokenStreamContents(
+ ts, new String[] {"วิ่ง", "เร็ว", "เร็ว"}, new int[] {0, 4, 8}, new int[] {4, 8, 9});
+ }
+
+ public void testRandomStrings() throws IOException {
+ Analyzer a =
+ new Analyzer() {
+ @Override
+ protected TokenStreamComponents createComponents(String fieldName) {
+ Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
+ return new TokenStreamComponents(tokenizer, new ThaiRepeatFilter(tokenizer));
+ }
+ };
+ checkRandomData(random(), a, 200 * RANDOM_MULTIPLIER);
+ a.close();
+ }
+}
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiRepeatFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiRepeatFilterFactory.java
new file mode 100644
index 00000000000..dc925398bfc
--- /dev/null
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiRepeatFilterFactory.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.th;
+
+import java.io.Reader;
+import java.io.StringReader;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.Tokenizer;
+import org.apache.lucene.tests.analysis.BaseTokenStreamFactoryTestCase;
+import org.apache.lucene.tests.analysis.MockTokenizer;
+
+/** Simple tests to ensure the Thai repeat factory is working. */
+public class TestThaiRepeatFilterFactory extends BaseTokenStreamFactoryTestCase {
+
+ public void testRepeat() throws Exception {
+ Reader reader = new StringReader("เร็ว ๆ");
+ TokenStream stream = new MockTokenizer(MockTokenizer.WHITESPACE, false);
+ ((Tokenizer) stream).setReader(reader);
+ stream = tokenFilterFactory("ThaiRepeat").create(stream);
+ assertTokenStreamContents(stream, new String[] {"เร็ว", "เร็ว"});
+ }
+
+ /** Test that bogus arguments result in exception */
+ public void testBogusArguments() throws Exception {
+ IllegalArgumentException expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ tokenFilterFactory("ThaiRepeat", "bogusArg", "bogusValue");
+ });
+ assertTrue(expected.getMessage().contains("Unknown parameters"));
+ }
+}