Skip to content

Apache Lucene open-source search software

LUCENE-5111: Fix WordDelimiterFilter offsets

Robert Muir0bba517d9397
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 3d23acb9bbe..4ffc3c58a9c 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -215,6 +215,8 @@ Bug fixes
indexed shapes within 1/2 maxDistErr from the edge of the query shape. This meant
searching for a point by the same point as a query rarely worked. (David Smiley)
+* LUCENE-5111: Fix WordDelimiterFilter to return offsets in correct order. (Robert Muir)
+
Test Framework
* LUCENE-5449: Rename _TestUtil and _TestHelper to remove the leading _.
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/Lucene47WordDelimiterFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/Lucene47WordDelimiterFilter.java
new file mode 100644
index 00000000000..6cf312fdfb6
--- /dev/null
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/Lucene47WordDelimiterFilter.java
@@ -0,0 +1,556 @@
+/*
+ * 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.miscellaneous;
+
+import org.apache.lucene.analysis.TokenFilter;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.core.WhitespaceTokenizer;
+import org.apache.lucene.analysis.standard.StandardTokenizer;
+import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
+import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
+import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
+import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
+import org.apache.lucene.analysis.util.CharArraySet;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.RamUsageEstimator;
+
+import java.io.IOException;
+
+/**
+ * Old Broken version of {@link WordDelimiterFilter}
+ */
+@Deprecated
+public final class Lucene47WordDelimiterFilter extends TokenFilter {
+
+ public static final int LOWER = 0x01;
+ public static final int UPPER = 0x02;
+ public static final int DIGIT = 0x04;
+ public static final int SUBWORD_DELIM = 0x08;
+
+ // combinations: for testing, not for setting bits
+ public static final int ALPHA = 0x03;
+ public static final int ALPHANUM = 0x07;
+
+ /**
+ * Causes parts of words to be generated:
+ * <p/>
+ * "PowerShot" => "Power" "Shot"
+ */
+ public static final int GENERATE_WORD_PARTS = 1;
+
+ /**
+ * Causes number subwords to be generated:
+ * <p/>
+ * "500-42" => "500" "42"
+ */
+ public static final int GENERATE_NUMBER_PARTS = 2;
+
+ /**
+ * Causes maximum runs of word parts to be catenated:
+ * <p/>
+ * "wi-fi" => "wifi"
+ */
+ public static final int CATENATE_WORDS = 4;
+
+ /**
+ * Causes maximum runs of word parts to be catenated:
+ * <p/>
+ * "wi-fi" => "wifi"
+ */
+ public static final int CATENATE_NUMBERS = 8;
+
+ /**
+ * Causes all subword parts to be catenated:
+ * <p/>
+ * "wi-fi-4000" => "wifi4000"
+ */
+ public static final int CATENATE_ALL = 16;
+
+ /**
+ * Causes original words are preserved and added to the subword list (Defaults to false)
+ * <p/>
+ * "500-42" => "500" "42" "500-42"
+ */
+ public static final int PRESERVE_ORIGINAL = 32;
+
+ /**
+ * If not set, causes case changes to be ignored (subwords will only be generated
+ * given SUBWORD_DELIM tokens)
+ */
+ public static final int SPLIT_ON_CASE_CHANGE = 64;
+
+ /**
+ * If not set, causes numeric changes to be ignored (subwords will only be generated
+ * given SUBWORD_DELIM tokens).
+ */
+ public static final int SPLIT_ON_NUMERICS = 128;
+
+ /**
+ * Causes trailing "'s" to be removed for each subword
+ * <p/>
+ * "O'Neil's" => "O", "Neil"
+ */
+ public static final int STEM_ENGLISH_POSSESSIVE = 256;
+
+ /**
+ * If not null is the set of tokens to protect from being delimited
+ *
+ */
+ final CharArraySet protWords;
+
+ private final int flags;
+
+ private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);
+ private final OffsetAttribute offsetAttribute = addAttribute(OffsetAttribute.class);
+ private final PositionIncrementAttribute posIncAttribute = addAttribute(PositionIncrementAttribute.class);
+ private final TypeAttribute typeAttribute = addAttribute(TypeAttribute.class);
+
+ // used for iterating word delimiter breaks
+ private final WordDelimiterIterator iterator;
+
+ // used for concatenating runs of similar typed subwords (word,number)
+ private final WordDelimiterConcatenation concat = new WordDelimiterConcatenation();
+ // number of subwords last output by concat.
+ private int lastConcatCount = 0;
+
+ // used for catenate all
+ private final WordDelimiterConcatenation concatAll = new WordDelimiterConcatenation();
+
+ // used for accumulating position increment gaps
+ private int accumPosInc = 0;
+
+ private char savedBuffer[] = new char[1024];
+ private int savedStartOffset;
+ private int savedEndOffset;
+ private String savedType;
+ private boolean hasSavedState = false;
+ // if length by start + end offsets doesn't match the term text then assume
+ // this is a synonym and don't adjust the offsets.
+ private boolean hasIllegalOffsets = false;
+
+ // for a run of the same subword type within a word, have we output anything?
+ private boolean hasOutputToken = false;
+ // when preserve original is on, have we output any token following it?
+ // this token must have posInc=0!
+ private boolean hasOutputFollowingOriginal = false;
+
+ /**
+ * Creates a new WordDelimiterFilter
+ *
+ * @param in TokenStream to be filtered
+ * @param charTypeTable table containing character types
+ * @param configurationFlags Flags configuring the filter
+ * @param protWords If not null is the set of tokens to protect from being delimited
+ */
+ public Lucene47WordDelimiterFilter(TokenStream in, byte[] charTypeTable, int configurationFlags, CharArraySet protWords) {
+ super(in);
+ this.flags = configurationFlags;
+ this.protWords = protWords;
+ this.iterator = new WordDelimiterIterator(
+ charTypeTable, has(SPLIT_ON_CASE_CHANGE), has(SPLIT_ON_NUMERICS), has(STEM_ENGLISH_POSSESSIVE));
+ }
+
+ /**
+ * Creates a new WordDelimiterFilter using {@link WordDelimiterIterator#DEFAULT_WORD_DELIM_TABLE}
+ * as its charTypeTable
+ *
+ * @param in TokenStream to be filtered
+ * @param configurationFlags Flags configuring the filter
+ * @param protWords If not null is the set of tokens to protect from being delimited
+ */
+ public Lucene47WordDelimiterFilter(TokenStream in, int configurationFlags, CharArraySet protWords) {
+ this(in, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, configurationFlags, protWords);
+ }
+
+ @Override
+ public boolean incrementToken() throws IOException {
+ while (true) {
+ if (!hasSavedState) {
+ // process a new input word
+ if (!input.incrementToken()) {
+ return false;
+ }
+
+ int termLength = termAttribute.length();
+ char[] termBuffer = termAttribute.buffer();
+
+ accumPosInc += posIncAttribute.getPositionIncrement();
+
+ iterator.setText(termBuffer, termLength);
+ iterator.next();
+
+ // word of no delimiters, or protected word: just return it
+ if ((iterator.current == 0 && iterator.end == termLength) ||
+ (protWords != null && protWords.contains(termBuffer, 0, termLength))) {
+ posIncAttribute.setPositionIncrement(accumPosInc);
+ accumPosInc = 0;
+ return true;
+ }
+
+ // word of simply delimiters
+ if (iterator.end == WordDelimiterIterator.DONE && !has(PRESERVE_ORIGINAL)) {
+ // if the posInc is 1, simply ignore it in the accumulation
+ if (posIncAttribute.getPositionIncrement() == 1) {
+ accumPosInc--;
+ }
+ continue;
+ }
+
+ saveState();
+
+ hasOutputToken = false;
+ hasOutputFollowingOriginal = !has(PRESERVE_ORIGINAL);
+ lastConcatCount = 0;
+
+ if (has(PRESERVE_ORIGINAL)) {
+ posIncAttribute.setPositionIncrement(accumPosInc);
+ accumPosInc = 0;
+ return true;
+ }
+ }
+
+ // at the end of the string, output any concatenations
+ if (iterator.end == WordDelimiterIterator.DONE) {
+ if (!concat.isEmpty()) {
+ if (flushConcatenation(concat)) {
+ return true;
+ }
+ }
+
+ if (!concatAll.isEmpty()) {
+ // only if we haven't output this same combo above!
+ if (concatAll.subwordCount > lastConcatCount) {
+ concatAll.writeAndClear();
+ return true;
+ }
+ concatAll.clear();
+ }
+
+ // no saved concatenations, on to the next input word
+ hasSavedState = false;
+ continue;
+ }
+
+ // word surrounded by delimiters: always output
+ if (iterator.isSingleWord()) {
+ generatePart(true);
+ iterator.next();
+ return true;
+ }
+
+ int wordType = iterator.type();
+
+ // do we already have queued up incompatible concatenations?
+ if (!concat.isEmpty() && (concat.type & wordType) == 0) {
+ if (flushConcatenation(concat)) {
+ hasOutputToken = false;
+ return true;
+ }
+ hasOutputToken = false;
+ }
+
+ // add subwords depending upon options
+ if (shouldConcatenate(wordType)) {
+ if (concat.isEmpty()) {
+ concat.type = wordType;
+ }
+ concatenate(concat);
+ }
+
+ // add all subwords (catenateAll)
+ if (has(CATENATE_ALL)) {
+ concatenate(concatAll);
+ }
+
+ // if we should output the word or number part
+ if (shouldGenerateParts(wordType)) {
+ generatePart(false);
+ iterator.next();
+ return true;
+ }
+
+ iterator.next();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void reset() throws IOException {
+ super.reset();
+ hasSavedState = false;
+ concat.clear();
+ concatAll.clear();
+ accumPosInc = 0;
+ }
+
+ // ================================================= Helper Methods ================================================
+
+ /**
+ * Saves the existing attribute states
+ */
+ private void saveState() {
+ // otherwise, we have delimiters, save state
+ savedStartOffset = offsetAttribute.startOffset();
+ savedEndOffset = offsetAttribute.endOffset();
+ // if length by start + end offsets doesn't match the term text then assume this is a synonym and don't adjust the offsets.
+ hasIllegalOffsets = (savedEndOffset - savedStartOffset != termAttribute.length());
+ savedType = typeAttribute.type();
+
+ if (savedBuffer.length < termAttribute.length()) {
+ savedBuffer = new char[ArrayUtil.oversize(termAttribute.length(), RamUsageEstimator.NUM_BYTES_CHAR)];
+ }
+
+ System.arraycopy(termAttribute.buffer(), 0, savedBuffer, 0, termAttribute.length());
+ iterator.text = savedBuffer;
+
+ hasSavedState = true;
+ }
+
+ /**
+ * Flushes the given WordDelimiterConcatenation by either writing its concat and then clearing, or just clearing.
+ *
+ * @param concatenation WordDelimiterConcatenation that will be flushed
+ * @return {@code true} if the concatenation was written before it was cleared, {@code false} otherwise
+ */
+ private boolean flushConcatenation(WordDelimiterConcatenation concatenation) {
+ lastConcatCount = concatenation.subwordCount;
+ if (concatenation.subwordCount != 1 || !shouldGenerateParts(concatenation.type)) {
+ concatenation.writeAndClear();
+ return true;
+ }
+ concatenation.clear();
+ return false;
+ }
+
+ /**
+ * Determines whether to concatenate a word or number if the current word is the given type
+ *
+ * @param wordType Type of the current word used to determine if it should be concatenated
+ * @return {@code true} if concatenation should occur, {@code false} otherwise
+ */
+ private boolean shouldConcatenate(int wordType) {
+ return (has(CATENATE_WORDS) && isAlpha(wordType)) || (has(CATENATE_NUMBERS) && isDigit(wordType));
+ }
+
+ /**
+ * Determines whether a word/number part should be generated for a word of the given type
+ *
+ * @param wordType Type of the word used to determine if a word/number part should be generated
+ * @return {@code true} if a word/number part should be generated, {@code false} otherwise
+ */
+ private boolean shouldGenerateParts(int wordType) {
+ return (has(GENERATE_WORD_PARTS) && isAlpha(wordType)) || (has(GENERATE_NUMBER_PARTS) && isDigit(wordType));
+ }
+
+ /**
+ * Concatenates the saved buffer to the given WordDelimiterConcatenation
+ *
+ * @param concatenation WordDelimiterConcatenation to concatenate the buffer to
+ */
+ private void concatenate(WordDelimiterConcatenation concatenation) {
+ if (concatenation.isEmpty()) {
+ concatenation.startOffset = savedStartOffset + iterator.current;
+ }
+ concatenation.append(savedBuffer, iterator.current, iterator.end - iterator.current);
+ concatenation.endOffset = savedStartOffset + iterator.end;
+ }
+
+ /**
+ * Generates a word/number part, updating the appropriate attributes
+ *
+ * @param isSingleWord {@code true} if the generation is occurring from a single word, {@code false} otherwise
+ */
+ private void generatePart(boolean isSingleWord) {
+ clearAttributes();
+ termAttribute.copyBuffer(savedBuffer, iterator.current, iterator.end - iterator.current);
+
+ int startOffset = savedStartOffset + iterator.current;
+ int endOffset = savedStartOffset + iterator.end;
+
+ if (hasIllegalOffsets) {
+ // historically this filter did this regardless for 'isSingleWord',
+ // but we must do a sanity check:
+ if (isSingleWord && startOffset <= savedEndOffset) {
+ offsetAttribute.setOffset(startOffset, savedEndOffset);
+ } else {
+ offsetAttribute.setOffset(savedStartOffset, savedEndOffset);
+ }
+ } else {
+ offsetAttribute.setOffset(startOffset, endOffset);
+ }
+ posIncAttribute.setPositionIncrement(position(false));
+ typeAttribute.setType(savedType);
+ }
+
+ /**
+ * Get the position increment gap for a subword or concatenation
+ *
+ * @param inject true if this token wants to be injected
+ * @return position increment gap
+ */
+ private int position(boolean inject) {
+ int posInc = accumPosInc;
+
+ if (hasOutputToken) {
+ accumPosInc = 0;
+ return inject ? 0 : Math.max(1, posInc);
+ }
+
+ hasOutputToken = true;
+
+ if (!hasOutputFollowingOriginal) {
+ // the first token following the original is 0 regardless
+ hasOutputFollowingOriginal = true;
+ return 0;
+ }
+ // clear the accumulated position increment
+ accumPosInc = 0;
+ return Math.max(1, posInc);
+ }
+
+ /**
+ * Checks if the given word type includes {@link #ALPHA}
+ *
+ * @param type Word type to check
+ * @return {@code true} if the type contains ALPHA, {@code false} otherwise
+ */
+ static boolean isAlpha(int type) {
+ return (type & ALPHA) != 0;
+ }
+
+ /**
+ * Checks if the given word type includes {@link #DIGIT}
+ *
+ * @param type Word type to check
+ * @return {@code true} if the type contains DIGIT, {@code false} otherwise
+ */
+ static boolean isDigit(int type) {
+ return (type & DIGIT) != 0;
+ }
+
+ /**
+ * Checks if the given word type includes {@link #SUBWORD_DELIM}
+ *
+ * @param type Word type to check
+ * @return {@code true} if the type contains SUBWORD_DELIM, {@code false} otherwise
+ */
+ static boolean isSubwordDelim(int type) {
+ return (type & SUBWORD_DELIM) != 0;
+ }
+
+ /**
+ * Checks if the given word type includes {@link #UPPER}
+ *
+ * @param type Word type to check
+ * @return {@code true} if the type contains UPPER, {@code false} otherwise
+ */
+ static boolean isUpper(int type) {
+ return (type & UPPER) != 0;
+ }
+
+ /**
+ * Determines whether the given flag is set
+ *
+ * @param flag Flag to see if set
+ * @return {@code true} if flag is set
+ */
+ private boolean has(int flag) {
+ return (flags & flag) != 0;
+ }
+
+ // ================================================= Inner Classes =================================================
+
+ /**
+ * A WDF concatenated 'run'
+ */
+ final class WordDelimiterConcatenation {
+ final StringBuilder buffer = new StringBuilder();
+ int startOffset;
+ int endOffset;
+ int type;
+ int subwordCount;
+
+ /**
+ * Appends the given text of the given length, to the concetenation at the given offset
+ *
+ * @param text Text to append
+ * @param offset Offset in the concetenation to add the text
+ * @param length Length of the text to append
+ */
+ void append(char text[], int offset, int length) {
+ buffer.append(text, offset, length);
+ subwordCount++;
+ }
+
+ /**
+ * Writes the concatenation to the attributes
+ */
+ void write() {
+ clearAttributes();
+ if (termAttribute.length() < buffer.length()) {
+ termAttribute.resizeBuffer(buffer.length());
+ }
+ char termbuffer[] = termAttribute.buffer();
+
+ buffer.getChars(0, buffer.length(), termbuffer, 0);
+ termAttribute.setLength(buffer.length());
+
+ if (hasIllegalOffsets) {
+ offsetAttribute.setOffset(savedStartOffset, savedEndOffset);
+ }
+ else {
+ offsetAttribute.setOffset(startOffset, endOffset);
+ }
+ posIncAttribute.setPositionIncrement(position(true));
+ typeAttribute.setType(savedType);
+ accumPosInc = 0;
+ }
+
+ /**
+ * Determines if the concatenation is empty
+ *
+ * @return {@code true} if the concatenation is empty, {@code false} otherwise
+ */
+ boolean isEmpty() {
+ return buffer.length() == 0;
+ }
+
+ /**
+ * Clears the concatenation and resets its state
+ */
+ void clear() {
+ buffer.setLength(0);
+ startOffset = endOffset = type = subwordCount = 0;
+ }
+
+ /**
+ * Convenience method for the common scenario of having to write the concetenation and then clearing its state
+ */
+ void writeAndClear() {
+ write();
+ clear();
+ }
+ }
+ // questions:
+ // negative numbers? -42 indexed as just 42?
+ // dollar sign? $42
+ // percent sign? 33%
+ // downsides: if source text is "powershot" then a query of "PowerShot" won't match!
+}
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilter.java
index e04043b4cdb..d684df0ccba 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilter.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilter.java
@@ -27,9 +27,13 @@ import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.AttributeSource;
+import org.apache.lucene.util.InPlaceMergeSorter;
import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.Version;
import java.io.IOException;
+import java.util.Arrays;
/**
* Splits words into subwords and performs optional transformations on subword
@@ -202,8 +206,11 @@ public final class WordDelimiterFilter extends TokenFilter {
* @param configurationFlags Flags configuring the filter
* @param protWords If not null is the set of tokens to protect from being delimited
*/
- public WordDelimiterFilter(TokenStream in, byte[] charTypeTable, int configurationFlags, CharArraySet protWords) {
+ public WordDelimiterFilter(Version matchVersion, TokenStream in, byte[] charTypeTable, int configurationFlags, CharArraySet protWords) {
super(in);
+ if (!matchVersion.onOrAfter(Version.LUCENE_48)) {
+ throw new IllegalArgumentException("This class only works with Lucene 4.8+. To emulate the old (broken) behavior of WordDelimiterFilter, use Lucene47WordDelimiterFilter");
+ }
this.flags = configurationFlags;
this.protWords = protWords;
this.iterator = new WordDelimiterIterator(
@@ -218,8 +225,8 @@ public final class WordDelimiterFilter extends TokenFilter {
* @param configurationFlags Flags configuring the filter
* @param protWords If not null is the set of tokens to protect from being delimited
*/
- public WordDelimiterFilter(TokenStream in, int configurationFlags, CharArraySet protWords) {
- this(in, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, configurationFlags, protWords);
+ public WordDelimiterFilter(Version matchVersion, TokenStream in, int configurationFlags, CharArraySet protWords) {
+ this(matchVersion, in, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, configurationFlags, protWords);
}
@Override
@@ -244,6 +251,7 @@ public final class WordDelimiterFilter extends TokenFilter {
(protWords != null && protWords.contains(termBuffer, 0, termLength))) {
posIncAttribute.setPositionIncrement(accumPosInc);
accumPosInc = 0;
+ first = false;
return true;
}
@@ -265,6 +273,7 @@ public final class WordDelimiterFilter extends TokenFilter {
if (has(PRESERVE_ORIGINAL)) {
posIncAttribute.setPositionIncrement(accumPosInc);
accumPosInc = 0;
+ first = false;
return true;
}
}
@@ -273,7 +282,8 @@ public final class WordDelimiterFilter extends TokenFilter {
if (iterator.end == WordDelimiterIterator.DONE) {
if (!concat.isEmpty()) {
if (flushConcatenation(concat)) {
- return true;
+ buffer();
+ continue;
}
}
@@ -281,12 +291,28 @@ public final class WordDelimiterFilter extends TokenFilter {
// only if we haven't output this same combo above!
if (concatAll.subwordCount > lastConcatCount) {
concatAll.writeAndClear();
- return true;
+ buffer();
+ continue;
}
concatAll.clear();
}
+ if (bufferedPos < bufferedLen) {
+ if (bufferedPos == 0) {
+ sorter.sort(0, bufferedLen);
+ }
+ clearAttributes();
+ restoreState(buffered[bufferedPos++]);
+ if (first && posIncAttribute.getPositionIncrement() == 0) {
+ // can easily happen with strange combinations (e.g. not outputting numbers, but concat-all)
+ posIncAttribute.setPositionIncrement(1);
+ }
+ first = false;
+ return true;
+ }
+
// no saved concatenations, on to the next input word
+ bufferedPos = bufferedLen = 0;
hasSavedState = false;
continue;
}
@@ -295,6 +321,7 @@ public final class WordDelimiterFilter extends TokenFilter {
if (iterator.isSingleWord()) {
generatePart(true);
iterator.next();
+ first = false;
return true;
}
@@ -304,7 +331,8 @@ public final class WordDelimiterFilter extends TokenFilter {
if (!concat.isEmpty() && (concat.type & wordType) == 0) {
if (flushConcatenation(concat)) {
hasOutputToken = false;
- return true;
+ buffer();
+ continue;
}
hasOutputToken = false;
}
@@ -325,28 +353,74 @@ public final class WordDelimiterFilter extends TokenFilter {
// if we should output the word or number part
if (shouldGenerateParts(wordType)) {
generatePart(false);
- iterator.next();
- return true;
+ buffer();
}
iterator.next();
}
}
- /**
- * {@inheritDoc}
- */
@Override
public void reset() throws IOException {
super.reset();
hasSavedState = false;
concat.clear();
concatAll.clear();
- accumPosInc = 0;
+ accumPosInc = bufferedPos = bufferedLen = 0;
+ first = true;
}
// ================================================= Helper Methods ================================================
+
+ private AttributeSource.State buffered[] = new AttributeSource.State[8];
+ private int startOff[] = new int[8];
+ private int posInc[] = new int[8];
+ private int bufferedLen = 0;
+ private int bufferedPos = 0;
+ private boolean first;
+
+ private class OffsetSorter extends InPlaceMergeSorter {
+ @Override
+ protected int compare(int i, int j) {
+ int cmp = Integer.compare(startOff[i], startOff[j]);
+ if (cmp == 0) {
+ cmp = Integer.compare(posInc[j], posInc[i]);
+ }
+ return cmp;
+ }
+
+ @Override
+ protected void swap(int i, int j) {
+ AttributeSource.State tmp = buffered[i];
+ buffered[i] = buffered[j];
+ buffered[j] = tmp;
+
+ int tmp2 = startOff[i];
+ startOff[i] = startOff[j];
+ startOff[j] = tmp2;
+
+ tmp2 = posInc[i];
+ posInc[i] = posInc[j];
+ posInc[j] = tmp2;
+ }
+ }
+
+ final OffsetSorter sorter = new OffsetSorter();
+
+ private void buffer() {
+ if (bufferedLen == buffered.length) {
+ int newSize = ArrayUtil.oversize(bufferedLen+1, 8);
+ buffered = Arrays.copyOf(buffered, newSize);
+ startOff = Arrays.copyOf(startOff, newSize);
+ posInc = Arrays.copyOf(posInc, newSize);
+ }
+ startOff[bufferedLen] = offsetAttribute.startOffset();
+ posInc[bufferedLen] = posIncAttribute.getPositionIncrement();
+ buffered[bufferedLen] = captureState();
+ bufferedLen++;
+ }
+
/**
* Saves the existing attribute states
*/
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilterFactory.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilterFactory.java
index cc66970a54e..aebb061994f 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilterFactory.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilterFactory.java
@@ -17,11 +17,13 @@ package org.apache.lucene.analysis.miscellaneous;
* limitations under the License.
*/
+import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.analysis.util.ResourceLoader;
import org.apache.lucene.analysis.util.ResourceLoaderAware;
import org.apache.lucene.analysis.util.TokenFilterFactory;
+import org.apache.lucene.util.Version;
import java.util.ArrayList;
import java.util.List;
@@ -61,6 +63,7 @@ public class WordDelimiterFilterFactory extends TokenFilterFactory implements Re
/** Creates a new WordDelimiterFilterFactory */
public WordDelimiterFilterFactory(Map<String, String> args) {
super(args);
+ assureMatchVersion();
int flags = 0;
if (getInt(args, "generateWordParts", 1) != 0) {
flags |= GENERATE_WORD_PARTS;
@@ -114,9 +117,14 @@ public class WordDelimiterFilterFactory extends TokenFilterFactory implements Re
}
@Override
- public WordDelimiterFilter create(TokenStream input) {
- return new WordDelimiterFilter(input, typeTable == null ? WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE : typeTable,
+ public TokenFilter create(TokenStream input) {
+ if (luceneMatchVersion.onOrAfter(Version.LUCENE_48)) {
+ return new WordDelimiterFilter(luceneMatchVersion, input, typeTable == null ? WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE : typeTable,
flags, protectedWords);
+ } else {
+ return new Lucene47WordDelimiterFilter(input, typeTable == null ? WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE : typeTable,
+ flags, protectedWords);
+ }
}
// source => type
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestRandomChains.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestRandomChains.java
index 8a91a9e4875..d3397a7ef61 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestRandomChains.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestRandomChains.java
@@ -144,9 +144,7 @@ public class TestRandomChains extends BaseTokenStreamTestCase {
CachingTokenFilter.class,
// Not broken: we forcefully add this, so we shouldn't
// also randomly pick it:
- ValidatingTokenFilter.class,
- // broken!
- WordDelimiterFilter.class)) {
+ ValidatingTokenFilter.class)) {
for (Constructor<?> ctor : c.getConstructors()) {
brokenConstructors.put(ctor, ALWAYS);
}
@@ -175,7 +173,9 @@ public class TestRandomChains extends BaseTokenStreamTestCase {
// TODO: LUCENE-4983
CommonGramsFilter.class,
// TODO: doesn't handle graph inputs
- CommonGramsQueryFilter.class)) {
+ CommonGramsQueryFilter.class,
+ // TODO: probably doesnt handle graph inputs, too afraid to try
+ WordDelimiterFilter.class)) {
for (Constructor<?> ctor : c.getConstructors()) {
brokenOffsetsConstructors.put(ctor, ALWAYS);
}
@@ -893,7 +893,26 @@ public class TestRandomChains extends BaseTokenStreamTestCase {
}
public void testRandomChains() throws Throwable {
- int numIterations = atLeast(10);
+ int numIterations = atLeast(20);
+ Random random = random();
+ for (int i = 0; i < numIterations; i++) {
+ MockRandomAnalyzer a = new MockRandomAnalyzer(random.nextLong());
+ if (VERBOSE) {
+ System.out.println("Creating random analyzer:" + a);
+ }
+ try {
+ checkRandomData(random, a, 500*RANDOM_MULTIPLIER, 20, false,
+ false /* We already validate our own offsets... */);
+ } catch (Throwable e) {
+ System.err.println("Exception from random analyzer: " + a);
+ throw e;
+ }
+ }
+ }
+
+ // we might regret this decision...
+ public void testRandomChainsWithLargeStrings() throws Throwable {
+ int numIterations = atLeast(20);
Random random = random();
for (int i = 0; i < numIterations; i++) {
MockRandomAnalyzer a = new MockRandomAnalyzer(random.nextLong());
@@ -901,7 +920,7 @@ public class TestRandomChains extends BaseTokenStreamTestCase {
System.out.println("Creating random analyzer:" + a);
}
try {
- checkRandomData(random, a, 200, 20, false,
+ checkRandomData(random, a, 50*RANDOM_MULTIPLIER, 256, false,
false /* We already validate our own offsets... */);
} catch (Throwable e) {
System.err.println("Exception from random analyzer: " + a);
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLucene47WordDelimiterFilter.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLucene47WordDelimiterFilter.java
new file mode 100644
index 00000000000..75a9ab067a6
--- /dev/null
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLucene47WordDelimiterFilter.java
@@ -0,0 +1,375 @@
+/*
+ * 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.miscellaneous;
+
+import org.apache.lucene.analysis.*;
+import org.apache.lucene.analysis.core.KeywordTokenizer;
+import org.apache.lucene.analysis.core.StopFilter;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
+import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
+import org.apache.lucene.analysis.util.CharArraySet;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.*;
+
+import static org.apache.lucene.analysis.miscellaneous.WordDelimiterFilter.*;
+import static org.apache.lucene.analysis.miscellaneous.WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE;
+
+/**
+ * New WordDelimiterFilter tests... most of the tests are in ConvertedLegacyTest
+ * TODO: should explicitly test things like protWords and not rely on
+ * the factory tests in Solr.
+ */
+@Deprecated
+public class TestLucene47WordDelimiterFilter extends BaseTokenStreamTestCase {
+
+ /***
+ public void testPerformance() throws IOException {
+ String s = "now is the time-for all good men to come to-the aid of their country.";
+ Token tok = new Token();
+ long start = System.currentTimeMillis();
+ int ret=0;
+ for (int i=0; i<1000000; i++) {
+ StringReader r = new StringReader(s);
+ TokenStream ts = new WhitespaceTokenizer(r);
+ ts = new WordDelimiterFilter(ts, 1,1,1,1,0);
+
+ while (ts.next(tok) != null) ret++;
+ }
+
+ System.out.println("ret="+ret+" time="+(System.currentTimeMillis()-start));
+ }
+ ***/
+
+ @Test
+ public void testOffsets() throws IOException {
+ int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
+ // test that subwords and catenated subwords have
+ // the correct offsets.
+ TokenFilter wdf = new Lucene47WordDelimiterFilter(new SingleTokenTokenStream(new Token("foo-bar", 5, 12)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+
+ assertTokenStreamContents(wdf,
+ new String[] { "foo", "bar", "foobar" },
+ new int[] { 5, 9, 5 },
+ new int[] { 8, 12, 12 },
+ null, null, null, null, false);
+
+ wdf = new Lucene47WordDelimiterFilter(new SingleTokenTokenStream(new Token("foo-bar", 5, 6)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+
+ assertTokenStreamContents(wdf,
+ new String[] { "foo", "bar", "foobar" },
+ new int[] { 5, 5, 5 },
+ new int[] { 6, 6, 6 },
+ null, null, null, null, false);
+ }
+
+ @Test
+ public void testOffsetChange() throws Exception {
+ int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
+ TokenFilter wdf = new Lucene47WordDelimiterFilter(new SingleTokenTokenStream(new Token("übelkeit)", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+
+ assertTokenStreamContents(wdf,
+ new String[] { "übelkeit" },
+ new int[] { 7 },
+ new int[] { 15 });
+ }
+
+ @Test
+ public void testOffsetChange2() throws Exception {
+ int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
+ TokenFilter wdf = new Lucene47WordDelimiterFilter(new SingleTokenTokenStream(new Token("(übelkeit", 7, 17)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+
+ assertTokenStreamContents(wdf,
+ new String[] { "übelkeit" },
+ new int[] { 8 },
+ new int[] { 17 });
+ }
+
+ @Test
+ public void testOffsetChange3() throws Exception {
+ int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
+ TokenFilter wdf = new Lucene47WordDelimiterFilter(new SingleTokenTokenStream(new Token("(übelkeit", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+
+ assertTokenStreamContents(wdf,
+ new String[] { "übelkeit" },
+ new int[] { 8 },
+ new int[] { 16 });
+ }
+
+ @Test
+ public void testOffsetChange4() throws Exception {
+ int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
+ TokenFilter wdf = new Lucene47WordDelimiterFilter(new SingleTokenTokenStream(new Token("(foo,bar)", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+
+ assertTokenStreamContents(wdf,
+ new String[] { "foo", "bar", "foobar"},
+ new int[] { 8, 12, 8 },
+ new int[] { 11, 15, 15 },
+ null, null, null, null, false);
+ }
+
+ public void doSplit(final String input, String... output) throws Exception {
+ int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
+ TokenFilter wdf = new Lucene47WordDelimiterFilter(keywordMockTokenizer(input),
+ WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null);
+
+ assertTokenStreamContents(wdf, output);
+ }
+
+ @Test
+ public void testSplits() throws Exception {
+ doSplit("basic-split","basic","split");
+ doSplit("camelCase","camel","Case");
+
+ // non-space marking symbol shouldn't cause split
+ // this is an example in Thai
+ doSplit("\u0e1a\u0e49\u0e32\u0e19","\u0e1a\u0e49\u0e32\u0e19");
+ // possessive followed by delimiter
+ doSplit("test's'", "test");
+
+ // some russian upper and lowercase
+ doSplit("Роберт", "Роберт");
+ // now cause a split (russian camelCase)
+ doSplit("РобЕрт", "Роб", "Ерт");
+
+ // a composed titlecase character, don't split
+ doSplit("aDžungla", "aDžungla");
+
+ // a modifier letter, don't split
+ doSplit("ســـــــــــــــــلام", "ســـــــــــــــــلام");
+
+ // enclosing mark, don't split
+ doSplit("test⃝", "test⃝");
+
+ // combining spacing mark (the virama), don't split
+ doSplit("हिन्दी", "हिन्दी");
+
+ // don't split non-ascii digits
+ doSplit("١٢٣٤", "١٢٣٤");
+
+ // don't split supplementaries into unpaired surrogates
+ doSplit("𠀀𠀀", "𠀀𠀀");
+ }
+
+ public void doSplitPossessive(int stemPossessive, final String input, final String... output) throws Exception {
+ int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS;
+ flags |= (stemPossessive == 1) ? STEM_ENGLISH_POSSESSIVE : 0;
+ TokenFilter wdf = new Lucene47WordDelimiterFilter(keywordMockTokenizer(input), flags, null);
+
+ assertTokenStreamContents(wdf, output);
+ }
+
+ /*
+ * Test option that allows disabling the special "'s" stemming, instead treating the single quote like other delimiters.
+ */
+ @Test
+ public void testPossessives() throws Exception {
+ doSplitPossessive(1, "ra's", "ra");
+ doSplitPossessive(0, "ra's", "ra", "s");
+ }
+
+ /*
+ * Set a large position increment gap of 10 if the token is "largegap" or "/"
+ */
+ private final class LargePosIncTokenFilter extends TokenFilter {
+ private CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
+ private PositionIncrementAttribute posIncAtt = addAttribute(PositionIncrementAttribute.class);
+
+ protected LargePosIncTokenFilter(TokenStream input) {
+ super(input);
+ }
+
+ @Override
+ public boolean incrementToken() throws IOException {
+ if (input.incrementToken()) {
+ if (termAtt.toString().equals("largegap") || termAtt.toString().equals("/"))
+ posIncAtt.setPositionIncrement(10);
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ @Test
+ public void testPositionIncrements() throws Exception {
+ final int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
+ final CharArraySet protWords = new CharArraySet(TEST_VERSION_CURRENT, new HashSet<>(Arrays.asList("NUTCH")), false);
+
+ /* analyzer that uses whitespace + wdf */
+ Analyzer a = new Analyzer() {
+ @Override
+ public TokenStreamComponents createComponents(String field) {
+ Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
+ return new TokenStreamComponents(tokenizer, new Lucene47WordDelimiterFilter(
+ tokenizer,
+ flags, protWords));
+ }
+ };
+
+ /* in this case, works as expected. */
+ assertAnalyzesTo(a, "LUCENE / SOLR", new String[] { "LUCENE", "SOLR" },
+ new int[] { 0, 9 },
+ new int[] { 6, 13 },
+ null,
+ new int[] { 1, 1 },
+ null,
+ false);
+
+ /* only in this case, posInc of 2 ?! */
+ assertAnalyzesTo(a, "LUCENE / solR", new String[] { "LUCENE", "sol", "R", "solR" },
+ new int[] { 0, 9, 12, 9 },
+ new int[] { 6, 12, 13, 13 },
+ null,
+ new int[] { 1, 1, 1, 0 },
+ null,
+ false);
+
+ assertAnalyzesTo(a, "LUCENE / NUTCH SOLR", new String[] { "LUCENE", "NUTCH", "SOLR" },
+ new int[] { 0, 9, 15 },
+ new int[] { 6, 14, 19 },
+ null,
+ new int[] { 1, 1, 1 },
+ null,
+ false);
+
+ /* analyzer that will consume tokens with large position increments */
+ Analyzer a2 = new Analyzer() {
+ @Override
+ public TokenStreamComponents createComponents(String field) {
+ Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
+ return new TokenStreamComponents(tokenizer, new Lucene47WordDelimiterFilter(
+ new LargePosIncTokenFilter(tokenizer),
+ flags, protWords));
+ }
+ };
+
+ /* increment of "largegap" is preserved */
+ assertAnalyzesTo(a2, "LUCENE largegap SOLR", new String[] { "LUCENE", "largegap", "SOLR" },
+ new int[] { 0, 7, 16 },
+ new int[] { 6, 15, 20 },
+ null,
+ new int[] { 1, 10, 1 },
+ null,
+ false);
+
+ /* the "/" had a position increment of 10, where did it go?!?!! */
+ assertAnalyzesTo(a2, "LUCENE / SOLR", new String[] { "LUCENE", "SOLR" },
+ new int[] { 0, 9 },
+ new int[] { 6, 13 },
+ null,
+ new int[] { 1, 11 },
+ null,
+ false);
+
+ /* in this case, the increment of 10 from the "/" is carried over */
+ assertAnalyzesTo(a2, "LUCENE / solR", new String[] { "LUCENE", "sol", "R", "solR" },
+ new int[] { 0, 9, 12, 9 },
+ new int[] { 6, 12, 13, 13 },
+ null,
+ new int[] { 1, 11, 1, 0 },
+ null,
+ false);
+
+ assertAnalyzesTo(a2, "LUCENE / NUTCH SOLR", new String[] { "LUCENE", "NUTCH", "SOLR" },
+ new int[] { 0, 9, 15 },
+ new int[] { 6, 14, 19 },
+ null,
+ new int[] { 1, 11, 1 },
+ null,
+ false);
+
+ Analyzer a3 = new Analyzer() {
+ @Override
+ public TokenStreamComponents createComponents(String field) {
+ Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
+ StopFilter filter = new StopFilter(TEST_VERSION_CURRENT,
+ tokenizer, StandardAnalyzer.STOP_WORDS_SET);
+ return new TokenStreamComponents(tokenizer, new Lucene47WordDelimiterFilter(filter, flags, protWords));
+ }
+ };
+
+ assertAnalyzesTo(a3, "lucene.solr",
+ new String[] { "lucene", "solr", "lucenesolr" },
+ new int[] { 0, 7, 0 },
+ new int[] { 6, 11, 11 },
+ null,
+ new int[] { 1, 1, 0 },
+ null,
+ false);
+
+ /* the stopword should add a gap here */
+ assertAnalyzesTo(a3, "the lucene.solr",
+ new String[] { "lucene", "solr", "lucenesolr" },
+ new int[] { 4, 11, 4 },
+ new int[] { 10, 15, 15 },
+ null,
+ new int[] { 2, 1, 0 },
+ null,
+ false);
+ }
+
+ /** blast some random strings through the analyzer */
+ public void testRandomStrings() throws Exception {
+ int numIterations = atLeast(5);
+ for (int i = 0; i < numIterations; i++) {
+ final int flags = random().nextInt(512);
+ final CharArraySet protectedWords;
+ if (random().nextBoolean()) {
+ protectedWords = new CharArraySet(TEST_VERSION_CURRENT, new HashSet<>(Arrays.asList("a", "b", "cd")), false);
+ } else {
+ protectedWords = null;
+ }
+
+ Analyzer a = new Analyzer() {
+
+ @Override
+ protected TokenStreamComponents createComponents(String fieldName) {
+ Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
+ return new TokenStreamComponents(tokenizer, new Lucene47WordDelimiterFilter(tokenizer, flags, protectedWords));
+ }
+ };
+ checkRandomData(random(), a, 200, 20, false, false);
+ }
+ }
+
+ public void testEmptyTerm() throws IOException {
+ Random random = random();
+ for (int i = 0; i < 512; i++) {
+ final int flags = i;
+ final CharArraySet protectedWords;
+ if (random.nextBoolean()) {
+ protectedWords = new CharArraySet(TEST_VERSION_CURRENT, new HashSet<>(Arrays.asList("a", "b", "cd")), false);
+ } else {
+ protectedWords = null;
+ }
+
+ Analyzer a = new Analyzer() {
+ @Override
+ protected TokenStreamComponents createComponents(String fieldName) {
+ Tokenizer tokenizer = new KeywordTokenizer();
+ return new TokenStreamComponents(tokenizer, new Lucene47WordDelimiterFilter(tokenizer, flags, protectedWords));
+ }
+ };
+ // depending upon options, this thing may or may not preserve the empty term
+ checkAnalysisConsistency(random, a, random.nextBoolean(), "");
+ }
+ }
+}
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestWordDelimiterFilter.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestWordDelimiterFilter.java
index 45ba5d5d21b..b76d668459a 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestWordDelimiterFilter.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestWordDelimiterFilter.java
@@ -62,27 +62,25 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
// test that subwords and catenated subwords have
// the correct offsets.
- WordDelimiterFilter wdf = new WordDelimiterFilter(new SingleTokenTokenStream(new Token("foo-bar", 5, 12)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("foo-bar", 5, 12)), DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
- new String[] { "foo", "bar", "foobar" },
- new int[] { 5, 9, 5 },
- new int[] { 8, 12, 12 },
- null, null, null, null, false);
+ new String[] { "foo", "foobar", "bar" },
+ new int[] { 5, 5, 9 },
+ new int[] { 8, 12, 12 });
- wdf = new WordDelimiterFilter(new SingleTokenTokenStream(new Token("foo-bar", 5, 6)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("foo-bar", 5, 6)), DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
new String[] { "foo", "bar", "foobar" },
new int[] { 5, 5, 5 },
- new int[] { 6, 6, 6 },
- null, null, null, null, false);
+ new int[] { 6, 6, 6 });
}
@Test
public void testOffsetChange() throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterFilter wdf = new WordDelimiterFilter(new SingleTokenTokenStream(new Token("übelkeit)", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("übelkeit)", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
new String[] { "übelkeit" },
@@ -93,7 +91,7 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
@Test
public void testOffsetChange2() throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterFilter wdf = new WordDelimiterFilter(new SingleTokenTokenStream(new Token("(übelkeit", 7, 17)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("(übelkeit", 7, 17)), DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
new String[] { "übelkeit" },
@@ -104,7 +102,7 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
@Test
public void testOffsetChange3() throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterFilter wdf = new WordDelimiterFilter(new SingleTokenTokenStream(new Token("(übelkeit", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("(übelkeit", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
new String[] { "übelkeit" },
@@ -115,18 +113,17 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
@Test
public void testOffsetChange4() throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterFilter wdf = new WordDelimiterFilter(new SingleTokenTokenStream(new Token("(foo,bar)", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
+ WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("(foo,bar)", 7, 16)), DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf,
- new String[] { "foo", "bar", "foobar"},
- new int[] { 8, 12, 8 },
- new int[] { 11, 15, 15 },
- null, null, null, null, false);
+ new String[] { "foo", "foobar", "bar"},
+ new int[] { 8, 8, 12 },
+ new int[] { 11, 15, 15 });
}
public void doSplit(final String input, String... output) throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
- WordDelimiterFilter wdf = new WordDelimiterFilter(keywordMockTokenizer(input),
+ WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, keywordMockTokenizer(input),
WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null);
assertTokenStreamContents(wdf, output);
@@ -170,7 +167,7 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
public void doSplitPossessive(int stemPossessive, final String input, final String... output) throws Exception {
int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS;
flags |= (stemPossessive == 1) ? STEM_ENGLISH_POSSESSIVE : 0;
- WordDelimiterFilter wdf = new WordDelimiterFilter(keywordMockTokenizer(input), flags, null);
+ WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, keywordMockTokenizer(input), flags, null);
assertTokenStreamContents(wdf, output);
}
@@ -217,7 +214,7 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
@Override
public TokenStreamComponents createComponents(String field) {
Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
- return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(
+ return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT,
tokenizer,
flags, protWords));
}
@@ -227,34 +224,25 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
assertAnalyzesTo(a, "LUCENE / SOLR", new String[] { "LUCENE", "SOLR" },
new int[] { 0, 9 },
new int[] { 6, 13 },
- null,
- new int[] { 1, 1 },
- null,
- false);
+ new int[] { 1, 1 });
/* only in this case, posInc of 2 ?! */
- assertAnalyzesTo(a, "LUCENE / solR", new String[] { "LUCENE", "sol", "R", "solR" },
- new int[] { 0, 9, 12, 9 },
+ assertAnalyzesTo(a, "LUCENE / solR", new String[] { "LUCENE", "sol", "solR", "R" },
+ new int[] { 0, 9, 9, 12 },
new int[] { 6, 12, 13, 13 },
- null,
- new int[] { 1, 1, 1, 0 },
- null,
- false);
+ new int[] { 1, 1, 0, 1 });
assertAnalyzesTo(a, "LUCENE / NUTCH SOLR", new String[] { "LUCENE", "NUTCH", "SOLR" },
new int[] { 0, 9, 15 },
new int[] { 6, 14, 19 },
- null,
- new int[] { 1, 1, 1 },
- null,
- false);
+ new int[] { 1, 1, 1 });
/* analyzer that will consume tokens with large position increments */
Analyzer a2 = new Analyzer() {
@Override
public TokenStreamComponents createComponents(String field) {
Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
- return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(
+ return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT,
new LargePosIncTokenFilter(tokenizer),
flags, protWords));
}
@@ -264,36 +252,24 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
assertAnalyzesTo(a2, "LUCENE largegap SOLR", new String[] { "LUCENE", "largegap", "SOLR" },
new int[] { 0, 7, 16 },
new int[] { 6, 15, 20 },
- null,
- new int[] { 1, 10, 1 },
- null,
- false);
+ new int[] { 1, 10, 1 });
/* the "/" had a position increment of 10, where did it go?!?!! */
assertAnalyzesTo(a2, "LUCENE / SOLR", new String[] { "LUCENE", "SOLR" },
new int[] { 0, 9 },
new int[] { 6, 13 },
- null,
- new int[] { 1, 11 },
- null,
- false);
+ new int[] { 1, 11 });
/* in this case, the increment of 10 from the "/" is carried over */
- assertAnalyzesTo(a2, "LUCENE / solR", new String[] { "LUCENE", "sol", "R", "solR" },
- new int[] { 0, 9, 12, 9 },
+ assertAnalyzesTo(a2, "LUCENE / solR", new String[] { "LUCENE", "sol", "solR", "R" },
+ new int[] { 0, 9, 9, 12 },
new int[] { 6, 12, 13, 13 },
- null,
- new int[] { 1, 11, 1, 0 },
- null,
- false);
+ new int[] { 1, 11, 0, 1 });
assertAnalyzesTo(a2, "LUCENE / NUTCH SOLR", new String[] { "LUCENE", "NUTCH", "SOLR" },
new int[] { 0, 9, 15 },
new int[] { 6, 14, 19 },
- null,
- new int[] { 1, 11, 1 },
- null,
- false);
+ new int[] { 1, 11, 1 });
Analyzer a3 = new Analyzer() {
@Override
@@ -301,28 +277,62 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
StopFilter filter = new StopFilter(TEST_VERSION_CURRENT,
tokenizer, StandardAnalyzer.STOP_WORDS_SET);
- return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(filter, flags, protWords));
+ return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, filter, flags, protWords));
}
};
assertAnalyzesTo(a3, "lucene.solr",
- new String[] { "lucene", "solr", "lucenesolr" },
- new int[] { 0, 7, 0 },
+ new String[] { "lucene", "lucenesolr", "solr" },
+ new int[] { 0, 0, 7 },
new int[] { 6, 11, 11 },
- null,
- new int[] { 1, 1, 0 },
- null,
- false);
+ new int[] { 1, 0, 1 });
/* the stopword should add a gap here */
assertAnalyzesTo(a3, "the lucene.solr",
- new String[] { "lucene", "solr", "lucenesolr" },
- new int[] { 4, 11, 4 },
+ new String[] { "lucene", "lucenesolr", "solr" },
+ new int[] { 4, 4, 11 },
new int[] { 10, 15, 15 },
- null,
- new int[] { 2, 1, 0 },
- null,
- false);
+ new int[] { 2, 0, 1 });
+ }
+
+ /** concat numbers + words + all */
+ public void testLotsOfConcatenating() throws Exception {
+ final int flags = GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_WORDS | CATENATE_NUMBERS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
+
+ /* analyzer that uses whitespace + wdf */
+ Analyzer a = new Analyzer() {
+ @Override
+ public TokenStreamComponents createComponents(String field) {
+ Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
+ return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, null));
+ }
+ };
+
+ assertAnalyzesTo(a, "abc-def-123-456",
+ new String[] { "abc", "abcdef", "abcdef123456", "def", "123", "123456", "456" },
+ new int[] { 0, 0, 0, 4, 8, 8, 12 },
+ new int[] { 3, 7, 15, 7, 11, 15, 15 },
+ new int[] { 1, 0, 0, 1, 1, 0, 1 });
+ }
+
+ /** concat numbers + words + all + preserve original */
+ public void testLotsOfConcatenating2() throws Exception {
+ final int flags = PRESERVE_ORIGINAL | GENERATE_WORD_PARTS | GENERATE_NUMBER_PARTS | CATENATE_WORDS | CATENATE_NUMBERS | CATENATE_ALL | SPLIT_ON_CASE_CHANGE | SPLIT_ON_NUMERICS | STEM_ENGLISH_POSSESSIVE;
+
+ /* analyzer that uses whitespace + wdf */
+ Analyzer a = new Analyzer() {
+ @Override
+ public TokenStreamComponents createComponents(String field) {
+ Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
+ return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, null));
+ }
+ };
+
+ assertAnalyzesTo(a, "abc-def-123-456",
+ new String[] { "abc-def-123-456", "abc", "abcdef", "abcdef123456", "def", "123", "123456", "456" },
+ new int[] { 0, 0, 0, 0, 4, 8, 8, 12 },
+ new int[] { 15, 3, 7, 15, 7, 11, 15, 15 },
+ new int[] { 1, 0, 0, 0, 1, 1, 0, 1 });
}
/** blast some random strings through the analyzer */
@@ -342,10 +352,34 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
- return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(tokenizer, flags, protectedWords));
+ return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, protectedWords));
+ }
+ };
+ checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
+ }
+ }
+
+ /** blast some enormous random strings through the analyzer */
+ public void testRandomHugeStrings() throws Exception {
+ int numIterations = atLeast(5);
+ for (int i = 0; i < numIterations; i++) {
+ final int flags = random().nextInt(512);
+ final CharArraySet protectedWords;
+ if (random().nextBoolean()) {
+ protectedWords = new CharArraySet(TEST_VERSION_CURRENT, new HashSet<>(Arrays.asList("a", "b", "cd")), false);
+ } else {
+ protectedWords = null;
+ }
+
+ Analyzer a = new Analyzer() {
+
+ @Override
+ protected TokenStreamComponents createComponents(String fieldName) {
+ Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
+ return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, protectedWords));
}
};
- checkRandomData(random(), a, 200, 20, false, false);
+ checkRandomData(random(), a, 100*RANDOM_MULTIPLIER, 8192);
}
}
@@ -364,7 +398,7 @@ public class TestWordDelimiterFilter extends BaseTokenStreamTestCase {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new KeywordTokenizer();
- return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(tokenizer, flags, protectedWords));
+ return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, protectedWords));
}
};
// depending upon options, this thing may or may not preserve the empty term
diff --git a/solr/core/src/test/org/apache/solr/analysis/TestWordDelimiterFilterFactory.java b/solr/core/src/test/org/apache/solr/analysis/TestWordDelimiterFilterFactory.java
index e71b8c8b7f7..9dff31bab22 100644
--- a/solr/core/src/test/org/apache/solr/analysis/TestWordDelimiterFilterFactory.java
+++ b/solr/core/src/test/org/apache/solr/analysis/TestWordDelimiterFilterFactory.java
@@ -200,6 +200,7 @@ public class TestWordDelimiterFilterFactory extends SolrTestCaseJ4 {
String testText = "I borrowed $5,400.00 at 25% interest-rate";
ResourceLoader loader = new SolrResourceLoader("solr/collection1");
Map<String,String> args = new HashMap<>();
+ args.put("luceneMatchVersion", TEST_VERSION_CURRENT.toString());
args.put("generateWordParts", "1");
args.put("generateNumberParts", "1");
args.put("catenateWords", "1");
@@ -213,16 +214,17 @@ public class TestWordDelimiterFilterFactory extends SolrTestCaseJ4 {
TokenStream ts = factoryDefault.create(whitespaceMockTokenizer(testText));
BaseTokenStreamTestCase.assertTokenStreamContents(ts,
- new String[] { "I", "borrowed", "5", "400", "00", "540000", "at", "25", "interest", "rate", "interestrate" });
+ new String[] { "I", "borrowed", "5", "540000", "400", "00", "at", "25", "interest", "interestrate", "rate" });
ts = factoryDefault.create(whitespaceMockTokenizer("foo\u200Dbar"));
BaseTokenStreamTestCase.assertTokenStreamContents(ts,
- new String[] { "foo", "bar", "foobar" });
+ new String[] { "foo", "foobar", "bar" });
/* custom behavior */
args = new HashMap<>();
// use a custom type mapping
+ args.put("luceneMatchVersion", TEST_VERSION_CURRENT.toString());
args.put("generateWordParts", "1");
args.put("generateNumberParts", "1");
args.put("catenateWords", "1");
@@ -235,7 +237,7 @@ public class TestWordDelimiterFilterFactory extends SolrTestCaseJ4 {
ts = factoryCustom.create(whitespaceMockTokenizer(testText));
BaseTokenStreamTestCase.assertTokenStreamContents(ts,
- new String[] { "I", "borrowed", "$5,400.00", "at", "25%", "interest", "rate", "interestrate" });
+ new String[] { "I", "borrowed", "$5,400.00", "at", "25%", "interest", "interestrate", "rate" });
/* test custom behavior with a char > 0x7F, because we had to make a larger byte[] */
ts = factoryCustom.create(whitespaceMockTokenizer("foo\u200Dbar"));
diff --git a/solr/core/src/test/org/apache/solr/handler/FieldAnalysisRequestHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/FieldAnalysisRequestHandlerTest.java
index c82cedcd121..ece55046f73 100644
--- a/solr/core/src/test/org/apache/solr/handler/FieldAnalysisRequestHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/FieldAnalysisRequestHandlerTest.java
@@ -365,8 +365,8 @@ public class FieldAnalysisRequestHandlerTest extends AnalysisRequestHandlerTestB
assertEquals(6, tokenList.size());
assertToken(tokenList.get(0), new TokenInfo("hi", null, "word", 0, 2, 1, new int[]{1,1}, null, false));
assertToken(tokenList.get(1), new TokenInfo("3456", null, "word", 4, 8, 2, new int[]{2,2}, null, false));
- assertToken(tokenList.get(2), new TokenInfo("12", null, "word", 9, 11, 3, new int[]{2,3}, null, false));
- assertToken(tokenList.get(3), new TokenInfo("345612", null, "word", 4, 11, 3, new int[]{2,3}, null, false));
+ assertToken(tokenList.get(2), new TokenInfo("345612", null, "word", 4, 11, 2, new int[]{2,2}, null, false));
+ assertToken(tokenList.get(3), new TokenInfo("12", null, "word", 9, 11, 3, new int[]{2,3}, null, false));
assertToken(tokenList.get(4), new TokenInfo("a", null, "word", 12, 13, 4, new int[]{3,4}, null, false));
assertToken(tokenList.get(5), new TokenInfo("Test", null, "word", 14, 18, 5, new int[]{4,5}, null, false));
tokenList = indexPart.get("org.apache.lucene.analysis.core.LowerCaseFilter");
@@ -374,8 +374,8 @@ public class FieldAnalysisRequestHandlerTest extends AnalysisRequestHandlerTestB
assertEquals(6, tokenList.size());
assertToken(tokenList.get(0), new TokenInfo("hi", null, "word", 0, 2, 1, new int[]{1,1,1}, null, false));
assertToken(tokenList.get(1), new TokenInfo("3456", null, "word", 4, 8, 2, new int[]{2,2,2}, null, false));
- assertToken(tokenList.get(2), new TokenInfo("12", null, "word", 9, 11, 3, new int[]{2,3,3}, null, false));
- assertToken(tokenList.get(3), new TokenInfo("345612", null, "word", 4, 11, 3, new int[]{2,3,3}, null, false));
+ assertToken(tokenList.get(2), new TokenInfo("345612", null, "word", 4, 11, 2, new int[]{2,2,2}, null, false));
+ assertToken(tokenList.get(3), new TokenInfo("12", null, "word", 9, 11, 3, new int[]{2,3,3}, null, false));
assertToken(tokenList.get(4), new TokenInfo("a", null, "word", 12, 13, 4, new int[]{3,4,4}, null, false));
assertToken(tokenList.get(5), new TokenInfo("test", null, "word", 14, 18, 5, new int[]{4,5,5}, null, false));
}