Skip to content

Apache Lucene open-source search software

LUCENE-6400: preserve original token when possible in SolrSynonymParser

Michael McCandlessf9e71c7eec46
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 9b9a6060dc6..64b48251d74 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -105,6 +105,10 @@ Bug Fixes
* LUCENE-6345: Null check terms/fields in Lucene queries (Lee
Hinman via Mike McCandless)
+* LUCENE-6400: SolrSynonymParser should preserve original token instead
+ of replacing it with a synonym, when expand=true and there is no
+ explicit mapping (Ian Ribas, Robert Muir, Mike McCandless)
+
API Changes
* LUCENE-6377: SearcherFactory#newSearcher now accepts the previous reader
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SolrSynonymParser.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SolrSynonymParser.java
index c89c538cb9c..18980896c28 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SolrSynonymParser.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SolrSynonymParser.java
@@ -84,9 +84,6 @@ public class SolrSynonymParser extends SynonymMap.Parser {
continue; // ignore empty lines and comments
}
- CharsRef inputs[];
- CharsRef outputs[];
-
// TODO: we could process this more efficiently.
String sides[] = split(line, "=>");
if (sides.length > 1) { // explicit mapping
@@ -94,37 +91,45 @@ public class SolrSynonymParser extends SynonymMap.Parser {
throw new IllegalArgumentException("more than one explicit mapping specified on the same line");
}
String inputStrings[] = split(sides[0], ",");
- inputs = new CharsRef[inputStrings.length];
+ CharsRef[] inputs = new CharsRef[inputStrings.length];
for (int i = 0; i < inputs.length; i++) {
inputs[i] = analyze(unescape(inputStrings[i]).trim(), new CharsRefBuilder());
}
String outputStrings[] = split(sides[1], ",");
- outputs = new CharsRef[outputStrings.length];
+ CharsRef[] outputs = new CharsRef[outputStrings.length];
for (int i = 0; i < outputs.length; i++) {
outputs[i] = analyze(unescape(outputStrings[i]).trim(), new CharsRefBuilder());
}
+ // these mappings are explicit and never preserve original
+ for (int i = 0; i < inputs.length; i++) {
+ for (int j = 0; j < outputs.length; j++) {
+ add(inputs[i], outputs[j], false);
+ }
+ }
} else {
String inputStrings[] = split(line, ",");
- inputs = new CharsRef[inputStrings.length];
+ CharsRef[] inputs = new CharsRef[inputStrings.length];
for (int i = 0; i < inputs.length; i++) {
inputs[i] = analyze(unescape(inputStrings[i]).trim(), new CharsRefBuilder());
}
if (expand) {
- outputs = inputs;
+ // all pairs
+ for (int i = 0; i < inputs.length; i++) {
+ for (int j = 0; j < inputs.length; j++) {
+ if (i != j) {
+ add(inputs[i], inputs[j], true);
+ }
+ }
+ }
} else {
- outputs = new CharsRef[1];
- outputs[0] = inputs[0];
- }
- }
-
- // currently we include the term itself in the map,
- // and use includeOrig = false always.
- // this is how the existing filter does it, but it's actually a bug,
- // especially if combined with ignoreCase = true
- for (int i = 0; i < inputs.length; i++) {
- for (int j = 0; j < outputs.length; j++) {
- add(inputs[i], outputs[j], false);
+ // all subsequent inputs map to first one; we also add inputs[0] here
+ // so that we "effectively" (because we remove the original input and
+ // add back a synonym with the same text) change that token's type to
+ // SYNONYM (matching legacy behavior):
+ for (int i = 0; i < inputs.length; i++) {
+ add(inputs[i], inputs[0], false);
+ }
}
}
}
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/BaseSynonymParserTestCase.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/BaseSynonymParserTestCase.java
new file mode 100644
index 00000000000..1c80fc63978
--- /dev/null
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/BaseSynonymParserTestCase.java
@@ -0,0 +1,93 @@
+package org.apache.lucene.analysis.synonym;
+
+/*
+ * 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.
+ */
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.BaseTokenStreamTestCase;
+import org.apache.lucene.store.ByteArrayDataInput;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.IntsRefBuilder;
+import org.apache.lucene.util.fst.Util;
+
+/**
+ * Base class for testing synonym parsers.
+ */
+public abstract class BaseSynonymParserTestCase extends BaseTokenStreamTestCase {
+ /**
+ * Helper method to validate synonym parsing.
+ *
+ * @param synonynMap the generated synonym map after parsing
+ * @param word word (phrase) we are validating the synonyms for. Should be the value that comes out of the analyzer.
+ * All spaces will be replaced by word separators.
+ * @param includeOrig if synonyms should include original
+ * @param synonyms actual synonyms. All word separators are replaced with a single space.
+ */
+ public static void assertEntryEquals(SynonymMap synonynMap, String word, boolean includeOrig, String[] synonyms)
+ throws Exception {
+ word = word.replace(' ', SynonymMap.WORD_SEPARATOR);
+ BytesRef value = Util.get(synonynMap.fst, Util.toUTF32(new CharsRef(word), new IntsRefBuilder()));
+ assertNotNull("No synonyms found for: " + word, value);
+
+ ByteArrayDataInput bytesReader = new ByteArrayDataInput(value.bytes, value.offset, value.length);
+ final int code = bytesReader.readVInt();
+
+ final boolean keepOrig = (code & 0x1) == 0;
+ assertEquals("Include original different than expected. Expected " + includeOrig + " was " + keepOrig,
+ includeOrig, keepOrig);
+
+ final int count = code >>> 1;
+ assertEquals("Invalid synonym count. Expected " + synonyms.length + " was " + count,
+ synonyms.length, count);
+
+ Set<String> synonymSet = new HashSet<>(Arrays.asList(synonyms));
+
+ BytesRef scratchBytes = new BytesRef();
+ for (int i = 0; i < count; i++) {
+ synonynMap.words.get(bytesReader.readVInt(), scratchBytes);
+ String synonym = scratchBytes.utf8ToString().replace(SynonymMap.WORD_SEPARATOR, ' ');
+ assertTrue("Unexpected synonym found: " + synonym, synonymSet.contains(synonym));
+ }
+ }
+
+ /**
+ * Validates that there are no synonyms for the given word.
+ * @param synonynMap the generated synonym map after parsing
+ * @param word word (phrase) we are validating the synonyms for. Should be the value that comes out of the analyzer.
+ * All spaces will be replaced by word separators.
+ */
+ public static void assertEntryAbsent(SynonymMap synonynMap, String word) throws IOException {
+ word = word.replace(' ', SynonymMap.WORD_SEPARATOR);
+ BytesRef value = Util.get(synonynMap.fst, Util.toUTF32(new CharsRef(word), new IntsRefBuilder()));
+ assertNull("There should be no synonyms for: " + word, value);
+ }
+
+ public static void assertEntryEquals(SynonymMap synonynMap, String word, boolean includeOrig, String synonym)
+ throws Exception {
+ assertEntryEquals(synonynMap, word, includeOrig, new String[]{synonym});
+ }
+
+ public static void assertAnalyzesToPositions(Analyzer a, String input, String[] output, String[] types, int[] posIncrements, int[] posLengths) throws IOException {
+ assertAnalyzesTo(a, input, output, null, null, types, posIncrements, posLengths);
+ }
+}
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSolrSynonymParser.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSolrSynonymParser.java
index 66d0aad2124..82e5958fe85 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSolrSynonymParser.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSolrSynonymParser.java
@@ -21,7 +21,6 @@ import java.io.StringReader;
import java.text.ParseException;
import org.apache.lucene.analysis.Analyzer;
-import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.Tokenizer;
@@ -31,7 +30,7 @@ import org.apache.lucene.analysis.en.EnglishAnalyzer;
* Tests parser for the Solr synonyms format
* @lucene.experimental
*/
-public class TestSolrSynonymParser extends BaseTokenStreamTestCase {
+public class TestSolrSynonymParser extends BaseSynonymParserTestCase {
/** Tests some simple examples from the solr wiki */
public void testSimple() throws Exception {
@@ -174,4 +173,61 @@ public class TestSolrSynonymParser extends BaseTokenStreamTestCase {
new int[] { 1 });
analyzer.close();
}
+
+ /** Verify type of token and positionLength after analyzer. */
+ public void testPositionLengthAndTypeSimple() throws Exception {
+ String testFile =
+ "spider man, spiderman";
+
+ Analyzer analyzer = new MockAnalyzer(random());
+ SolrSynonymParser parser = new SolrSynonymParser(true, true, analyzer);
+ parser.parse(new StringReader(testFile));
+ final SynonymMap map = parser.build();
+ analyzer.close();
+
+ analyzer = new Analyzer() {
+ @Override
+ protected TokenStreamComponents createComponents(String fieldName) {
+ Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, true);
+ return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
+ }
+ };
+
+ assertAnalyzesToPositions(analyzer, "spider man",
+ new String[]{"spider", "spiderman", "man"},
+ new String[]{"word", "SYNONYM", "word"},
+ new int[]{1, 0, 1},
+ new int[]{1, 2, 1});
+ }
+
+ /** Test parsing of simple examples. */
+ public void testParseSimple() throws Exception {
+ String testFile =
+ "spider man, spiderman\n" +
+ "usa,united states,u s a,united states of america\n"+
+ "mystyped, mistyped => mistyped\n" +
+ "foo => foo bar\n" +
+ "foo => baz";
+
+ Analyzer analyzer = new MockAnalyzer(random());
+ SolrSynonymParser parser = new SolrSynonymParser(true, true, analyzer);
+ parser.parse(new StringReader(testFile));
+ final SynonymMap map = parser.build();
+ analyzer.close();
+
+ assertEntryEquals(map, "spiderman", true, "spider man");
+ assertEntryEquals(map, "spider man", true, "spiderman");
+
+ assertEntryEquals(map, "usa", true, new String[] {"united states", "u s a", "united states of america"});
+ assertEntryEquals(map, "united states", true, new String[] {"usa", "u s a", "united states of america"});
+ assertEntryEquals(map, "u s a", true, new String[] {"usa", "united states", "united states of america"});
+ assertEntryEquals(map, "united states of america", true, new String[] {"usa", "u s a", "united states"});
+
+ assertEntryEquals(map, "mistyped", false, "mistyped");
+ assertEntryEquals(map, "mystyped", false, "mistyped");
+
+ assertEntryEquals(map, "foo", false, new String[]{"foo bar", "baz"});
+ assertEntryAbsent(map, "baz");
+ assertEntryAbsent(map, "bar");
+ }
}