Apache Lucene open-source search software
LUCENE-6459: add common suggest API for document based NRT suggester
Michael McCandlessbe4d58c7740b
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 3e8f9b10912..6b50669404e 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -41,6 +41,12 @@ New Featurescan be used with getMultiValueSeparator render whole fieldvalues. (Luca Cavanna via Robert Muir)+* LUCENE-6459: Add common suggest API that mirrors Lucene's+ Query/IndexSearcher APIs for Document based suggester.+ Adds PrefixCompletionQuery, RegexCompletionQuery,+ FuzzyCompletionQuery and ContextQuery.+ (Areek Zillur via Mike McCandless)+Bug fixes* LUCENE-6500: ParallelCompositeReader did not always calldiff --git a/lucene/core/src/java/org/apache/lucene/util/fst/Util.java b/lucene/core/src/java/org/apache/lucene/util/fst/Util.javaindex ebee4f295f0..4c914e8a8e4 100644--- a/lucene/core/src/java/org/apache/lucene/util/fst/Util.java+++ b/lucene/core/src/java/org/apache/lucene/util/fst/Util.java@@ -251,17 +251,29 @@ public final class Util {public FST.Arc<T> arc;public T cost;public final IntsRefBuilder input;+ public final float boost;+ public final CharSequence context;/** Sole constructor */public FSTPath(T cost, FST.Arc<T> arc, IntsRefBuilder input) {+ this(cost, arc, input, 0, null);+ }++ public FSTPath(T cost, FST.Arc<T> arc, IntsRefBuilder input, float boost, CharSequence context) {this.arc = new FST.Arc<T>().copyFrom(arc);this.cost = cost;this.input = input;+ this.boost = boost;+ this.context = context;+ }++ public FSTPath<T> newPath(T cost, IntsRefBuilder input) {+ return new FSTPath<>(cost, this.arc, input, this.boost, this.context);}@Overridepublic String toString() {- return "input=" + input + " cost=" + cost;+ return "input=" + input + " cost=" + cost + "context=" + context + "boost=" + boost;}}@@ -307,13 +319,18 @@ public final class Util {* @param comparator the comparator to select the top N*/public TopNSearcher(FST<T> fst, int topN, int maxQueueDepth, Comparator<T> comparator) {+ this(fst, topN, maxQueueDepth, comparator, new TieBreakByInputComparator<>(comparator));+ }++ public TopNSearcher(FST<T> fst, int topN, int maxQueueDepth, Comparator<T> comparator,+ Comparator<FSTPath<T>> pathComparator) {this.fst = fst;this.bytesReader = fst.getBytesReader();this.topN = topN;this.maxQueueDepth = maxQueueDepth;this.comparator = comparator;- queue = new TreeSet<>(new TieBreakByInputComparator<>(comparator));+ queue = new TreeSet<>(pathComparator);}// If back plus this arc is competitive then add to queue:@@ -354,25 +371,29 @@ public final class Util {IntsRefBuilder newInput = new IntsRefBuilder();newInput.copyInts(path.input.get());newInput.append(path.arc.label);- final FSTPath<T> newPath = new FSTPath<>(cost, path.arc, newInput);- queue.add(newPath);+ queue.add(path.newPath(cost, newInput));if (queue.size() == maxQueueDepth+1) {queue.pollLast();}}+ public void addStartPaths(FST.Arc<T> node, T startOutput, boolean allowEmptyString, IntsRefBuilder input) throws IOException {+ addStartPaths(node, startOutput, allowEmptyString, input, 0, null);+ }+/** Adds all leaving arcs, including 'finished' arc, if* the node is final, from this node into the queue. */- public void addStartPaths(FST.Arc<T> node, T startOutput, boolean allowEmptyString, IntsRefBuilder input) throws IOException {+ public void addStartPaths(FST.Arc<T> node, T startOutput, boolean allowEmptyString, IntsRefBuilder input,+ float boost, CharSequence context) throws IOException {// De-dup NO_OUTPUT since it must be a singleton:if (startOutput.equals(fst.outputs.getNoOutput())) {startOutput = fst.outputs.getNoOutput();}- FSTPath<T> path = new FSTPath<>(startOutput, node, input);+ FSTPath<T> path = new FSTPath<>(startOutput, node, input, boost, context);fst.readFirstTargetArc(node, path.arc, bytesReader);//System.out.println("add start paths");@@ -493,10 +514,10 @@ public final class Util {if (path.arc.label == FST.END_LABEL) {// Add final output://System.out.println(" done!: " + path);- T finalOutput = fst.outputs.add(path.cost, path.arc.output);- if (acceptResult(path.input.get(), finalOutput)) {+ path.cost = fst.outputs.add(path.cost, path.arc.output);+ if (acceptResult(path)) {//System.out.println(" add result: " + path);- results.add(new Result<>(path.input.get(), finalOutput));+ results.add(new Result<>(path.input.get(), path.cost));} else {rejectCount++;}@@ -510,6 +531,10 @@ public final class Util {return new TopResults<>(rejectCount + topN <= maxQueueDepth, results);}+ protected boolean acceptResult(FSTPath<T> path) {+ return acceptResult(path.input.get(), path.cost);+ }+protected boolean acceptResult(IntsRef input, T output) {return true;}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionAnalyzer.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionAnalyzer.javaindex 4a1c30b5bb3..2bf41516985 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionAnalyzer.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionAnalyzer.java@@ -17,22 +17,10 @@ package org.apache.lucene.search.suggest.document;* limitations under the License.*/-import java.io.IOException;-import java.util.HashSet;-import java.util.LinkedList;-import java.util.Map;-import java.util.Set;-import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.AnalyzerWrapper;-import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.TokenStreamToAutomaton;-import org.apache.lucene.util.BytesRef;-import org.apache.lucene.util.BytesRefBuilder;-import org.apache.lucene.util.IOUtils;-import org.apache.lucene.util.automaton.Automaton;import org.apache.lucene.util.automaton.Operations;-import org.apache.lucene.util.automaton.Transition;/*** Wraps an {@link org.apache.lucene.analysis.Analyzer}@@ -40,15 +28,15 @@ import org.apache.lucene.util.automaton.Transition;* (e.g. preserving token separators, preserving position increments while converting* a token stream to an automaton)* <p>- * Can be used to index {@link SuggestField}- * and as a query analyzer to {@link SuggestIndexSearcher}+ * Can be used to index {@link SuggestField} and {@link ContextSuggestField}+ * and as a query analyzer to {@link PrefixCompletionQuery} amd {@link FuzzyCompletionQuery}* <p>- * NOTE: In most cases, index and query analyzer should have same values for {@link #preservePositionIncrements}- * and {@link #preserveSep}+ * NOTE: In most cases, index and query analyzer should have same values for {@link #preservePositionIncrements()}+ * and {@link #preserveSep()}** @lucene.experimental*/-public class CompletionAnalyzer extends AnalyzerWrapper {+public final class CompletionAnalyzer extends AnalyzerWrapper {/*** Represents the separation between tokens, if@@ -64,7 +52,7 @@ public class CompletionAnalyzer extends AnalyzerWrapper {*/final static int HOLE_CHARACTER = TokenStreamToAutomaton.HOLE;- final static int DEFAULT_MAX_GRAPH_EXPANSIONS = -1;+ final static int DEFAULT_MAX_GRAPH_EXPANSIONS = Operations.DEFAULT_MAX_DETERMINIZED_STATES;final static boolean DEFAULT_PRESERVE_SEP = true;final static boolean DEFAULT_PRESERVE_POSITION_INCREMENTS = true;@@ -133,6 +121,22 @@ public class CompletionAnalyzer extends AnalyzerWrapper {this(analyzer, DEFAULT_PRESERVE_SEP, DEFAULT_PRESERVE_POSITION_INCREMENTS, maxGraphExpansions);}+ /**+ * Returns true if separation between tokens are preserved when converting+ * the token stream to an automaton+ */+ public boolean preserveSep() {+ return preserveSep;+ }++ /**+ * Returns true if position increments are preserved when converting+ * the token stream to an automaton+ */+ public boolean preservePositionIncrements() {+ return preservePositionIncrements;+ }+@Overrideprotected Analyzer getWrappedAnalyzer(String fieldName) {return analyzer;@@ -141,33 +145,7 @@ public class CompletionAnalyzer extends AnalyzerWrapper {@Overrideprotected TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) {CompletionTokenStream tokenStream = new CompletionTokenStream(components.getTokenStream(),- preserveSep, preservePositionIncrements, SEP_LABEL, maxGraphExpansions);+ preserveSep, preservePositionIncrements, maxGraphExpansions);return new TokenStreamComponents(components.getTokenizer(), tokenStream);}-- /**- * Converts <code>key</code> to an automaton using- * {@link #preservePositionIncrements}, {@link #preserveSep}- * and {@link #maxGraphExpansions}- */- public Automaton toAutomaton(String field, CharSequence key) throws IOException {- for (int i = 0; i < key.length(); i++) {- switch (key.charAt(i)) {- case HOLE_CHARACTER:- throw new IllegalArgumentException("lookup key cannot contain HOLE character U+001E; this character is reserved");- case SEP_LABEL:- throw new IllegalArgumentException("lookup key cannot contain unit separator character U+001F; this character is reserved");- default:- break;- }- }-- try (TokenStream tokenStream = analyzer.tokenStream(field, key.toString())) {- try(CompletionTokenStream stream = new CompletionTokenStream(tokenStream,- preserveSep, preservePositionIncrements, SEP_LABEL, maxGraphExpansions)) {- return stream.toAutomaton(tokenStream);- }- }- }-}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.javaindex da7ae5df48e..5654bb4f2ff 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java@@ -58,7 +58,7 @@ import static org.apache.lucene.search.suggest.document.CompletionPostingsFormatfinal class CompletionFieldsConsumer extends FieldsConsumer {private final String delegatePostingsFormatName;- private final Map<String, Long> seenFields = new HashMap<>();+ private final Map<String, CompletionMetaData> seenFields = new HashMap<>();private final SegmentWriteState state;private IndexOutput dictOut;private FieldsConsumer delegateFieldsConsumer;@@ -98,7 +98,10 @@ final class CompletionFieldsConsumer extends FieldsConsumer {// store lookup, if neededlong filePointer = dictOut.getFilePointer();if (termWriter.finish(dictOut)) {- seenFields.put(field, filePointer);+ seenFields.put(field, new CompletionMetaData(filePointer,+ termWriter.minWeight,+ termWriter.maxWeight,+ termWriter.type));}}}@@ -124,10 +127,14 @@ final class CompletionFieldsConsumer extends FieldsConsumer {// write # of seen fieldsindexOut.writeVInt(seenFields.size());// write field numbers and dictOut offsets- for (Map.Entry<String, Long> seenField : seenFields.entrySet()) {+ for (Map.Entry<String, CompletionMetaData> seenField : seenFields.entrySet()) {FieldInfo fieldInfo = state.fieldInfos.fieldInfo(seenField.getKey());indexOut.writeVInt(fieldInfo.number);- indexOut.writeVLong(seenField.getValue());+ CompletionMetaData metaData = seenField.getValue();+ indexOut.writeVLong(metaData.filePointer);+ indexOut.writeVLong(metaData.minWeight);+ indexOut.writeVLong(metaData.maxWeight);+ indexOut.writeByte(metaData.type);}CodecUtil.writeFooter(indexOut);CodecUtil.writeFooter(dictOut);@@ -140,17 +147,36 @@ final class CompletionFieldsConsumer extends FieldsConsumer {}}+ private static class CompletionMetaData {+ private final long filePointer;+ private final long minWeight;+ private final long maxWeight;+ private final byte type;++ private CompletionMetaData(long filePointer, long minWeight, long maxWeight, byte type) {+ this.filePointer = filePointer;+ this.minWeight = minWeight;+ this.maxWeight = maxWeight;+ this.type = type;+ }+ }+// builds an FST based on the terms writtenprivate static class CompletionTermWriter {private PostingsEnum postingsEnum = null;private int docCount = 0;+ private long maxWeight = 0;+ private long minWeight = Long.MAX_VALUE;+ private byte type;+ private boolean first;private final BytesRefBuilder scratch = new BytesRefBuilder();private final NRTSuggesterBuilder builder;public CompletionTermWriter() {builder = new NRTSuggesterBuilder();+ first = true;}/**@@ -160,6 +186,9 @@ final class CompletionFieldsConsumer extends FieldsConsumer {public boolean finish(IndexOutput output) throws IOException {boolean stored = builder.store(output);assert stored || docCount == 0 : "the FST is null but docCount is != 0 actual value: [" + docCount + "]";+ if (docCount == 0) {+ minWeight = 0;+ }return stored;}@@ -181,7 +210,17 @@ final class CompletionFieldsConsumer extends FieldsConsumer {scratch.grow(len);scratch.setLength(len);input.readBytes(scratch.bytes(), 0, scratch.length());- builder.addEntry(docID, scratch.get(), input.readVLong() - 1);+ long weight = input.readVInt() - 1;+ maxWeight = Math.max(maxWeight, weight);+ minWeight = Math.min(minWeight, weight);+ byte type = input.readByte();+ if (first) {+ this.type = type;+ first = false;+ } else if (this.type != type) {+ throw new IllegalArgumentException("single field name has mixed types");+ }+ builder.addEntry(docID, scratch.get(), weight);}docFreq++;docCount = Math.max(docCount, docFreq + 1);diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsProducer.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsProducer.javaindex a205826bf2e..1ef3d5f9774 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsProducer.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsProducer.java@@ -30,7 +30,6 @@ import org.apache.lucene.codecs.CodecUtil;import org.apache.lucene.codecs.FieldsProducer;import org.apache.lucene.codecs.PostingsFormat;import org.apache.lucene.index.FieldInfo;-import org.apache.lucene.index.FilterLeafReader;import org.apache.lucene.index.IndexFileNames;import org.apache.lucene.index.SegmentReadState;import org.apache.lucene.index.Terms;@@ -98,9 +97,12 @@ final class CompletionFieldsProducer extends FieldsProducer {for (int i = 0; i < numFields; i++) {int fieldNumber = index.readVInt();long offset = index.readVLong();+ long minWeight = index.readVLong();+ long maxWeight = index.readVLong();+ byte type = index.readByte();FieldInfo fieldInfo = state.fieldInfos.fieldInfo(fieldNumber);// we don't load the FST yet- readers.put(fieldInfo.name, new CompletionsTermsReader(offset));+ readers.put(fieldInfo.name, new CompletionsTermsReader(dictIn, offset, minWeight, maxWeight, type));}CodecUtil.checkFooter(index);success = true;@@ -161,7 +163,11 @@ final class CompletionFieldsProducer extends FieldsProducer {@Overridepublic Terms terms(String field) throws IOException {- return new CompletionTerms(delegateFieldsProducer.terms(field), readers.get(field));+ Terms terms = delegateFieldsProducer.terms(field) ;+ if (terms == null) {+ return null;+ }+ return new CompletionTerms(terms, readers.get(field));}@Override@@ -169,60 +175,4 @@ final class CompletionFieldsProducer extends FieldsProducer {return readers.size();}- private class CompletionsTermsReader implements Accountable {- private final long offset;- private NRTSuggester suggester;-- public CompletionsTermsReader(long offset) throws IOException {- assert offset >= 0l && offset < dictIn.length();- this.offset = offset;- }-- public synchronized NRTSuggester suggester() throws IOException {- if (suggester == null) {- try (IndexInput dictClone = dictIn.clone()) { // let multiple fields load concurrently- dictClone.seek(offset);- suggester = NRTSuggester.load(dictClone);- }- }- return suggester;- }-- @Override- public long ramBytesUsed() {- return (suggester != null) ? suggester.ramBytesUsed() : 0;- }-- @Override- public Collection<Accountable> getChildResources() {- return Collections.emptyList();- }- }-- /**- * Thin wrapper over {@link org.apache.lucene.index.Terms} with- * a {@link NRTSuggester}- */- public static class CompletionTerms extends FilterLeafReader.FilterTerms {-- private final CompletionsTermsReader reader;-- public CompletionTerms(Terms in, CompletionsTermsReader reader) {- super(in);- this.reader = reader;- }-- /**- * Returns a {@link NRTSuggester} for the field- * or <code>null</code> if no FST- * was indexed for this field- */- public NRTSuggester suggester() throws IOException {- if (reader == null) {- return null;- }- return reader.suggester();- }- }-}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionPostingsFormat.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionPostingsFormat.javaindex 89b87bcfc32..d2e3e9f8f51 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionPostingsFormat.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionPostingsFormat.java@@ -68,9 +68,12 @@ import org.apache.lucene.util.fst.FST;* <li>CompletionIndex (.cmp) --> Header, NumSuggestFields, Entry<sup>NumSuggestFields</sup>, Footer</li>* <li>Header --> {@link CodecUtil#writeHeader CodecHeader}</li>* <li>NumSuggestFields --> {@link DataOutput#writeVInt Uint32}</li>- * <li>Entry --> FieldNumber, CompletionDictionaryOffset</li>+ * <li>Entry --> FieldNumber, CompletionDictionaryOffset, MinWeight, MaxWeight, Type</li>* <li>FieldNumber --> {@link DataOutput#writeVInt Uint32}</li>* <li>CompletionDictionaryOffset --> {@link DataOutput#writeVLong Uint64}</li>+ * <li>MinWeight --> {@link DataOutput#writeVLong Uint64}</li>+ * <li>MaxWeight --> {@link DataOutput#writeVLong Uint64}</li>+ * <li>Type --> {@link DataOutput#writeByte Byte}</li>* <li>Footer --> {@link CodecUtil#writeFooter CodecFooter}</li>* </ul>* <p>Notes:</p>@@ -80,6 +83,8 @@ import org.apache.lucene.util.fst.FST;* <li>NumSuggestFields is the number of suggest fields indexed</li>* <li>FieldNumber is the fields number from {@link FieldInfos}. (.fnm)</li>* <li>CompletionDictionaryOffset is the file offset of a field's FST in CompletionDictionary (.lkp)</li>+ * <li>MinWeight and MaxWeight are the global minimum and maximum weight for the field</li>+ * <li>Type indicates if the suggester has context or not</li>* </ul>** @lucene.experimentaldiff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.javanew file mode 100644index 00000000000..eb2ba221814--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java@@ -0,0 +1,170 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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 org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.LeafReader;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.Terms;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.Query;++import static org.apache.lucene.search.suggest.document.CompletionAnalyzer.HOLE_CHARACTER;+import static org.apache.lucene.search.suggest.document.CompletionAnalyzer.SEP_LABEL;++/**+ * Abstract {@link Query} that match documents containing terms with a specified prefix+ * filtered by {@link Filter}. This should be used to query against any {@link SuggestField}s+ * or {@link ContextSuggestField}s of documents.+ * <p>+ * Use {@link SuggestIndexSearcher#suggest(CompletionQuery, int)} to execute any query+ * that provides a concrete implementation of this query. Example below shows using this query+ * to retrieve the top 5 documents.+ *+ * <pre class="prettyprint">+ * SuggestIndexSearcher searcher = new SuggestIndexSearcher(reader);+ * TopSuggestDocs suggestDocs = searcher.suggest(query, 5);+ * </pre>+ * This query rewrites to an appropriate {@link CompletionQuery} depending on the+ * type ({@link SuggestField} or {@link ContextSuggestField}) of the field the query is run against.+ *+ * @lucene.experimental+ */+public abstract class CompletionQuery extends Query {++ /**+ * Term to query against+ */+ private final Term term;++ /**+ * Filter for document scoping+ */+ private final Filter filter;++ /**+ * Creates a base Completion query against a <code>term</code>+ * with a <code>filter</code> to scope the documents+ */+ protected CompletionQuery(Term term, Filter filter) {+ validate(term.text());+ this.term = term;+ this.filter = filter;+ }++ /**+ * Returns the filter for the query, used to+ * suggest completions on a subset of indexed documents+ */+ public Filter getFilter() {+ return filter;+ }++ /**+ * Returns the field name this query should+ * be run against+ */+ public String getField() {+ return term.field();+ }++ /**+ * Returns the term to be queried against+ */+ public Term getTerm() {+ return term;+ }++ @Override+ public Query rewrite(IndexReader reader) throws IOException {+ byte type = 0;+ boolean first = true;+ Terms terms;+ for (LeafReaderContext context : reader.leaves()) {+ LeafReader leafReader = context.reader();+ try {+ if ((terms = leafReader.terms(getField())) == null) {+ continue;+ }+ } catch (IOException e) {+ continue;+ }+ if (terms instanceof CompletionTerms) {+ CompletionTerms completionTerms = (CompletionTerms) terms;+ byte t = completionTerms.getType();+ if (first) {+ type = t;+ first = false;+ } else if (type != t) {+ throw new IllegalStateException(getField() + " has values of multiple types");+ }+ }+ }++ if (first == false) {+ if (this instanceof ContextQuery) {+ if (type == SuggestField.TYPE) {+ throw new IllegalStateException(this.getClass().getSimpleName()+ + " can not be executed against a non context-enabled SuggestField: "+ + getField());+ }+ } else {+ if (type == ContextSuggestField.TYPE) {+ return new ContextQuery(this);+ }+ }+ }+ return this;+ }++ @Override+ public String toString(String field) {+ StringBuilder buffer = new StringBuilder();+ if (!term.field().equals(field)) {+ buffer.append(term.field());+ buffer.append(":");+ }+ buffer.append(term.text());+ buffer.append('*');+ if (filter != null) {+ buffer.append(",");+ buffer.append("filter");+ buffer.append(":");+ buffer.append(filter.toString(field));+ }+ return buffer.toString();+ }++ private void validate(String termText) {+ for (int i = 0; i < termText.length(); i++) {+ switch (termText.charAt(i)) {+ case HOLE_CHARACTER:+ throw new IllegalArgumentException(+ "Term text cannot contain HOLE character U+001E; this character is reserved");+ case SEP_LABEL:+ throw new IllegalArgumentException(+ "Term text cannot contain unit separator character U+001F; this character is reserved");+ default:+ break;+ }+ }+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionScorer.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionScorer.javanew file mode 100644index 00000000000..d1b6679900b--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionScorer.java@@ -0,0 +1,103 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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 org.apache.lucene.index.LeafReader;+import org.apache.lucene.search.BulkScorer;+import org.apache.lucene.search.LeafCollector;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.automaton.Automaton;++/**+ * Expert: Responsible for executing the query against an+ * appropriate suggester and collecting the results+ * via a collector.+ *+ * {@link #score(LeafCollector, int, int)} is called+ * for each leaf reader.+ *+ * {@link #accept(int)} and {@link #score(float, float)}+ * is called for every matched completion (i.e. document)+ *+ * @lucene.experimental+ */+public class CompletionScorer extends BulkScorer {+ private final NRTSuggester suggester;+ private final Bits acceptDocs;++ // values accessed by suggester+ /** weight that created this scorer */+ protected final CompletionWeight weight;+ final LeafReader reader;+ final boolean filtered;+ final Automaton automaton;++ /**+ * Creates a scorer for a field-specific <code>suggester</code> scoped by <code>acceptDocs</code>+ */+ protected CompletionScorer(final CompletionWeight weight, final NRTSuggester suggester,+ final LeafReader reader, final Bits acceptDocs,+ final boolean filtered, final Automaton automaton) throws IOException {+ this.weight = weight;+ this.suggester = suggester;+ this.reader = reader;+ this.automaton = automaton;+ this.filtered = filtered;+ this.acceptDocs = acceptDocs;+ }++ @Override+ public int score(LeafCollector collector, int min, int max) throws IOException {+ if (!(collector instanceof TopSuggestDocsCollector)) {+ throw new IllegalArgumentException("collector is not of type TopSuggestDocsCollector");+ }+ suggester.lookup(this, ((TopSuggestDocsCollector) collector));+ return max;+ }++ @Override+ public long cost() {+ return 0;+ }++ /**+ * Returns true if a document with <code>docID</code> is accepted,+ * false if the docID maps to a deleted+ * document or has been filtered out+ */+ public final boolean accept(int docID) {+ return acceptDocs == null || acceptDocs.get(docID);+ }++ /**+ * Returns the score for a matched completion+ * based on the query time boost and the+ * index time weight.+ */+ public float score(float weight, float boost) {+ if (boost == 0f) {+ return weight;+ }+ if (weight == 0f) {+ return boost;+ }+ return weight * boost;+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionTerms.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionTerms.javanew file mode 100644index 00000000000..6accac4678f--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionTerms.java@@ -0,0 +1,74 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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 org.apache.lucene.index.FilterLeafReader;+import org.apache.lucene.index.Terms;++/**+ * Wrapped {@link org.apache.lucene.index.Terms}+ * used by {@link SuggestField} and {@link ContextSuggestField}+ * to access corresponding suggester and their attributes+ *+ * @lucene.experimental+ */+public final class CompletionTerms extends FilterLeafReader.FilterTerms {++ private final CompletionsTermsReader reader;++ /**+ * Creates a completionTerms based on {@link CompletionsTermsReader}+ */+ CompletionTerms(Terms in, CompletionsTermsReader reader) {+ super(in);+ this.reader = reader;+ }++ /**+ * Returns the type of FST, either {@link SuggestField#TYPE} or+ * {@link ContextSuggestField#TYPE}+ */+ public byte getType() {+ return (reader != null) ? reader.type : SuggestField.TYPE;+ }++ /**+ * Returns the minimum weight of all entries in the weighted FST+ */+ public long getMinWeight() {+ return (reader != null) ? reader.minWeight : 0;+ }++ /**+ * Returns the maximum weight of all entries in the weighted FST+ */+ public long getMaxWeight() {+ return (reader != null) ? reader.maxWeight : 0;+ }++ /**+ * Returns a {@link NRTSuggester} for the field+ * or <code>null</code> if no FST+ * was indexed for this field+ */+ public NRTSuggester suggester() throws IOException {+ return (reader != null) ? reader.suggester() : null;+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionTokenStream.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionTokenStream.javaindex 3acd7136816..d5adf68f50d 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionTokenStream.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionTokenStream.java@@ -18,7 +18,7 @@ package org.apache.lucene.search.suggest.document;*/import java.io.IOException;-import java.util.HashSet;+import java.util.BitSet;import java.util.Iterator;import java.util.LinkedList;import java.util.Set;@@ -52,18 +52,18 @@ import static org.apache.lucene.search.suggest.document.CompletionAnalyzer.SEP_L* The token stream uses a {@link org.apache.lucene.analysis.tokenattributes.PayloadAttribute} to store* a completion's payload (see {@link CompletionTokenStream#setPayload(org.apache.lucene.util.BytesRef)})*+ * @lucene.experimental*/-final class CompletionTokenStream extends TokenStream {+public final class CompletionTokenStream extends TokenStream {private final PayloadAttribute payloadAttr = addAttribute(PayloadAttribute.class);private final PositionIncrementAttribute posAttr = addAttribute(PositionIncrementAttribute.class);private final ByteTermAttribute bytesAtt = addAttribute(ByteTermAttribute.class);private final TokenStream input;- private final boolean preserveSep;- private final boolean preservePositionIncrements;- private final int sepLabel;- private final int maxGraphExpansions;+ final boolean preserveSep;+ final boolean preservePositionIncrements;+ final int maxGraphExpansions;private BytesRef payload;private Iterator<IntsRef> finiteStrings;@@ -77,28 +77,19 @@ final class CompletionTokenStream extends TokenStream {* The token stream <code>input</code> is converted to an automaton* with the default settings of {@link org.apache.lucene.search.suggest.document.CompletionAnalyzer}*/- public CompletionTokenStream(TokenStream input) {- this(input, DEFAULT_PRESERVE_SEP, DEFAULT_PRESERVE_POSITION_INCREMENTS, SEP_LABEL, DEFAULT_MAX_GRAPH_EXPANSIONS);+ CompletionTokenStream(TokenStream input) {+ this(input, DEFAULT_PRESERVE_SEP, DEFAULT_PRESERVE_POSITION_INCREMENTS, DEFAULT_MAX_GRAPH_EXPANSIONS);}- CompletionTokenStream(TokenStream input, boolean preserveSep, boolean preservePositionIncrements, int sepLabel, int maxGraphExpansions) {+ CompletionTokenStream(TokenStream input, boolean preserveSep, boolean preservePositionIncrements, int maxGraphExpansions) {// Don't call the super(input) ctor - this is a true delegate and has a new attribute source since we consume// the input stream entirely in toFiniteStrings(input)this.input = input;this.preserveSep = preserveSep;this.preservePositionIncrements = preservePositionIncrements;- this.sepLabel = sepLabel;this.maxGraphExpansions = maxGraphExpansions;}- /**- * Returns a separator label that is reserved for the payload- * in {@link CompletionTokenStream#setPayload(org.apache.lucene.util.BytesRef)}- */- public int sepLabel() {- return sepLabel;- }-/*** Sets a payload available throughout successive token stream enumeration*/@@ -111,7 +102,7 @@ final class CompletionTokenStream extends TokenStream {clearAttributes();if (finiteStrings == null) {//TODO: make this return a Iterator<IntsRef> instead?- Automaton automaton = toAutomaton(input);+ Automaton automaton = toAutomaton();Set<IntsRef> strings = Operations.getFiniteStrings(automaton, maxGraphExpansions);posInc = strings.size();@@ -165,9 +156,17 @@ final class CompletionTokenStream extends TokenStream {}/**- * Converts <code>tokenStream</code> to an automaton+ * Converts the token stream to an automaton,+ * treating the transition labels as utf-8+ */+ public Automaton toAutomaton() throws IOException {+ return toAutomaton(false);+ }++ /**+ * Converts the tokenStream to an automaton*/- public Automaton toAutomaton(TokenStream tokenStream) throws IOException {+ public Automaton toAutomaton(boolean unicodeAware) throws IOException {// TODO refactor this// maybe we could hook up a modified automaton from TermAutomatonQuery here?Automaton automaton = null;@@ -184,10 +183,11 @@ final class CompletionTokenStream extends TokenStream {tsta = new TokenStreamToAutomaton();}tsta.setPreservePositionIncrements(preservePositionIncrements);+ tsta.setUnicodeArcs(unicodeAware);- automaton = tsta.toAutomaton(tokenStream);+ automaton = tsta.toAutomaton(input);} finally {- IOUtils.closeWhileHandlingException(tokenStream);+ IOUtils.closeWhileHandlingException(input);}// TODO: we can optimize this somewhat by determinizing@@ -281,11 +281,12 @@ final class CompletionTokenStream extends TokenStream {}private static int[] topoSortStates(Automaton a) {- int[] states = new int[a.getNumStates()];- final Set<Integer> visited = new HashSet<>();+ int numStates = a.getNumStates();+ int[] states = new int[numStates];+ final BitSet visited = new BitSet(numStates);final LinkedList<Integer> worklist = new LinkedList<>();worklist.add(0);- visited.add(0);+ visited.set(0);int upto = 0;states[upto] = 0;upto++;@@ -293,10 +294,10 @@ final class CompletionTokenStream extends TokenStream {while (worklist.size() > 0) {int s = worklist.removeFirst();int count = a.initTransition(s, t);- for (int i = 0; i < count; i++) {+ for (int i=0;i<count;i++) {a.getNextTransition(t);- if (!visited.contains(t.dest)) {- visited.add(t.dest);+ if (!visited.get(t.dest)) {+ visited.set(t.dest);worklist.add(t.dest);states[upto++] = t.dest;}@@ -305,21 +306,37 @@ final class CompletionTokenStream extends TokenStream {return states;}- public interface ByteTermAttribute extends TermToBytesRefAttribute {+ /**+ * Attribute providing access to the term builder and UTF-16 conversion+ */+ private interface ByteTermAttribute extends TermToBytesRefAttribute {// marker interface/**- * Return the builder from which the term is derived.+ * Returns the builder from which the term is derived.*/- public BytesRefBuilder builder();+ BytesRefBuilder builder();- public CharSequence toUTF16();+ /**+ * Returns the term represented as UTF-16+ */+ CharSequence toUTF16();}+ /**+ * Custom attribute implementation for completion token stream+ */public static final class ByteTermAttributeImpl extends AttributeImpl implements ByteTermAttribute, TermToBytesRefAttribute {private final BytesRefBuilder bytes = new BytesRefBuilder();private CharsRefBuilder charsRef;+ /**+ * Sole constructor+ * no-op+ */+ public ByteTermAttributeImpl() {+ }+@Overridepublic void fillBytesRef() {// does nothing - we change in placediff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.javanew file mode 100644index 00000000000..dec1578e893--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java@@ -0,0 +1,209 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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.Set;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.LeafReader;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.Terms;+import org.apache.lucene.search.BulkScorer;+import org.apache.lucene.search.DocIdSet;+import org.apache.lucene.search.Explanation;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.Scorer;+import org.apache.lucene.search.Weight;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.IntsRef;+import org.apache.lucene.util.automaton.Automaton;++/**+ * Expert: the Weight for CompletionQuery, used to+ * score and explain these queries.+ *+ * Subclasses can override {@link #setNextMatch(IntsRef)},+ * {@link #boost()} and {@link #context()}+ * to calculate the boost and extract the context of+ * a matched path prefix.+ *+ * @lucene.experimental+ */+public class CompletionWeight extends Weight {+ private final CompletionQuery completionQuery;+ private final Automaton automaton;+ private final long maxWeight;+ private final long minWeight;++ /**+ * Creates a weight for <code>query</code> with an <code>automaton</code>,+ * using the <code>reader</code> for index stats+ */+ public CompletionWeight(final IndexReader reader, final CompletionQuery query,+ final Automaton automaton) throws IOException {+ super(query);+ this.completionQuery = query;+ this.automaton = automaton;+ this.minWeight = minWeight(query.getField(), reader);+ this.maxWeight = maxWeight(query.getField(), reader);+ }++ /**+ * Returns the automaton specified+ * by the {@link CompletionQuery}+ *+ * @return query automaton+ */+ public Automaton getAutomaton() {+ return automaton;+ }++ @Override+ public BulkScorer bulkScorer(final LeafReaderContext context, Bits acceptDocs) throws IOException {+ final LeafReader reader = context.reader();+ final Terms terms;+ final NRTSuggester suggester;+ if ((terms = reader.terms(completionQuery.getField())) == null) {+ return null;+ }+ if (terms instanceof CompletionTerms) {+ CompletionTerms completionTerms = (CompletionTerms) terms;+ if ((suggester = completionTerms.suggester()) == null) {+ // a segment can have a null suggester+ // i.e. no FST was built+ return null;+ }+ } else {+ throw new IllegalArgumentException(completionQuery.getField() + " is not a SuggestField");+ }++ DocIdSet docIdSet = null;+ Filter filter = completionQuery.getFilter();+ if (filter != null) {+ docIdSet = filter.getDocIdSet(context, acceptDocs);+ if (docIdSet == null || docIdSet.iterator() == null) {+ // filter matches no docs in current leave+ return null;+ } else if (docIdSet.bits() == null) {+ throw new IllegalArgumentException("DocIDSet does not provide random access interface");+ }+ }+ Bits acceptDocBits = (docIdSet != null) ? docIdSet.bits() : acceptDocs;+ return new CompletionScorer(this, suggester, reader, acceptDocBits, filter != null, automaton);+ }++ /**+ * Set for every partial path in the index that matched the query+ * automaton.+ *+ * Subclasses should override {@link #boost()} and {@link #context()}+ * to return an appropriate value with respect to the current pathPrefix.+ *+ * @param pathPrefix the prefix of a matched path+ */+ protected void setNextMatch(IntsRef pathPrefix) {+ }++ /**+ * Returns the boost of the partial path set by {@link #setNextMatch(IntsRef)}+ *+ * @return suggestion query-time boost+ */+ protected float boost() {+ return 0;+ }++ /**+ * Returns the context of the partial path set by {@link #setNextMatch(IntsRef)}+ *+ * @return suggestion context+ */+ protected CharSequence context() {+ return null;+ }++ private static long minWeight(String field, IndexReader reader) {+ long minWeight = Long.MAX_VALUE;+ Terms terms;+ for (LeafReaderContext context : reader.leaves()) {+ LeafReader leafReader = context.reader();+ try {+ if ((terms = leafReader.terms(field)) == null) {+ continue;+ }+ } catch (IOException e) {+ continue;+ }+ if (terms instanceof CompletionTerms) {+ CompletionTerms completionTerms = (CompletionTerms) terms;+ minWeight = Math.min(completionTerms.getMinWeight(), minWeight);+ }+ }+ if (minWeight == Long.MAX_VALUE) {+ minWeight = 0;+ }+ return minWeight;+ }++ private static long maxWeight(String field, IndexReader reader) {+ long maxWeight = 0;+ Terms terms;+ for (LeafReaderContext context : reader.leaves()) {+ LeafReader leafReader = context.reader();+ try {+ if ((terms = leafReader.terms(field)) == null) {+ continue;+ }+ } catch (IOException e) {+ continue;+ }+ if (terms instanceof CompletionTerms) {+ CompletionTerms completionTerms = (CompletionTerms) terms;+ maxWeight = Math.max(completionTerms.getMaxWeight(), maxWeight);+ }+ }+ return maxWeight;+ }++ @Override+ public Scorer scorer(LeafReaderContext context, Bits acceptDocs) throws IOException {+ throw new UnsupportedOperationException();+ }++ @Override+ public void extractTerms(Set<Term> terms) {+ // no-op+ }++ @Override+ public Explanation explain(LeafReaderContext context, int doc) throws IOException {+ //TODO+ return null;+ }++ @Override+ public float getValueForNormalization() throws IOException {+ return 0;+ }++ @Override+ public void normalize(float norm, float topLevelBoost) {+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionsTermsReader.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionsTermsReader.javanew file mode 100644index 00000000000..35e2d4647e5--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionsTermsReader.java@@ -0,0 +1,82 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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.Collection;+import java.util.Collections;++import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.Accountable;++/**+ * Holder for suggester and field-level info+ * for a suggest field+ *+ * @lucene.experimental+ */+public final class CompletionsTermsReader implements Accountable {+ /** Minimum entry weight for the suggester */+ public final long minWeight;+ /** Maximum entry weight for the suggester */+ public final long maxWeight;+ /** type of suggester (context-enabled or not) */+ public final byte type;+ private final IndexInput dictIn;+ private final long offset;++ private NRTSuggester suggester;++ /**+ * Creates a CompletionTermsReader to load a field-specific suggester+ * from the index <code>dictIn</code> with <code>offset</code>+ */+ CompletionsTermsReader(IndexInput dictIn, long offset, long minWeight, long maxWeight, byte type) throws IOException {+ assert minWeight <= maxWeight;+ assert offset >= 0l && offset < dictIn.length();+ this.dictIn = dictIn;+ this.offset = offset;+ this.minWeight = minWeight;+ this.maxWeight = maxWeight;+ this.type = type;+ }++ /**+ * Returns the suggester for a field, if not loaded already, loads+ * the appropriate suggester from CompletionDictionary+ */+ public synchronized NRTSuggester suggester() throws IOException {+ if (suggester == null) {+ try (IndexInput dictClone = dictIn.clone()) { // let multiple fields load concurrently+ dictClone.seek(offset);+ suggester = NRTSuggester.load(dictClone);+ }+ }+ return suggester;+ }++ @Override+ public long ramBytesUsed() {+ return (suggester != null) ? suggester.ramBytesUsed() : 0;+ }++ @Override+ public Collection<Accountable> getChildResources() {+ return Collections.emptyList();+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/ContextQuery.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/ContextQuery.javanew file mode 100644index 00000000000..5ebe55c6d88--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/ContextQuery.java@@ -0,0 +1,307 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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.HashMap;+import java.util.Iterator;+import java.util.Map;+import java.util.TreeSet;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Weight;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.BytesRefBuilder;+import org.apache.lucene.util.IntsRef;+import org.apache.lucene.util.IntsRefBuilder;+import org.apache.lucene.util.automaton.Automata;+import org.apache.lucene.util.automaton.Automaton;+import org.apache.lucene.util.automaton.Operations;+import org.apache.lucene.util.automaton.RegExp;+import org.apache.lucene.util.fst.Util;++/**+ * A {@link CompletionQuery} that match documents specified by+ * a wrapped {@link CompletionQuery} supporting boosting and/or filtering+ * by specified contexts.+ * <p>+ * Use this query against {@link ContextSuggestField}+ * <p>+ * Example of using a {@link CompletionQuery} with boosted+ * contexts:+ * <pre class="prettyprint">+ * CompletionQuery completionQuery = ...;+ * ContextQuery query = new ContextQuery(completionQuery);+ * query.addContext("context1", 2);+ * query.addContext("context2", 1);+ * </pre>+ * <p>+ * NOTE:+ * <ul>+ * <li>+ * This query can be constructed with+ * {@link PrefixCompletionQuery}, {@link RegexCompletionQuery}+ * or {@link FuzzyCompletionQuery} query.+ * </li>+ * <li>+ * To suggest across all contexts with the same boost,+ * use '*' as the context in {@link #addContext(CharSequence)})}.+ * This can be combined with specific contexts with different boosts.+ * </li>+ * <li>+ * To apply the same boost to multiple contexts sharing the same prefix,+ * Use {@link #addContext(CharSequence, float, boolean)} with the common+ * context prefix, boost and set <code>exact</code> to false.+ * <li>+ * Using this query against a {@link SuggestField} (not context enabled),+ * would yield results ignoring any context filtering/boosting+ * </li>+ * </ul>+ *+ * @lucene.experimental+ */+public class ContextQuery extends CompletionQuery {+ private Map<CharSequence, ContextMetaData> contexts;+ /** Inner completion query */+ protected CompletionQuery query;++ /**+ * Constructs a context completion query that matches+ * documents specified by <code>query</code>.+ * <p>+ * Use {@link #addContext(CharSequence, float, boolean)}+ * to add context(s) with boost+ */+ public ContextQuery(CompletionQuery query) {+ super(query.getTerm(), query.getFilter());+ if (query instanceof ContextQuery) {+ throw new IllegalArgumentException("'query' parameter must not be of type "+ + this.getClass().getSimpleName());+ }+ this.query = query;+ contexts = new HashMap<>();+ }++ /**+ * Adds an exact context with default boost of 1+ */+ public void addContext(CharSequence context) {+ addContext(context, 1f, true);+ }++ /**+ * Adds an exact context with boost+ */+ public void addContext(CharSequence context, float boost) {+ addContext(context, boost, true);+ }++ /**+ * Adds a context with boost, set <code>exact</code> to false+ * if the context is a prefix of any indexed contexts+ */+ public void addContext(CharSequence context, float boost, boolean exact) {+ if (boost < 0f) {+ throw new IllegalArgumentException("'boost' must be >= 0");+ }+ for (int i = 0; i < context.length(); i++) {+ if (ContextSuggestField.CONTEXT_SEPARATOR == context.charAt(i)) {+ throw new IllegalArgumentException("Illegal value [" + context + "] UTF-16 codepoint [0x"+ + Integer.toHexString((int) context.charAt(i))+ "] at position " + i + " is a reserved character");+ }+ }+ contexts.put(context, new ContextMetaData(boost, exact));+ }++ @Override+ public String toString(String field) {+ StringBuilder buffer = new StringBuilder();+ for (CharSequence context : contexts.keySet()) {+ if (buffer.length() != 0) {+ buffer.append(",");+ } else {+ buffer.append("contexts");+ buffer.append(":[");+ }+ buffer.append(context);+ ContextMetaData metaData = contexts.get(context);+ if (metaData.exact == false) {+ buffer.append("*");+ }+ if (metaData.boost != 0) {+ buffer.append("^");+ buffer.append(Float.toString(metaData.boost));+ }+ }+ if (buffer.length() != 0) {+ buffer.append("]");+ buffer.append(",");+ }+ return buffer.toString() + query.toString(field);+ }++ @Override+ public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {+ IntsRefBuilder scratch = new IntsRefBuilder();+ final Map<IntsRef, Float> contextMap = new HashMap<>(contexts.size());+ final TreeSet<Integer> contextLengths = new TreeSet<>();+ final CompletionWeight innerWeight = ((CompletionWeight) query.createWeight(searcher, needsScores));+ Automaton contextsAutomaton = null;+ Automaton gap = Automata.makeChar(ContextSuggestField.CONTEXT_SEPARATOR);+ // if separators are preserved the fst contains a SEP_LABEL+ // behind each gap. To have a matching automaton, we need to+ // include the SEP_LABEL in the query as well+ gap = Operations.concatenate(gap, Operations.optional(Automata.makeChar(CompletionAnalyzer.SEP_LABEL)));+ final Automaton prefixAutomaton = Operations.concatenate(gap, innerWeight.getAutomaton());+ final Automaton matchAllAutomaton = new RegExp(".*").toAutomaton();+ for (Map.Entry<CharSequence, ContextMetaData> entry : contexts.entrySet()) {+ Automaton contextAutomaton;+ if (entry.getKey().equals("*")) {+ contextAutomaton = Operations.concatenate(matchAllAutomaton, prefixAutomaton);+ } else {+ BytesRef ref = new BytesRef(entry.getKey());+ ContextMetaData contextMetaData = entry.getValue();+ contextMap.put(IntsRef.deepCopyOf(Util.toIntsRef(ref, scratch)), contextMetaData.boost);+ contextLengths.add(scratch.length());+ contextAutomaton = Automata.makeString(entry.getKey().toString());+ if (contextMetaData.exact) {+ contextAutomaton = Operations.concatenate(contextAutomaton, prefixAutomaton);+ } else {+ contextAutomaton = Operations.concatenate(Arrays.asList(contextAutomaton,+ matchAllAutomaton,+ prefixAutomaton));+ }+ }+ if (contextsAutomaton == null) {+ contextsAutomaton = contextAutomaton;+ } else {+ contextsAutomaton = Operations.union(contextsAutomaton, contextAutomaton);+ }+ }+ if (contexts.size() == 0) {+ addContext("*");+ contextsAutomaton = Operations.concatenate(matchAllAutomaton, prefixAutomaton);+ }+ contextsAutomaton = Operations.determinize(contextsAutomaton, Operations.DEFAULT_MAX_DETERMINIZED_STATES);+ int[] contextLengthArray = new int[contextLengths.size()];+ final Iterator<Integer> iterator = contextLengths.descendingIterator();+ for (int i = 0; iterator.hasNext(); i++) {+ contextLengthArray[i] = iterator.next();+ }+ return new ContextCompletionWeight(searcher.getIndexReader(), this, contextsAutomaton,+ innerWeight, contextMap, contextLengthArray);+ }++ private static class ContextMetaData {+ private final float boost;+ private final boolean exact;++ private ContextMetaData(float boost, boolean exact) {+ this.boost = boost;+ this.exact = exact;+ }+ }++ private class ContextCompletionWeight extends CompletionWeight {++ private final Map<IntsRef, Float> contextMap;+ private final int[] contextLengths;+ private final CompletionWeight innerWeight;+ private final BytesRefBuilder scratch = new BytesRefBuilder();++ private float currentBoost;+ private CharSequence currentContext;++ public ContextCompletionWeight(IndexReader reader, CompletionQuery query,+ Automaton automaton, CompletionWeight innerWeight,+ Map<IntsRef, Float> contextMap,+ int[] contextLengths) throws IOException {+ super(reader, query, automaton);+ this.contextMap = contextMap;+ this.contextLengths = contextLengths;+ this.innerWeight = innerWeight;+ }++ @Override+ protected void setNextMatch(IntsRef pathPrefix) {+ IntsRef ref = pathPrefix.clone();++ // check if the pathPrefix matches any+ // defined context, longer context first+ for (int contextLength : contextLengths) {+ if (contextLength > pathPrefix.length) {+ continue;+ }+ ref.length = contextLength;+ if (contextMap.containsKey(ref)) {+ currentBoost = contextMap.get(ref);+ ref.length = pathPrefix.length;+ ref.offset = contextLength;+ while (ref.ints[ref.offset] != ContextSuggestField.CONTEXT_SEPARATOR) {+ ref.offset++;+ assert ref.offset < ref.length;+ }+ assert ref.ints[ref.offset] == ContextSuggestField.CONTEXT_SEPARATOR : "expected CONTEXT_SEPARATOR at offset=" + ref.offset;+ if (ref.offset > pathPrefix.offset) {+ currentContext = Util.toBytesRef(new IntsRef(pathPrefix.ints, pathPrefix.offset, ref.offset), scratch).utf8ToString();+ } else {+ currentContext = null;+ }+ ref.offset++;+ if (ref.ints[ref.offset] == CompletionAnalyzer.SEP_LABEL) {+ ref.offset++;+ }+ innerWeight.setNextMatch(ref);+ return;+ }+ }+ // unknown context+ ref.length = pathPrefix.length;+ currentBoost = contexts.get("*").boost;+ for (int i = pathPrefix.offset; i < pathPrefix.length; i++) {+ if (pathPrefix.ints[i] == ContextSuggestField.CONTEXT_SEPARATOR) {+ if (i > pathPrefix.offset) {+ currentContext = Util.toBytesRef(new IntsRef(pathPrefix.ints, pathPrefix.offset, i), scratch).utf8ToString();+ } else {+ currentContext = null;+ }+ ref.offset = ++i;+ assert ref.offset < ref.length : "input should not end with the context separator";+ if (pathPrefix.ints[i] == CompletionAnalyzer.SEP_LABEL) {+ ref.offset++;+ assert ref.offset < ref.length : "input should not end with a context separator followed by SEP_LABEL";+ }+ ref.length -= ref.offset;+ innerWeight.setNextMatch(ref);+ }+ }+ }++ @Override+ protected CharSequence context() {+ return currentContext;+ }++ @Override+ protected float boost() {+ return currentBoost + innerWeight.boost();+ }+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/ContextSuggestField.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/ContextSuggestField.javanew file mode 100644index 00000000000..ef1c93d2b04--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/ContextSuggestField.java@@ -0,0 +1,167 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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.Collection;+import java.util.HashSet;+import java.util.Iterator;+import java.util.Set;++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.PositionIncrementAttribute;++/**+ * {@link SuggestField} which additionally takes in a set of+ * contexts. Example usage of adding a suggestion with contexts is as follows:+ *+ * <pre class="prettyprint">+ * document.add(+ * new ContextSuggestField(name, "suggestion", Arrays.asList("context1", "context2"), 4));+ * </pre>+ *+ * Use {@link ContextQuery} to boost and/or filter suggestions+ * at query-time. Use {@link PrefixCompletionQuery}, {@link RegexCompletionQuery}+ * or {@link FuzzyCompletionQuery} if context boost/filtering+ * are not needed.+ *+ * @lucene.experimental+ */+public class ContextSuggestField extends SuggestField {++ /**+ * Separator used between context value and the suggest field value+ */+ public static final int CONTEXT_SEPARATOR = '\u001D';+ static final byte TYPE = 1;++ private final Set<CharSequence> contexts;++ /**+ * Creates a context-enabled suggest field+ *+ * @param name field name+ * @param contexts associated contexts+ * @param value field value to get suggestion on+ * @param weight field weight+ *+ * @throws IllegalArgumentException if either the name or value is null,+ * if value is an empty string, if the weight is negative, if value or+ * contexts contains any reserved characters+ */+ public ContextSuggestField(String name, Collection<CharSequence> contexts, String value, int weight) {+ super(name, value, weight);+ validate(value);+ if (contexts != null) {+ for (CharSequence context : contexts) {+ validate(context);+ }+ this.contexts = new HashSet<>(contexts);+ } else {+ this.contexts = new HashSet<>();+ }+ }++ @Override+ protected CompletionTokenStream wrapTokenStream(TokenStream stream) {+ CompletionTokenStream completionTokenStream;+ if (stream instanceof CompletionTokenStream) {+ completionTokenStream = (CompletionTokenStream) stream;+ completionTokenStream = new CompletionTokenStream(+ new PrefixTokenFilter(stream, (char) CONTEXT_SEPARATOR, contexts),+ completionTokenStream.preserveSep,+ completionTokenStream.preservePositionIncrements,+ completionTokenStream.maxGraphExpansions);+ } else {+ completionTokenStream = new CompletionTokenStream(+ new PrefixTokenFilter(stream, (char) CONTEXT_SEPARATOR, contexts));+ }+ return completionTokenStream;+ }++ @Override+ protected byte type() {+ return TYPE;+ }++ /**+ * The {@link PrefixTokenFilter} wraps a {@link TokenStream} and adds a set+ * prefixes ahead. The position attribute will not be incremented for the prefixes.+ */+ private static final class PrefixTokenFilter extends TokenFilter {++ private final char separator;+ private final CharTermAttribute termAttr = addAttribute(CharTermAttribute.class);+ private final PositionIncrementAttribute posAttr = addAttribute(PositionIncrementAttribute.class);+ private final Iterable<CharSequence> prefixes;++ private Iterator<CharSequence> currentPrefix;++ /**+ * Create a new {@link PrefixTokenFilter}+ *+ * @param input {@link TokenStream} to wrap+ * @param separator Character used separate prefixes from other tokens+ * @param prefixes {@link Iterable} of {@link CharSequence} which keeps all prefixes+ */+ public PrefixTokenFilter(TokenStream input, char separator, Iterable<CharSequence> prefixes) {+ super(input);+ this.prefixes = prefixes;+ this.currentPrefix = null;+ this.separator = separator;+ }++ @Override+ public boolean incrementToken() throws IOException {+ if (currentPrefix != null) {+ if (!currentPrefix.hasNext()) {+ return input.incrementToken();+ } else {+ posAttr.setPositionIncrement(0);+ }+ } else {+ currentPrefix = prefixes.iterator();+ termAttr.setEmpty();+ posAttr.setPositionIncrement(1);+ }+ termAttr.setEmpty();+ if (currentPrefix.hasNext()) {+ termAttr.append(currentPrefix.next());+ }+ termAttr.append(separator);+ return true;+ }++ @Override+ public void reset() throws IOException {+ super.reset();+ currentPrefix = null;+ }+ }++ private void validate(final CharSequence value) {+ for (int i = 0; i < value.length(); i++) {+ if (CONTEXT_SEPARATOR == value.charAt(i)) {+ throw new IllegalArgumentException("Illegal value [" + value + "] UTF-16 codepoint [0x"+ + Integer.toHexString((int) value.charAt(i))+ "] at position " + i + " is a reserved character");+ }+ }+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/FuzzyCompletionQuery.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/FuzzyCompletionQuery.javanew file mode 100644index 00000000000..b5e8d9a183b--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/FuzzyCompletionQuery.java@@ -0,0 +1,254 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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.Set;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Weight;+import org.apache.lucene.util.IntsRef;+import org.apache.lucene.util.UnicodeUtil;+import org.apache.lucene.util.automaton.Automata;+import org.apache.lucene.util.automaton.Automaton;+import org.apache.lucene.util.automaton.LevenshteinAutomata;+import org.apache.lucene.util.automaton.Operations;+import org.apache.lucene.util.automaton.UTF32ToUTF8;++/**+ * A {@link CompletionQuery} that match documents containing terms+ * within an edit distance of the specified prefix.+ * <p>+ * This query boost documents relative to how similar the indexed terms are to the+ * provided prefix.+ * <p>+ * Example usage of querying an analyzed prefix within an edit distance of 1 of 'subg'+ * against a field 'suggest_field' is as follows:+ *+ * <pre class="prettyprint">+ * CompletionQuery query = new FuzzyCompletionQuery(analyzer, new Term("suggest_field", "subg"));+ * </pre>+ *+ * @lucene.experimental+ */+public class FuzzyCompletionQuery extends PrefixCompletionQuery {++ /**+ * Measure maxEdits, minFuzzyLength, transpositions and nonFuzzyPrefix+ * parameters in Unicode code points (actual letters)+ * instead of bytes.+ * */+ public static final boolean DEFAULT_UNICODE_AWARE = false;++ /**+ * The default minimum length of the key before any edits are allowed.+ */+ public static final int DEFAULT_MIN_FUZZY_LENGTH = 3;++ /**+ * The default prefix length where edits are not allowed.+ */+ public static final int DEFAULT_NON_FUZZY_PREFIX = 1;++ /**+ * The default maximum number of edits for fuzzy+ * suggestions.+ */+ public static final int DEFAULT_MAX_EDITS = 1;++ /**+ * The default transposition value passed to {@link LevenshteinAutomata}+ */+ public static final boolean DEFAULT_TRANSPOSITIONS = true;++ private final int maxEdits;+ private final boolean transpositions;+ private final int nonFuzzyPrefix;+ private final int minFuzzyLength;+ private final boolean unicodeAware;+ private final int maxDeterminizedStates;++ /**+ * Calls {@link FuzzyCompletionQuery#FuzzyCompletionQuery(Analyzer, Term, Filter)}+ * with no filter+ */+ public FuzzyCompletionQuery(Analyzer analyzer, Term term) {+ this(analyzer, term, null);+ }++ /**+ * Calls {@link FuzzyCompletionQuery#FuzzyCompletionQuery(Analyzer, Term, Filter,+ * int, boolean, int, int, boolean, int)}+ * with defaults for <code>maxEdits</code>, <code>transpositions</code>,+ * <code>nonFuzzyPrefix</code>, <code>minFuzzyLength</code>,+ * <code>unicodeAware</code> and <code>maxDeterminizedStates</code>+ *+ * See {@link #DEFAULT_MAX_EDITS}, {@link #DEFAULT_TRANSPOSITIONS},+ * {@link #DEFAULT_NON_FUZZY_PREFIX}, {@link #DEFAULT_MIN_FUZZY_LENGTH},+ * {@link #DEFAULT_UNICODE_AWARE} and {@link Operations#DEFAULT_MAX_DETERMINIZED_STATES}+ * for defaults+ */+ public FuzzyCompletionQuery(Analyzer analyzer, Term term, Filter filter) {+ this(analyzer, term, filter, DEFAULT_MAX_EDITS, DEFAULT_TRANSPOSITIONS, DEFAULT_NON_FUZZY_PREFIX,+ DEFAULT_MIN_FUZZY_LENGTH, DEFAULT_UNICODE_AWARE, Operations.DEFAULT_MAX_DETERMINIZED_STATES+ );+ }++ /**+ * Constructs an analyzed fuzzy prefix completion query+ *+ * @param analyzer used to analyze the provided {@link Term#text()}+ * @param term query is run against {@link Term#field()} and {@link Term#text()}+ * is analyzed with <code>analyzer</code>+ * @param filter used to query on a sub set of documents+ * @param maxEdits maximum number of acceptable edits+ * @param transpositions value passed to {@link LevenshteinAutomata}+ * @param nonFuzzyPrefix prefix length where edits are not allowed+ * @param minFuzzyLength minimum prefix length before any edits are allowed+ * @param unicodeAware treat prefix as unicode rather than bytes+ * @param maxDeterminizedStates maximum automaton states allowed for {@link LevenshteinAutomata}+ */+ public FuzzyCompletionQuery(Analyzer analyzer, Term term, Filter filter, int maxEdits,+ boolean transpositions, int nonFuzzyPrefix, int minFuzzyLength,+ boolean unicodeAware, int maxDeterminizedStates) {+ super(analyzer, term, filter);+ this.maxEdits = maxEdits;+ this.transpositions = transpositions;+ this.nonFuzzyPrefix = nonFuzzyPrefix;+ this.minFuzzyLength = minFuzzyLength;+ this.unicodeAware = unicodeAware;+ this.maxDeterminizedStates = maxDeterminizedStates;+ }++ @Override+ public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {+ CompletionTokenStream stream = (CompletionTokenStream) analyzer.tokenStream(getField(), getTerm().text());+ Automaton a = stream.toAutomaton(unicodeAware);+ final Set<IntsRef> refs = Operations.getFiniteStrings(a, -1);+ assert refs.size() > 0;+ Automaton automaton = toLevenshteinAutomata(refs);+ if (unicodeAware) {+ Automaton utf8automaton = new UTF32ToUTF8().convert(automaton);+ utf8automaton = Operations.determinize(utf8automaton, maxDeterminizedStates);+ automaton = utf8automaton;+ }+ return new FuzzyCompletionWeight(searcher.getIndexReader(), this, automaton, refs);+ }++ private Automaton toLevenshteinAutomata(Set<IntsRef> ref) {+ Automaton subs[] = new Automaton[ref.size()];+ int upto = 0;+ for (IntsRef path : ref) {+ if (path.length <= nonFuzzyPrefix || path.length < minFuzzyLength) {+ subs[upto] = Automata.makeString(path.ints, path.offset, path.length);+ upto++;+ } else {+ int ints[] = new int[path.length - nonFuzzyPrefix];+ System.arraycopy(path.ints, path.offset + nonFuzzyPrefix, ints, 0, ints.length);+ // TODO: maybe add alphaMin to LevenshteinAutomata,+ // and pass 1 instead of 0? We probably don't want+ // to allow the trailing dedup bytes to be+ // edited... but then 0 byte is "in general" allowed+ // on input (but not in UTF8).+ LevenshteinAutomata lev = new LevenshteinAutomata(ints,+ unicodeAware ? Character.MAX_CODE_POINT : 255,+ transpositions);+ subs[upto] = lev.toAutomaton(maxEdits,+ UnicodeUtil.newString(path.ints, path.offset, nonFuzzyPrefix));+ upto++;+ }+ }++ if (subs.length == 0) {+ // automaton is empty, there is no accepted paths through it+ return Automata.makeEmpty(); // matches nothing+ } else if (subs.length == 1) {+ // no synonyms or anything: just a single path through the tokenstream+ return subs[0];+ } else {+ // multiple paths: this is really scary! is it slow?+ // maybe we should not do this and throw UOE?+ Automaton a = Operations.union(Arrays.asList(subs));+ // TODO: we could call toLevenshteinAutomata() before det?+ // this only happens if you have multiple paths anyway (e.g. synonyms)+ return Operations.determinize(a, maxDeterminizedStates);+ }+ }++ @Override+ public String toString(String field) {+ StringBuilder buffer = new StringBuilder();+ if (!getField().equals(field)) {+ buffer.append(getField());+ buffer.append(":");+ }+ buffer.append(getTerm().text());+ buffer.append('*');+ buffer.append('~');+ buffer.append(Integer.toString(maxEdits));+ if (getFilter() != null) {+ buffer.append(",");+ buffer.append("filter");+ buffer.append(getFilter().toString(field));+ }+ return buffer.toString();+ }++ private static class FuzzyCompletionWeight extends CompletionWeight {+ private final Set<IntsRef> refs;+ int currentBoost = 0;++ public FuzzyCompletionWeight(IndexReader reader, CompletionQuery query,+ Automaton automaton, Set<IntsRef> refs) throws IOException {+ super(reader, query, automaton);+ this.refs = refs;+ }++ @Override+ protected void setNextMatch(IntsRef pathPrefix) {+ // NOTE: the last letter of the matched prefix for the exact+ // match never makes it through here+ // so an exact match and a match with only a edit at the+ // end is boosted the same+ int maxCount = 0;+ for (IntsRef ref : refs) {+ int minLength = Math.min(ref.length, pathPrefix.length);+ int count = 0;+ for (int i = 0; i < minLength; i++) {+ if (ref.ints[i + ref.offset] == pathPrefix.ints[i + pathPrefix.offset]) {+ count++;+ } else {+ break;+ }+ }+ maxCount = Math.max(maxCount, count);+ }+ currentBoost = maxCount;+ }++ @Override+ protected float boost() {+ return currentBoost;+ }+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/NRTSuggester.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/NRTSuggester.javaindex a014d04bb47..d9f8d24feff 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/NRTSuggester.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/NRTSuggester.java@@ -23,19 +23,13 @@ import java.util.Collections;import java.util.Comparator;import java.util.List;-import org.apache.lucene.index.LeafReader;-import org.apache.lucene.search.CollectionTerminatedException;-import org.apache.lucene.search.DocIdSet;import org.apache.lucene.search.suggest.analyzing.FSTUtil;import org.apache.lucene.store.ByteArrayDataInput;import org.apache.lucene.store.ByteArrayDataOutput;import org.apache.lucene.store.IndexInput;import org.apache.lucene.util.Accountable;-import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.CharsRefBuilder;-import org.apache.lucene.util.IntsRef;-import org.apache.lucene.util.automaton.Automaton;import org.apache.lucene.util.fst.ByteSequenceOutputs;import org.apache.lucene.util.fst.FST;import org.apache.lucene.util.fst.PairOutputs;@@ -48,18 +42,11 @@ import static org.apache.lucene.search.suggest.document.NRTSuggester.PayLoadProc/*** <p>- * NRTSuggester returns Top N completions with corresponding documents matching a provided automaton.- * The completions are returned in descending order of their corresponding weight.- * Deleted documents are filtered out in near real time using the provided reader.- * A {@link org.apache.lucene.search.DocIdSet} can be passed in at query time to filter out documents.- * </p>+ * NRTSuggester executes Top N search on a weighted FST specified by a {@link CompletionScorer}* <p>- * See {@link #lookup(LeafReader, Automaton, int, DocIdSet, TopSuggestDocsCollector)} for more implementation+ * See {@link #lookup(CompletionScorer, TopSuggestDocsCollector)} for more implementation* details.* <p>- * Builder: {@link NRTSuggesterBuilder}- * </p>- * <p>* FST Format:* <ul>* <li>Input: analyzed forms of input terms</li>@@ -68,16 +55,17 @@ import static org.apache.lucene.search.suggest.document.NRTSuggester.PayLoadProc* <p>* NOTE:* <ul>- * <li>currently only {@link org.apache.lucene.search.DocIdSet} with random access capabilities are supported.</li>* <li>having too many deletions or using a very restrictive filter can make the search inadmissible due to- * over-pruning of potential paths</li>- * <li>when a {@link org.apache.lucene.search.DocIdSet} is used, it is assumed that the filter will roughly- * filter out half the number of documents that match the provided automaton</li>+ * over-pruning of potential paths. See {@link CompletionScorer#accept(int)}</li>+ * <li>when matched documents are arbitrarily filtered ({@link CompletionScorer#filtered} set to <code>true</code>,+ * it is assumed that the filter will roughly filter out half the number of documents that match+ * the provided automaton</li>* <li>lookup performance will degrade as more accepted completions lead to filtered out documents</li>* </ul>*+ * @lucene.experimental*/-final class NRTSuggester implements Accountable {+public final class NRTSuggester implements Accountable {/*** FST<Weight,Surface>:@@ -113,7 +101,7 @@ final class NRTSuggester implements Accountable {** NOTE: value should be <= Integer.MAX_VALUE*/- private static final long MAX_TOP_N_QUEUE_SIZE = 1000;+ private static final long MAX_TOP_N_QUEUE_SIZE = 5000;private NRTSuggester(FST<Pair<Long, BytesRef>> fst, int maxAnalyzedPathsPerOutput, int payloadSep, int endByte) {this.fst = fst;@@ -132,102 +120,90 @@ final class NRTSuggester implements Accountable {return Collections.emptyList();}- private static Comparator<Pair<Long, BytesRef>> getComparator() {- return new Comparator<Pair<Long, BytesRef>>() {- @Override- public int compare(Pair<Long, BytesRef> o1, Pair<Long, BytesRef> o2) {- return Long.compare(o1.output1, o2.output1);- }- };- }-/**- * Collects at most Top <code>num</code> completions, filtered by <code>filter</code> on- * corresponding documents, which has a prefix accepted by <code>automaton</code>+ * Collects at most {@link TopSuggestDocsCollector#getCountToCollect()} completions that+ * match the provided {@link CompletionScorer}.* <p>- * Supports near real time deleted document filtering using <code>reader</code>- * <p>- * {@link TopSuggestDocsCollector#collect(int, CharSequence, long)} is called- * for every matched completion- * <p>- * Completion collection can be early terminated by throwing {@link org.apache.lucene.search.CollectionTerminatedException}+ * The {@link CompletionScorer#automaton} is intersected with the {@link #fst}.+ * {@link CompletionScorer#weight} is used to compute boosts and/or extract context+ * for each matched partial paths. A top N search is executed on {@link #fst} seeded with+ * the matched partial paths. Upon reaching a completed path, {@link CompletionScorer#accept(int)}+ * and {@link CompletionScorer#score(float, float)} is used on the document id, index weight+ * and query boost to filter and score the entry, before being collected via+ * {@link TopSuggestDocsCollector#collect(int, CharSequence, CharSequence, float)}*/- public void lookup(final LeafReader reader, final Automaton automaton, final int num, final DocIdSet filter, final TopSuggestDocsCollector collector) {- final Bits filterDocs;- try {- if (filter != null) {- if (filter.iterator() == null) {- return;+ public void lookup(final CompletionScorer scorer, final TopSuggestDocsCollector collector) throws IOException {+ final double liveDocsRatio = calculateLiveDocRatio(scorer.reader.numDocs(), scorer.reader.maxDoc());+ if (liveDocsRatio == -1) {+ return;+ }+ final List<FSTUtil.Path<Pair<Long, BytesRef>>> prefixPaths = FSTUtil.intersectPrefixPaths(scorer.automaton, fst);+ final int queueSize = getMaxTopNSearcherQueueSize(collector.getCountToCollect() * prefixPaths.size(),+ scorer.reader.numDocs(), liveDocsRatio, scorer.filtered);+ Comparator<Pair<Long, BytesRef>> comparator = getComparator();+ Util.TopNSearcher<Pair<Long, BytesRef>> searcher = new Util.TopNSearcher<Pair<Long, BytesRef>>(fst,+ collector.getCountToCollect(), queueSize, comparator, new ScoringPathComparator(scorer)) {++ private final CharsRefBuilder spare = new CharsRefBuilder();++ @Override+ protected boolean acceptResult(Util.FSTPath<Pair<Long, BytesRef>> path) {+ int payloadSepIndex = parseSurfaceForm(path.cost.output2, payloadSep, spare);+ int docID = parseDocID(path.cost.output2, payloadSepIndex);+ if (!scorer.accept(docID)) {+ return false;}- if (filter.bits() == null) {- throw new IllegalArgumentException("DocIDSet does not provide random access interface");- } else {- filterDocs = filter.bits();+ try {+ float score = scorer.score(decode(path.cost.output1), path.boost);+ collector.collect(docID, spare.toCharsRef(), path.context, score);+ return true;+ } catch (IOException e) {+ throw new RuntimeException(e);}- } else {- filterDocs = null;}- } catch (IOException e) {- throw new RuntimeException(e);- }+ };- int queueSize = getMaxTopNSearcherQueueSize(num, reader, filterDocs != null);- if (queueSize == -1) {- return;+ for (FSTUtil.Path<Pair<Long, BytesRef>> path : prefixPaths) {+ scorer.weight.setNextMatch(path.input.get());+ searcher.addStartPaths(path.fstNode, path.output, false, path.input, scorer.weight.boost(),+ scorer.weight.context());}+ // hits are also returned by search()+ // we do not use it, instead collect at acceptResult+ Util.TopResults<Pair<Long, BytesRef>> search = searcher.search();+ // search admissibility is not guaranteed+ // see comment on getMaxTopNSearcherQueueSize+ // assert search.isComplete;+ }- final Bits liveDocs = reader.getLiveDocs();- try {- final List<FSTUtil.Path<Pair<Long, BytesRef>>> prefixPaths = FSTUtil.intersectPrefixPaths(automaton, fst);- Util.TopNSearcher<Pair<Long, BytesRef>> searcher = new Util.TopNSearcher<Pair<Long, BytesRef>>(fst, num, queueSize, getComparator()) {-- private final CharsRefBuilder spare = new CharsRefBuilder();-- @Override- protected boolean acceptResult(IntsRef input, Pair<Long, BytesRef> output) {- int payloadSepIndex = parseSurfaceForm(output.output2, payloadSep, spare);- int docID = parseDocID(output.output2, payloadSepIndex);-- // filter out deleted docs only if no filter is set- if (filterDocs == null && liveDocs != null && !liveDocs.get(docID)) {- return false;- }-- // filter by filter context- if (filterDocs != null && !filterDocs.get(docID)) {- return false;- }-- try {- collector.collect(docID, spare.toCharsRef(), decode(output.output1));- return true;- } catch (IOException e) {- throw new RuntimeException(e);- }- }- };-- // TODO: add fuzzy support- for (FSTUtil.Path<Pair<Long, BytesRef>> path : prefixPaths) {- searcher.addStartPaths(path.fstNode, path.output, false, path.input);- }+ /**+ * Compares partial completion paths using {@link CompletionScorer#score(float, float)},+ * breaks ties comparing path inputs+ */+ private static class ScoringPathComparator implements Comparator<Util.FSTPath<Pair<Long, BytesRef>>> {+ private final CompletionScorer scorer;- try {- // hits are also returned by search()- // we do not use it, instead collect at acceptResult- Util.TopResults<Pair<Long, BytesRef>> search = searcher.search();- // search admissibility is not guaranteed- // see comment on getMaxTopNSearcherQueueSize- // assert search.isComplete;- } catch (CollectionTerminatedException e) {- // terminate- }+ public ScoringPathComparator(CompletionScorer scorer) {+ this.scorer = scorer;+ }- } catch (IOException bogus) {- throw new RuntimeException(bogus);+ @Override+ public int compare(Util.FSTPath<Pair<Long, BytesRef>> first, Util.FSTPath<Pair<Long, BytesRef>> second) {+ int cmp = Float.compare(scorer.score(decode(second.cost.output1), second.boost),+ scorer.score(decode(first.cost.output1), first.boost));+ return (cmp != 0) ? cmp : first.input.get().compareTo(second.input.get());}}+ private static Comparator<Pair<Long, BytesRef>> getComparator() {+ return new Comparator<Pair<Long, BytesRef>>() {+ @Override+ public int compare(Pair<Long, BytesRef> o1, Pair<Long, BytesRef> o2) {+ return Long.compare(o1.output1, o2.output1);+ }+ };+ }+/*** Simple heuristics to try to avoid over-pruning potential suggestions by the* TopNSearcher. Since suggestion entries can be rejected if they belong@@ -241,17 +217,13 @@ final class NRTSuggester implements Accountable {* <p>* The maximum queue size is {@link #MAX_TOP_N_QUEUE_SIZE}*/- private int getMaxTopNSearcherQueueSize(int num, LeafReader reader, boolean filterEnabled) {- double liveDocsRatio = calculateLiveDocRatio(reader.numDocs(), reader.maxDoc());- if (liveDocsRatio == -1) {- return -1;- }- long maxQueueSize = num * maxAnalyzedPathsPerOutput;+ private int getMaxTopNSearcherQueueSize(int topN, int numDocs, double liveDocsRatio, boolean filterEnabled) {+ long maxQueueSize = topN * maxAnalyzedPathsPerOutput;// liveDocRatio can be at most 1.0 (if no docs were deleted)assert liveDocsRatio <= 1.0d;maxQueueSize = (long) (maxQueueSize / liveDocsRatio);if (filterEnabled) {- maxQueueSize = maxQueueSize + (reader.numDocs()/2);+ maxQueueSize = maxQueueSize + (numDocs/2);}return (int) Math.min(MAX_TOP_N_QUEUE_SIZE, maxQueueSize);}@@ -276,14 +248,16 @@ final class NRTSuggester implements Accountable {}static long encode(long input) {- if (input < 0) {+ if (input < 0 || input > Integer.MAX_VALUE) {throw new UnsupportedOperationException("cannot encode value: " + input);}- return Long.MAX_VALUE - input;+ return Integer.MAX_VALUE - input;}static long decode(long output) {- return (Long.MAX_VALUE - output);+ assert output >= 0 && output <= Integer.MAX_VALUE :+ "decoded output: " + output + " is not within 0 and Integer.MAX_VALUE";+ return Integer.MAX_VALUE - output;}/**@@ -307,7 +281,8 @@ final class NRTSuggester implements Accountable {static int parseDocID(final BytesRef output, int payloadSepIndex) {assert payloadSepIndex != -1 : "payload sep index can not be -1";- ByteArrayDataInput input = new ByteArrayDataInput(output.bytes, payloadSepIndex + output.offset + 1, output.length - (payloadSepIndex + output.offset));+ ByteArrayDataInput input = new ByteArrayDataInput(output.bytes, payloadSepIndex + output.offset + 1,+ output.length - (payloadSepIndex + output.offset));return input.readVInt();}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/NRTSuggesterBuilder.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/NRTSuggesterBuilder.javaindex 80c7d368bcc..a962bbf49fc 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/NRTSuggesterBuilder.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/NRTSuggesterBuilder.java@@ -49,7 +49,7 @@ final class NRTSuggesterBuilder {* Marks end of the analyzed input and start of dedup* byte.*/- private static final int END_BYTE = 0x0;+ public static final int END_BYTE = 0x0;private final PairOutputs<Long, BytesRef> outputs;private final Builder<PairOutputs.Pair<Long, BytesRef>> builder;diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/PrefixCompletionQuery.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/PrefixCompletionQuery.javanew file mode 100644index 00000000000..8d8d54f33d7--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/PrefixCompletionQuery.java@@ -0,0 +1,74 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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 org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Weight;++/**+ * A {@link CompletionQuery} which takes an {@link Analyzer}+ * to analyze the prefix of the query term.+ * <p>+ * Example usage of querying an analyzed prefix 'sugg'+ * against a field 'suggest_field' is as follows:+ *+ * <pre class="prettyprint">+ * CompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg"));+ * </pre>+ * @lucene.experimental+ */+public class PrefixCompletionQuery extends CompletionQuery {+ /** Used to analyze the term text */+ protected final CompletionAnalyzer analyzer;++ /**+ * Calls {@link PrefixCompletionQuery#PrefixCompletionQuery(Analyzer, Term, Filter)}+ * with no filter+ */+ public PrefixCompletionQuery(Analyzer analyzer, Term term) {+ this(analyzer, term, null);+ }++ /**+ * Constructs an analyzed prefix completion query+ *+ * @param analyzer used to analyze the provided {@link Term#text()}+ * @param term query is run against {@link Term#field()} and {@link Term#text()}+ * is analyzed with <code>analyzer</code>+ * @param filter used to query on a sub set of documents+ */+ public PrefixCompletionQuery(Analyzer analyzer, Term term, Filter filter) {+ super(term, filter);+ if (!(analyzer instanceof CompletionAnalyzer)) {+ this.analyzer = new CompletionAnalyzer(analyzer);+ } else {+ this.analyzer = (CompletionAnalyzer) analyzer;+ }+ }++ @Override+ public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {+ CompletionTokenStream stream = (CompletionTokenStream) analyzer.tokenStream(getField(), getTerm().text());+ return new CompletionWeight(searcher.getIndexReader(), this, stream.toAutomaton());+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/RegexCompletionQuery.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/RegexCompletionQuery.javanew file mode 100644index 00000000000..f9b567b2040--- /dev/null+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/RegexCompletionQuery.java@@ -0,0 +1,96 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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 org.apache.lucene.index.Term;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Weight;+import org.apache.lucene.util.automaton.Operations;+import org.apache.lucene.util.automaton.RegExp;++/**+ * A {@link CompletionQuery} which takes a regular expression+ * as the prefix of the query term.+ *+ * <p>+ * Example usage of querying a prefix of 'sug' and 'sub'+ * as a regular expression against a suggest field 'suggest_field':+ *+ * <pre class="prettyprint">+ * CompletionQuery query = new RegexCompletionQuery(new Term("suggest_field", "su[g|b]"));+ * </pre>+ *+ * <p>+ * See {@link RegExp} for the supported regular expression+ * syntax+ *+ * @lucene.experimental+ */+public class RegexCompletionQuery extends CompletionQuery {++ private final int flags;+ private final int maxDeterminizedStates;++ /**+ * Calls {@link RegexCompletionQuery#RegexCompletionQuery(Term, Filter)}+ * with no filter+ */+ public RegexCompletionQuery(Term term) {+ this(term, null);+ }++ /**+ * Calls {@link RegexCompletionQuery#RegexCompletionQuery(Term, int, int, Filter)}+ * enabling all optional regex syntax and <code>maxDeterminizedStates</code> of+ * {@value Operations#DEFAULT_MAX_DETERMINIZED_STATES}+ */+ public RegexCompletionQuery(Term term, Filter filter) {+ this(term, RegExp.ALL, Operations.DEFAULT_MAX_DETERMINIZED_STATES, filter);+ }+ /**+ * Calls {@link RegexCompletionQuery#RegexCompletionQuery(Term, int, int, Filter)}+ * with no filter+ */+ public RegexCompletionQuery(Term term, int flags, int maxDeterminizedStates) {+ this(term, flags, maxDeterminizedStates, null);+ }++ /**+ * Constructs a regular expression completion query+ *+ * @param term query is run against {@link Term#field()} and {@link Term#text()}+ * is interpreted as a regular expression+ * @param flags used as syntax_flag in {@link RegExp#RegExp(String, int)}+ * @param maxDeterminizedStates used in {@link RegExp#toAutomaton(int)}+ * @param filter used to query on a sub set of documents+ */+ public RegexCompletionQuery(Term term, int flags, int maxDeterminizedStates, Filter filter) {+ super(term, filter);+ this.flags = flags;+ this.maxDeterminizedStates = maxDeterminizedStates;+ }++ @Override+ public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {+ return new CompletionWeight(searcher.getIndexReader(), this,+ new RegExp(getTerm().text(), flags).toAutomaton(maxDeterminizedStates));+ }+}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/SuggestField.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/SuggestField.javaindex c7d4093cb4f..c6d1a4a42fc 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/SuggestField.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/SuggestField.java@@ -48,20 +48,14 @@ import org.apache.lucene.util.BytesRef;* document.add(new SuggestField(name, "suggestion", 4));* </pre>* To perform document suggestions based on the this field, use- * {@link SuggestIndexSearcher#suggest(String, CharSequence, int, org.apache.lucene.search.Filter)}- * <p>- * Example query usage:- * <pre class="prettyprint">- * SuggestIndexSearcher indexSearcher = ..- * indexSearcher.suggest(name, "su", 2)- * </pre>+ * {@link SuggestIndexSearcher#suggest(CompletionQuery, int)}** @lucene.experimental*/public class SuggestField extends Field {- private static final FieldType FIELD_TYPE = new FieldType();-+ /** Default field type for suggest field */+ public static final FieldType FIELD_TYPE = new FieldType();static {FIELD_TYPE.setTokenized(true);FIELD_TYPE.setStored(false);@@ -71,53 +65,86 @@ public class SuggestField extends Field {FIELD_TYPE.freeze();}+ static final byte TYPE = 0;+private final BytesRef surfaceForm;- private final long weight;+ private final int weight;/*** Creates a {@link SuggestField}*- * @param name of the field- * @param value to get suggestions on- * @param weight weight of the suggestion+ * @param name field name+ * @param value field value to get suggestions on+ * @param weight field weight+ *+ * @throws IllegalArgumentException if either the name or value is null,+ * if value is an empty string, if the weight is negative, if value contains+ * any reserved characters*/- public SuggestField(String name, String value, long weight) {+ public SuggestField(String name, String value, int weight) {super(name, value, FIELD_TYPE);- if (weight < 0l) {+ if (weight < 0) {throw new IllegalArgumentException("weight must be >= 0");}+ if (value.length() == 0) {+ throw new IllegalArgumentException("value must have a length > 0");+ }+ for (int i = 0; i < value.length(); i++) {+ if (isReserved(value.charAt(i))) {+ throw new IllegalArgumentException("Illegal input [" + value + "] UTF-16 codepoint [0x"+ + Integer.toHexString((int) value.charAt(i))+ "] at position " + i + " is a reserved character");+ }+ }this.surfaceForm = new BytesRef(value);this.weight = weight;}@Overridepublic TokenStream tokenStream(Analyzer analyzer, TokenStream reuse) throws IOException {- TokenStream stream = super.tokenStream(analyzer, reuse);- CompletionTokenStream completionStream;+ CompletionTokenStream completionStream = wrapTokenStream(super.tokenStream(analyzer, reuse));+ completionStream.setPayload(buildSuggestPayload());+ return completionStream;+ }++ /**+ * Wraps a <code>stream</code> with a CompletionTokenStream.+ *+ * Subclasses can override this method to change the indexing pipeline.+ */+ protected CompletionTokenStream wrapTokenStream(TokenStream stream) {if (stream instanceof CompletionTokenStream) {- completionStream = (CompletionTokenStream) stream;+ return (CompletionTokenStream) stream;} else {- completionStream = new CompletionTokenStream(stream);+ return new CompletionTokenStream(stream);}- BytesRef suggestPayload = buildSuggestPayload(surfaceForm, weight, (char) completionStream.sepLabel());- completionStream.setPayload(suggestPayload);- return completionStream;}- private BytesRef buildSuggestPayload(BytesRef surfaceForm, long weight, char sepLabel) throws IOException {- for (int i = 0; i < surfaceForm.length; i++) {- if (surfaceForm.bytes[i] == sepLabel) {- assert sepLabel == '\u001f';- throw new IllegalArgumentException(- "surface form cannot contain unit separator character U+001F; this character is reserved");- }- }+ /**+ * Returns a byte to denote the type of the field+ */+ protected byte type() {+ return TYPE;+ }++ private BytesRef buildSuggestPayload() throws IOException {ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();try (OutputStreamDataOutput output = new OutputStreamDataOutput(byteArrayOutputStream)) {output.writeVInt(surfaceForm.length);output.writeBytes(surfaceForm.bytes, surfaceForm.offset, surfaceForm.length);- output.writeVLong(weight + 1);+ output.writeVInt(weight + 1);+ output.writeByte(type());}return new BytesRef(byteArrayOutputStream.toByteArray());}++ private boolean isReserved(char c) {+ switch (c) {+ case CompletionAnalyzer.SEP_LABEL:+ case CompletionAnalyzer.HOLE_CHARACTER:+ case NRTSuggesterBuilder.END_BYTE:+ return true;+ default:+ return false;+ }+ }}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/SuggestIndexSearcher.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/SuggestIndexSearcher.javaindex ffc7a4873f4..17b30ce1130 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/SuggestIndexSearcher.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/SuggestIndexSearcher.java@@ -19,132 +19,66 @@ package org.apache.lucene.search.suggest.document;import java.io.IOException;-import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.LeafReader;import org.apache.lucene.index.LeafReaderContext;-import org.apache.lucene.index.Terms;-import org.apache.lucene.search.DocIdSet;-import org.apache.lucene.search.Filter;+import org.apache.lucene.search.BulkScorer;+import org.apache.lucene.search.CollectionTerminatedException;import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.util.automaton.Automaton;--import static org.apache.lucene.search.suggest.document.CompletionFieldsProducer.CompletionTerms;+import org.apache.lucene.search.Weight;/**- * Adds document suggest capabilities to IndexSearcher+ * Adds document suggest capabilities to IndexSearcher.+ * Any {@link CompletionQuery} can be used to suggest documents.+ *+ * Use {@link PrefixCompletionQuery} for analyzed prefix queries,+ * {@link RegexCompletionQuery} for regular expression prefix queries,+ * {@link FuzzyCompletionQuery} for analyzed prefix with typo tolerance+ * and {@link ContextQuery} to boost and/or filter suggestions by contexts** @lucene.experimental*/public class SuggestIndexSearcher extends IndexSearcher {- private final Analyzer queryAnalyzer;-/*** Creates a searcher with document suggest capabilities* for <code>reader</code>.- * <p>- * Suggestion <code>key</code> is analyzed with <code>queryAnalyzer</code>*/- public SuggestIndexSearcher(IndexReader reader, Analyzer queryAnalyzer) {+ public SuggestIndexSearcher(IndexReader reader) {super(reader);- this.queryAnalyzer = queryAnalyzer;- }-- /**- * Calls {@link #suggest(String, CharSequence, int, Filter)}- * with no document filter- */- public TopSuggestDocs suggest(String field, CharSequence key, int num) throws IOException {- return suggest(field, key, num, (Filter) null);- }-- /**- * Calls {@link #suggest(String, CharSequence, int, Filter, TopSuggestDocsCollector)}- * with no document filter- */- public void suggest(String field, CharSequence key, int num, TopSuggestDocsCollector collector) throws IOException {- suggest(field, key, num, null, collector);}/**- * Suggests at most <code>num</code> documents filtered by <code>filter</code>- * that completes to <code>key</code> for a suggest <code>field</code>- * <p>- * Returns at most Top <code>num</code> document ids with corresponding completion and weight pair- *- * @throws java.lang.IllegalArgumentException if <code>filter</code> does not provide a random access- * interface or if <code>field</code> is not a {@link SuggestField}+ * Returns top <code>n</code> completion hits for+ * <code>query</code>*/- public TopSuggestDocs suggest(String field, CharSequence key, int num, Filter filter) throws IOException {- TopSuggestDocsCollector collector = new TopSuggestDocsCollector(num);- suggest(field, key, num, filter, collector);+ public TopSuggestDocs suggest(CompletionQuery query, int n) throws IOException {+ TopSuggestDocsCollector collector = new TopSuggestDocsCollector(n);+ suggest(query, collector);return collector.get();}/**- * Suggests at most <code>num</code> documents filtered by <code>filter</code>- * that completes to <code>key</code> for a suggest <code>field</code>- * <p>- * Collect completions with {@link TopSuggestDocsCollector}- * The completions are collected in order of the suggest <code>field</code> weight.- * There can be more than one collection of the same document, if the <code>key</code>- * matches multiple <code>field</code> values of the same document+ * Lower-level suggest API.+ * Collects completion hits through <code>collector</code> for <code>query</code>.*- * @throws java.lang.IllegalArgumentException if <code>filter</code> does not provide a random access- * interface or if <code>field</code> is not a {@link SuggestField}+ * <p>{@link TopSuggestDocsCollector#collect(int, CharSequence, CharSequence, float)}+ * is called for every matching completion hit.*/- public void suggest(String field, CharSequence key, int num, Filter filter, TopSuggestDocsCollector collector) throws IOException {- // verify input- if (field == null) {- throw new IllegalArgumentException("'field' can not be null");- }- if (num <= 0) {- throw new IllegalArgumentException("'num' should be > 0");- }- if (collector == null) {- throw new IllegalArgumentException("'collector' can not be null");- }-- // build query automaton- CompletionAnalyzer analyzer;- if (queryAnalyzer instanceof CompletionAnalyzer) {- analyzer = (CompletionAnalyzer) queryAnalyzer;- } else {- analyzer = new CompletionAnalyzer(queryAnalyzer);- }- final Automaton automaton = analyzer.toAutomaton(field, key);-- // collect results+ public void suggest(CompletionQuery query, TopSuggestDocsCollector collector) throws IOException {+ // TODO use IndexSearcher.rewrite instead+ // have to implement equals() and hashCode() in CompletionQuerys and co+ query = (CompletionQuery) query.rewrite(getIndexReader());+ Weight weight = query.createWeight(this, collector.needsScores());for (LeafReaderContext context : getIndexReader().leaves()) {- TopSuggestDocsCollector leafCollector = (TopSuggestDocsCollector) collector.getLeafCollector(context);- LeafReader reader = context.reader();- Terms terms = reader.terms(field);- if (terms == null) {- continue;- }- NRTSuggester suggester;- if (terms instanceof CompletionTerms) {- CompletionTerms completionTerms = (CompletionTerms) terms;- suggester = completionTerms.suggester();- } else {- throw new IllegalArgumentException(field + " is not a SuggestField");- }- if (suggester == null) {- // a segment can have a null suggester- // i.e. no FST was built- continue;- }-- DocIdSet docIdSet = null;- if (filter != null) {- docIdSet = filter.getDocIdSet(context, reader.getLiveDocs());- if (docIdSet == null) {- // filter matches no docs in current leave- continue;+ BulkScorer scorer = weight.bulkScorer(context, context.reader().getLiveDocs());+ if (scorer != null) {+ try {+ scorer.score(collector.getLeafCollector(context));+ } catch (CollectionTerminatedException e) {+ // collection was terminated prematurely+ // continue with the following leaf}}- suggester.lookup(reader, automaton, num, docIdSet, leafCollector);}}}diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/TopSuggestDocs.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/TopSuggestDocs.javaindex 0064b4b5779..049f73a7169 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/TopSuggestDocs.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/TopSuggestDocs.java@@ -43,7 +43,12 @@ public class TopSuggestDocs extends TopDocs {/*** Matched completion key*/- public CharSequence key;+ public final CharSequence key;++ /**+ * Context for the completion+ */+ public final CharSequence context;/*** Creates a SuggestScoreDoc instance@@ -52,11 +57,10 @@ public class TopSuggestDocs extends TopDocs {* @param key matched completion* @param score weight of the matched completion*/- public SuggestScoreDoc(int doc, CharSequence key, long score) {- // loss of precision but not magnitude- // implicit conversion from long -> float+ public SuggestScoreDoc(int doc, CharSequence key, CharSequence context, float score) {super(doc, score);this.key = key;+ this.context = context;}@Overridediff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/TopSuggestDocsCollector.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/TopSuggestDocsCollector.javaindex 6644b0d9607..1cb327715a0 100644--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/TopSuggestDocsCollector.java+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/TopSuggestDocsCollector.java@@ -30,20 +30,23 @@ import static org.apache.lucene.search.suggest.document.TopSuggestDocs.SuggestSc* score, along with document id* <p>* Non scoring collector that collect completions in order of their- * pre-defined weight.+ * pre-computed scores.* <p>* NOTE: One document can be collected multiple times if a document* is matched for multiple unique completions for a given query* <p>- * Subclasses should only override {@link TopSuggestDocsCollector#collect(int, CharSequence, long)},- * {@link #setScorer(org.apache.lucene.search.Scorer)} is not- * used+ * Subclasses should only override+ * {@link TopSuggestDocsCollector#collect(int, CharSequence, CharSequence, float)}.+ * <p>+ * NOTE: {@link #setScorer(org.apache.lucene.search.Scorer)} and+ * {@link #collect(int)} is not used** @lucene.experimental*/public class TopSuggestDocsCollector extends SimpleCollector {private final SuggestScoreDocPriorityQueue priorityQueue;+ private final int num;/*** Document base offset for the current Leaf@@ -60,9 +63,17 @@ public class TopSuggestDocsCollector extends SimpleCollector {if (num <= 0) {throw new IllegalArgumentException("'num' must be > 0");}+ this.num = num;this.priorityQueue = new SuggestScoreDocPriorityQueue(num);}+ /**+ * Returns the number of results to be collected+ */+ public int getCountToCollect() {+ return num;+ }+@Overrideprotected void doSetNextReader(LeafReaderContext context) throws IOException {docBase = context.docBase;@@ -76,8 +87,8 @@ public class TopSuggestDocsCollector extends SimpleCollector {* NOTE: collection at the leaf level is guaranteed to be in* descending order of score*/- public void collect(int docID, CharSequence key, long score) throws IOException {- SuggestScoreDoc current = new SuggestScoreDoc(docBase + docID, key, score);+ public void collect(int docID, CharSequence key, CharSequence context, float score) throws IOException {+ SuggestScoreDoc current = new SuggestScoreDoc(docBase + docID, key, context, score);if (current == priorityQueue.insertWithOverflow(current)) {// if the current SuggestScoreDoc has overflown from pq,// we can assume all of the successive collections from@@ -104,7 +115,7 @@ public class TopSuggestDocsCollector extends SimpleCollector {*/@Overridepublic void collect(int doc) throws IOException {- // {@link #collect(int, CharSequence, long)} is used+ // {@link #collect(int, CharSequence, CharSequence, long)} is used// instead}@@ -113,6 +124,6 @@ public class TopSuggestDocsCollector extends SimpleCollector {*/@Overridepublic boolean needsScores() {- return false;+ return true;}}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextQuery.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextQuery.javanew file mode 100644index 00000000000..52ff1702840--- /dev/null+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextQuery.java@@ -0,0 +1,522 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.Comparator;+import java.util.HashSet;+import java.util.List;+import java.util.Set;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.TestUtil;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;++import static org.apache.lucene.search.suggest.document.TestSuggestField.Entry;+import static org.apache.lucene.search.suggest.document.TestSuggestField.assertSuggestions;+import static org.apache.lucene.search.suggest.document.TestSuggestField.iwcWithSuggestField;++public class TestContextQuery extends LuceneTestCase {+ public Directory dir;++ @Before+ public void before() throws Exception {+ dir = newDirectory();+ }++ @After+ public void after() throws Exception {+ dir.close();+ }++ @Test+ public void testIllegalInnerQuery() throws Exception {+ try {+ new ContextQuery(new ContextQuery(+ new PrefixCompletionQuery(new MockAnalyzer(random()), new Term("suggest_field", "sugg"))));+ fail("should error out trying to nest a Context query within another Context query");+ } catch (IllegalArgumentException expected) {+ assertTrue(expected.getMessage().contains(ContextQuery.class.getSimpleName()));+ }+ }++ @Test+ public void testSimpleContextQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "suggestion1", 8));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "suggestion2", 7));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "suggestion3", 6));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion4", 5));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ query.addContext("type1", 1);+ query.addContext("type2", 2);+ query.addContext("type3", 3);+ query.addContext("type4", 4);+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion4", "type4", 5 * 4),+ new Entry("suggestion3", "type3", 6 * 3),+ new Entry("suggestion2", "type2", 7 * 2),+ new Entry("suggestion1", "type1", 8 * 1)+ );++ reader.close();+ iw.close();+ }++ @Test+ public void testContextQueryOnSuggestField() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new SuggestField("suggest_field", "abc", 3));+ document.add(new SuggestField("suggest_field", "abd", 4));+ document.add(new SuggestField("suggest_field", "The Foo Fighters", 2));+ iw.addDocument(document);+ document.clear();+ document.add(new SuggestField("suggest_field", "abcdd", 5));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "ab")));+ try {+ suggestIndexSearcher.suggest(query, 4);+ } catch (IllegalStateException expected) {+ assertTrue(expected.getMessage().contains("SuggestField"));+ }+ reader.close();+ iw.close();+ }++ @Test+ public void testNonExactContextQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "suggestion1", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "suggestion2", 3));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "suggestion3", 2));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion4", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ query.addContext("type", 1, false);+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion1", "type1", 4),+ new Entry("suggestion2", "type2", 3),+ new Entry("suggestion3", "type3", 2),+ new Entry("suggestion4", "type4", 1));++ reader.close();+ iw.close();+ }++ @Test+ public void testContextPrecedenceBoost() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("typetype"), "suggestion1", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type"), "suggestion2", 3));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ query.addContext("type", 1);+ query.addContext("typetype", 2);+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion1", "typetype", 4 * 2),+ new Entry("suggestion2", "type", 3 * 1)+ );++ reader.close();+ iw.close();+ }++ @Test+ public void testEmptyContext() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", null, "suggestion_no_ctx", 4));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion_no_ctx", null, 4),+ new Entry("suggestion", "type4", 1));++ reader.close();+ iw.close();+ }++ @Test+ public void testEmptyContextWithBoosts() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", null, "suggestion1", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.emptyList(), "suggestion2", 3));+ document.add(new ContextSuggestField("suggest_field", null, "suggestion3", 2));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion4", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);++ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ query.addContext("type4", 10);+ query.addContext("*");+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion4", "type4", 1 * 10),+ new Entry("suggestion1", null, 4),+ new Entry("suggestion2", null, 3),+ new Entry("suggestion3", null, 2)+ );+ reader.close();+ iw.close();+ }++ @Test+ public void testSameSuggestionMultipleContext() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Arrays.asList("type1", "type2", "type3"), "suggestion", 4));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ query.addContext("type1", 10);+ query.addContext("type2", 2);+ query.addContext("type3", 3);+ query.addContext("type4", 4);+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion", "type1", 4 * 10),+ new Entry("suggestion", "type3", 4 * 3),+ new Entry("suggestion", "type2", 4 * 2),+ new Entry("suggestion", "type4", 1 * 4)+ );++ reader.close();+ iw.close();+ }++ @Test+ public void testMixedContextQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "suggestion1", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "suggestion2", 3));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "suggestion3", 2));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion4", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ query.addContext("type1", 7);+ query.addContext("type2", 6);+ query.addContext("*", 5);+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion1", "type1", 4 * 7),+ new Entry("suggestion2", "type2", 3 * 6),+ new Entry("suggestion3", "type3", 2 * 5),+ new Entry("suggestion4", "type4", 1 * 5)+ );++ reader.close();+ iw.close();+ }++ @Test+ public void testFilteringContextQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "suggestion1", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "suggestion2", 3));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "suggestion3", 2));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion4", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ query.addContext("type3", 3);+ query.addContext("type4", 4);+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion3", "type3", 2 * 3),+ new Entry("suggestion4", "type4", 1 * 4)+ );++ reader.close();+ iw.close();+ }++ @Test+ public void testContextQueryRewrite() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "suggestion1", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "suggestion2", 3));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "suggestion3", 2));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion4", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ CompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg"));+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion1", "type1", 4),+ new Entry("suggestion2", "type2", 3),+ new Entry("suggestion3", "type3", 2),+ new Entry("suggestion4", "type4", 1));++ reader.close();+ iw.close();+ }++ @Test+ public void testMultiContextQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Arrays.asList("type1", "type3"), "suggestion1", 8));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "suggestion2", 7));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "suggestion3", 6));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion4", 5));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ query.addContext("type1", 1);+ query.addContext("type2", 2);+ query.addContext("type3", 3);+ query.addContext("type4", 4);+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion1", "type3", 8 * 3),+ new Entry("suggestion4", "type4", 5 * 4),+ new Entry("suggestion3", "type3", 6 * 3),+ new Entry("suggestion2", "type2", 7 * 2),+ new Entry("suggestion1", "type1", 8 * 1));++ reader.close();+ iw.close();+ }++ @Test+ public void testAllContextQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "suggestion1", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "suggestion2", 3));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "suggestion3", 2));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion4", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 4);+ assertSuggestions(suggest,+ new Entry("suggestion1", "type1", 4),+ new Entry("suggestion2", "type2", 3),+ new Entry("suggestion3", "type3", 2),+ new Entry("suggestion4", "type4", 1));++ reader.close();+ iw.close();+ }++ @Test+ public void testRandomContextQueryScoring() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ int numSuggestions = atLeast(20);+ int numContexts = atLeast(5);++ Set<Integer> seenWeights = new HashSet<>();+ List<Entry> expectedEntries = new ArrayList<>();+ List<CharSequence> contexts = new ArrayList<>();+ for (int i = 1; i <= numContexts; i++) {+ CharSequence context = TestUtil.randomSimpleString(random(), 10) + i;+ contexts.add(context);+ for (int j = 1; j <= numSuggestions; j++) {+ String suggestion = "sugg_" + TestUtil.randomSimpleString(random(), 10) + j;+ int weight = TestUtil.nextInt(random(), 1, 1000 * numContexts * numSuggestions);+ while (seenWeights.contains(weight)) {+ weight = TestUtil.nextInt(random(), 1, 1000 * numContexts * numSuggestions);+ }+ seenWeights.add(weight);+ Document document = new Document();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList(context), suggestion, weight));+ iw.addDocument(document);+ expectedEntries.add(new Entry(suggestion, context.toString(), i * weight));+ }+ if (rarely()) {+ iw.commit();+ }+ }+ Entry[] expectedResults = expectedEntries.toArray(new Entry[expectedEntries.size()]);++ ArrayUtil.introSort(expectedResults, new Comparator<Entry>() {+ @Override+ public int compare(Entry o1, Entry o2) {+ int cmp = Float.compare(o2.value, o1.value);+ if (cmp != 0) {+ return cmp;+ } else {+ return o1.output.compareTo(o2.output);+ }+ }+ });++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg")));+ for (int i = 0; i < contexts.size(); i++) {+ query.addContext(contexts.get(i), i + 1);+ }+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 4);+ assertSuggestions(suggest, Arrays.copyOfRange(expectedResults, 0, 4));++ reader.close();+ iw.close();+ }+}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextSuggestField.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextSuggestField.javanew file mode 100644index 00000000000..844e78fe3bc--- /dev/null+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextSuggestField.java@@ -0,0 +1,145 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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.util.Collections;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.CharsRefBuilder;+import org.apache.lucene.util.LuceneTestCase;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;++import static org.apache.lucene.search.suggest.document.TestSuggestField.Entry;+import static org.apache.lucene.search.suggest.document.TestSuggestField.assertSuggestions;+import static org.apache.lucene.search.suggest.document.TestSuggestField.iwcWithSuggestField;++public class TestContextSuggestField extends LuceneTestCase {++ public Directory dir;++ @Before+ public void before() throws Exception {+ dir = newDirectory();+ }++ @After+ public void after() throws Exception {+ dir.close();+ }++ @Test+ public void testEmptySuggestion() throws Exception {+ try {+ new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "", 1);+ fail("no exception thrown when indexing zero length suggestion");+ } catch (IllegalArgumentException expected) {+ assertTrue(expected.getMessage().contains("value"));+ }+ }++ @Test+ public void testReservedChars() throws Exception {+ CharsRefBuilder charsRefBuilder = new CharsRefBuilder();+ charsRefBuilder.append("sugg");+ charsRefBuilder.setCharAt(2, (char) ContextSuggestField.CONTEXT_SEPARATOR);+ try {+ new ContextSuggestField("name", Collections.singletonList(charsRefBuilder.toString()), "sugg", 1);+ fail("no exception thrown for context value containing CONTEXT_SEPARATOR:" + ContextSuggestField.CONTEXT_SEPARATOR);+ } catch (IllegalArgumentException e) {+ assertTrue(e.getMessage().contains("[0x1d]"));+ }++ try {+ new ContextSuggestField("name", Collections.singletonList("sugg"), charsRefBuilder.toString(), 1);+ fail("no exception thrown for value containing CONTEXT_SEPARATOR:" + ContextSuggestField.CONTEXT_SEPARATOR);+ } catch (IllegalArgumentException e) {+ assertTrue(e.getMessage().contains("[0x1d]"));+ }+ }++ @Test+ public void testMixedSuggestFields() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ Document document = new Document();+ document.add(new SuggestField("suggest_field", "suggestion1", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.emptyList(), "suggestion2", 3));++ try (RandomIndexWriter iw = new RandomIndexWriter(random(), dir,+ iwcWithSuggestField(analyzer, "suggest_field"))) {+ iw.addDocument(document);+ iw.commit();+ fail("mixing suggest field types for same field name should error out");+ } catch (IllegalArgumentException expected) {+ assertTrue(expected.getMessage().contains("mixed types"));+ }+ }++ @Test+ public void testWithSuggestFields() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir,+ iwcWithSuggestField(analyzer, "suggest_field", "context_suggest_field"));+ Document document = new Document();++ document.add(new SuggestField("suggest_field", "suggestion1", 4));+ document.add(new SuggestField("suggest_field", "suggestion2", 3));+ document.add(new SuggestField("suggest_field", "suggestion3", 2));+ document.add(new ContextSuggestField("context_suggest_field", Collections.singletonList("type1"), "suggestion1", 4));+ document.add(new ContextSuggestField("context_suggest_field", Collections.singletonList("type2"), "suggestion2", 3));+ document.add(new ContextSuggestField("context_suggest_field", Collections.singletonList("type3"), "suggestion3", 2));+ iw.addDocument(document);+ document.clear();+ document.add(new SuggestField("suggest_field", "suggestion4", 1));+ document.add(new ContextSuggestField("context_suggest_field", Collections.singletonList("type4"), "suggestion4", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);++ CompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "sugg"));+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 10);+ assertSuggestions(suggest,+ new Entry("suggestion1", 4),+ new Entry("suggestion2", 3),+ new Entry("suggestion3", 2),+ new Entry("suggestion4", 1));++ query = new PrefixCompletionQuery(analyzer, new Term("context_suggest_field", "sugg"));+ suggest = suggestIndexSearcher.suggest(query, 10);+ assertSuggestions(suggest,+ new Entry("suggestion1", "type1", 4),+ new Entry("suggestion2", "type2", 3),+ new Entry("suggestion3", "type3", 2),+ new Entry("suggestion4", "type4", 1));++ reader.close();+ iw.close();+ }+}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestFuzzyCompletionQuery.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestFuzzyCompletionQuery.javanew file mode 100644index 00000000000..452c7d06bf0--- /dev/null+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestFuzzyCompletionQuery.java@@ -0,0 +1,153 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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.util.Collections;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.LuceneTestCase;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;++import static org.apache.lucene.search.suggest.document.TestSuggestField.Entry;+import static org.apache.lucene.search.suggest.document.TestSuggestField.assertSuggestions;+import static org.apache.lucene.search.suggest.document.TestSuggestField.iwcWithSuggestField;++public class TestFuzzyCompletionQuery extends LuceneTestCase {+ public Directory dir;++ @Before+ public void before() throws Exception {+ dir = newDirectory();+ }++ @After+ public void after() throws Exception {+ dir.close();+ }++ @Test+ public void testFuzzyQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new SuggestField("suggest_field", "suggestion", 2));+ document.add(new SuggestField("suggest_field", "suaggestion", 4));+ document.add(new SuggestField("suggest_field", "ssuggestion", 1));+ iw.addDocument(document);+ document.clear();+ document.add(new SuggestField("suggest_field", "sugfoo", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ CompletionQuery query = new FuzzyCompletionQuery(analyzer, new Term("suggest_field", "sugg"));+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 4);+ assertSuggestions(suggest,+ new Entry("suaggestion", 4 * 2),+ new Entry("suggestion", 2 * 3),+ new Entry("sugfoo", 1 * 3),+ new Entry("ssuggestion", 1 * 1)+ );++ reader.close();+ iw.close();+ }++ @Test+ public void testFuzzyContextQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "sduggestion", 1));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "sudggestion", 1));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "sugdgestion", 1));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggdestion", 1));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ CompletionQuery query = new ContextQuery(new FuzzyCompletionQuery(analyzer, new Term("suggest_field", "sugge")));+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("suggestion", "type4", 1 + 4),+ new Entry("suggdestion", "type4", 1 + 4),+ new Entry("sugdgestion", "type3", 1 + 3),+ new Entry("sudggestion", "type2", 1 + 2),+ new Entry("sduggestion", "type1", 1 + 1)+ );++ reader.close();+ iw.close();+ }++ @Test+ public void testFuzzyFilteredContextQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "sduggestion", 1));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "sudggestion", 1));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "sugdgestion", 1));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggdestion", 1));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ CompletionQuery fuzzyQuery = new FuzzyCompletionQuery(analyzer, new Term("suggest_field", "sugge"));+ ContextQuery contextQuery = new ContextQuery(fuzzyQuery);+ contextQuery.addContext("type1", 6);+ contextQuery.addContext("type3", 2);+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(contextQuery, 5);+ assertSuggestions(suggest,+ new Entry("sduggestion", "type1", 1 * (1 + 6)),+ new Entry("sugdgestion", "type3", 1 * (3 + 2))+ );++ reader.close();+ iw.close();+ }+}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestPrefixCompletionQuery.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestPrefixCompletionQuery.javanew file mode 100644index 00000000000..4f7f3f95f48--- /dev/null+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestPrefixCompletionQuery.java@@ -0,0 +1,300 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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 org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.analysis.MockTokenFilter;+import org.apache.lucene.analysis.MockTokenizer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.IntField;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.DocIdSet;+import org.apache.lucene.search.DocIdSetIterator;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.NumericRangeQuery;+import org.apache.lucene.search.QueryWrapperFilter;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.BitDocIdSet;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.FixedBitSet;+import org.apache.lucene.util.LuceneTestCase;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;++import static org.apache.lucene.search.suggest.document.TestSuggestField.Entry;+import static org.apache.lucene.search.suggest.document.TestSuggestField.assertSuggestions;+import static org.apache.lucene.search.suggest.document.TestSuggestField.iwcWithSuggestField;+import static org.hamcrest.core.IsEqual.equalTo;++public class TestPrefixCompletionQuery extends LuceneTestCase {+ public Directory dir;++ @Before+ public void before() throws Exception {+ dir = newDirectory();+ }++ @After+ public void after() throws Exception {+ dir.close();+ }++ @Test+ public void testSimple() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new SuggestField("suggest_field", "abc", 3));+ document.add(new SuggestField("suggest_field", "abd", 4));+ document.add(new SuggestField("suggest_field", "The Foo Fighters", 2));+ iw.addDocument(document);+ document.clear();+ document.add(new SuggestField("suggest_field", "abcdd", 5));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "ab"));+ TopSuggestDocs lookupDocs = suggestIndexSearcher.suggest(query, 3);+ assertSuggestions(lookupDocs, new Entry("abcdd", 5), new Entry("abd", 4), new Entry("abc", 3));++ reader.close();+ iw.close();+ }++ @Test+ public void testMostlyFilteredOutDocuments() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ int num = Math.min(1000, atLeast(10));+ Document document = new Document();+ for (int i = 0; i < num; i++) {+ document.add(new SuggestField("suggest_field", "abc_" + i, i));+ document.add(new IntField("filter_int_fld", i, Field.Store.NO));+ iw.addDocument(document);+ document.clear();++ if (usually()) {+ iw.commit();+ }+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);++ int topScore = num/2;+ QueryWrapperFilter filterWrapper = new QueryWrapperFilter(NumericRangeQuery.newIntRange("filter_int_fld", 0, topScore, true, true));+ Filter filter = randomAccessFilter(filterWrapper);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"), filter);+ // if at most half of the top scoring documents have been filtered out+ // the search should be admissible for a single segment+ TopSuggestDocs suggest = indexSearcher.suggest(query, num);+ assertTrue(suggest.totalHits >= 1);+ assertThat(suggest.scoreLookupDocs()[0].key.toString(), equalTo("abc_" + topScore));+ assertThat(suggest.scoreLookupDocs()[0].score, equalTo((float) topScore));++ filterWrapper = new QueryWrapperFilter(NumericRangeQuery.newIntRange("filter_int_fld", 0, 0, true, true));+ filter = randomAccessFilter(filterWrapper);+ query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"), filter);+ // if more than half of the top scoring documents have been filtered out+ // search is not admissible, so # of suggestions requested is num instead of 1+ suggest = indexSearcher.suggest(query, num);+ assertSuggestions(suggest, new Entry("abc_0", 0));++ filterWrapper = new QueryWrapperFilter(NumericRangeQuery.newIntRange("filter_int_fld", num - 1, num - 1, true, true));+ filter = randomAccessFilter(filterWrapper);+ query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"), filter);+ // if only lower scoring documents are filtered out+ // search is admissible+ suggest = indexSearcher.suggest(query, 1);+ assertSuggestions(suggest, new Entry("abc_" + (num - 1), num - 1));++ reader.close();+ iw.close();+ }++ @Test+ public void testDocFiltering() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));++ Document document = new Document();+ document.add(new IntField("filter_int_fld", 9, Field.Store.NO));+ document.add(new SuggestField("suggest_field", "apples", 3));+ iw.addDocument(document);++ document.clear();+ document.add(new IntField("filter_int_fld", 10, Field.Store.NO));+ document.add(new SuggestField("suggest_field", "applle", 4));+ iw.addDocument(document);++ document.clear();+ document.add(new IntField("filter_int_fld", 4, Field.Store.NO));+ document.add(new SuggestField("suggest_field", "apple", 5));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);++ // suggest without filter+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "app"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, 3);+ assertSuggestions(suggest, new Entry("apple", 5), new Entry("applle", 4), new Entry("apples", 3));++ // suggest with filter+ QueryWrapperFilter filterWrapper = new QueryWrapperFilter(NumericRangeQuery.newIntRange("filter_int_fld", 5, 12, true, true));+ Filter filter = randomAccessFilter(filterWrapper);+ query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "app"), filter);+ suggest = indexSearcher.suggest(query, 3);+ assertSuggestions(suggest, new Entry("applle", 4), new Entry("apples", 3));++ reader.close();+ iw.close();+ }++ @Test+ public void testAnalyzerWithoutPreservePosAndSep() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random(), MockTokenizer.WHITESPACE, true, MockTokenFilter.ENGLISH_STOPSET);+ CompletionAnalyzer completionAnalyzer = new CompletionAnalyzer(analyzer, false, false);+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(completionAnalyzer, "suggest_field_no_p_sep_or_pos_inc"));+ Document document = new Document();+ document.add(new SuggestField("suggest_field_no_p_sep_or_pos_inc", "foobar", 7));+ document.add(new SuggestField("suggest_field_no_p_sep_or_pos_inc", "foo bar", 8));+ document.add(new SuggestField("suggest_field_no_p_sep_or_pos_inc", "the fo", 9));+ document.add(new SuggestField("suggest_field_no_p_sep_or_pos_inc", "the foo bar", 10));+ iw.addDocument(document);++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);+ CompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field_no_p_sep_or_pos_inc", "fo"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, 4); // all 4+ assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("the fo", 9), new Entry("foo bar", 8), new Entry("foobar", 7));+ query = new PrefixCompletionQuery(analyzer, new Term("suggest_field_no_p_sep_or_pos_inc", "foob"));+ suggest = indexSearcher.suggest(query, 4); // not the fo+ assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("foo bar", 8), new Entry("foobar", 7));+ reader.close();+ iw.close();+ }++ @Test+ public void testAnalyzerWithSepAndNoPreservePos() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random(), MockTokenizer.WHITESPACE, true, MockTokenFilter.ENGLISH_STOPSET);+ CompletionAnalyzer completionAnalyzer = new CompletionAnalyzer(analyzer, true, false);+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(completionAnalyzer, "suggest_field_no_p_pos_inc"));+ Document document = new Document();+ document.add(new SuggestField("suggest_field_no_p_pos_inc", "foobar", 7));+ document.add(new SuggestField("suggest_field_no_p_pos_inc", "foo bar", 8));+ document.add(new SuggestField("suggest_field_no_p_pos_inc", "the fo", 9));+ document.add(new SuggestField("suggest_field_no_p_pos_inc", "the foo bar", 10));+ iw.addDocument(document);++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);+ CompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field_no_p_pos_inc", "fo"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, 4); //matches all 4+ assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("the fo", 9), new Entry("foo bar", 8), new Entry("foobar", 7));+ query = new PrefixCompletionQuery(analyzer, new Term("suggest_field_no_p_pos_inc", "foob"));+ suggest = indexSearcher.suggest(query, 4); // only foobar+ assertSuggestions(suggest, new Entry("foobar", 7));+ reader.close();+ iw.close();+ }++ @Test+ public void testAnalyzerWithPreservePosAndNoSep() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random(), MockTokenizer.WHITESPACE, true, MockTokenFilter.ENGLISH_STOPSET);+ CompletionAnalyzer completionAnalyzer = new CompletionAnalyzer(analyzer, false, true);+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(completionAnalyzer, "suggest_field_no_p_sep"));+ Document document = new Document();+ document.add(new SuggestField("suggest_field_no_p_sep", "foobar", 7));+ document.add(new SuggestField("suggest_field_no_p_sep", "foo bar", 8));+ document.add(new SuggestField("suggest_field_no_p_sep", "the fo", 9));+ document.add(new SuggestField("suggest_field_no_p_sep", "the foo bar", 10));+ iw.addDocument(document);++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);+ CompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field_no_p_sep", "fo"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, 4); // matches all 4+ assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("the fo", 9), new Entry("foo bar", 8), new Entry("foobar", 7));+ query = new PrefixCompletionQuery(analyzer, new Term("suggest_field_no_p_sep", "foob"));+ suggest = indexSearcher.suggest(query, 4); // except the fo+ assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("foo bar", 8), new Entry("foobar", 7));+ reader.close();+ iw.close();+ }++ private static class RandomAccessFilter extends Filter {+ private final Filter in;++ private RandomAccessFilter(Filter in) {+ this.in = in;+ }++ @Override+ public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) throws IOException {+ DocIdSet docIdSet = in.getDocIdSet(context, acceptDocs);+ DocIdSetIterator iterator = docIdSet.iterator();+ FixedBitSet bits = new FixedBitSet(context.reader().maxDoc());+ if (iterator != null) {+ bits.or(iterator);+ }+ return new BitDocIdSet(bits);+ }++ @Override+ public String toString(String field) {+ return in.toString(field);+ }++ @Override+ public boolean equals(Object obj) {+ if (super.equals(obj) == false) {+ return false;+ }+ return in.equals(((RandomAccessFilter) obj).in);+ }++ @Override+ public int hashCode() {+ return 31 * super.hashCode() + in.hashCode();+ }+ }++ private static Filter randomAccessFilter(Filter filter) {+ return new RandomAccessFilter(filter);+ }++}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestRegexCompletionQuery.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestRegexCompletionQuery.javanew file mode 100644index 00000000000..916e79c88b3--- /dev/null+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestRegexCompletionQuery.java@@ -0,0 +1,150 @@+package org.apache.lucene.search.suggest.document;++/*+ * 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.util.Collections;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.LuceneTestCase;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;++import static org.apache.lucene.search.suggest.document.TestSuggestField.Entry;+import static org.apache.lucene.search.suggest.document.TestSuggestField.assertSuggestions;+import static org.apache.lucene.search.suggest.document.TestSuggestField.iwcWithSuggestField;++public class TestRegexCompletionQuery extends LuceneTestCase {+ public Directory dir;++ @Before+ public void before() throws Exception {+ dir = newDirectory();+ }++ @After+ public void after() throws Exception {+ dir.close();+ }++ @Test+ public void testRegexQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new SuggestField("suggest_field", "suggestion", 1));+ document.add(new SuggestField("suggest_field", "asuggestion", 2));+ document.add(new SuggestField("suggest_field", "ssuggestion", 3));+ iw.addDocument(document);+ document.clear();+ document.add(new SuggestField("suggest_field", "wsuggestion", 4));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ RegexCompletionQuery query = new RegexCompletionQuery(new Term("suggest_field", "[a|w|s]s?ugg"));+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 4);+ assertSuggestions(suggest, new Entry("wsuggestion", 4), new Entry("ssuggestion", 3),+ new Entry("asuggestion", 2), new Entry("suggestion", 1));++ reader.close();+ iw.close();+ }++ @Test+ public void testSimpleRegexContextQuery() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "sduggestion", 5));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "sudggestion", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "sugdgestion", 3));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggdestion", 2));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ CompletionQuery query = new RegexCompletionQuery(new Term("suggest_field", "[a|s][d|u|s][u|d|g]"));+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(query, 5);+ assertSuggestions(suggest,+ new Entry("sduggestion", "type1", 5),+ new Entry("sudggestion", "type2", 4),+ new Entry("sugdgestion", "type3", 3),+ new Entry("suggdestion", "type4", 2),+ new Entry("suggestion", "type4", 1));++ reader.close();+ iw.close();+ }++ @Test+ public void testRegexContextQueryWithBoost() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ Document document = new Document();++ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type1"), "sduggestion", 5));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type2"), "sudggestion", 4));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type3"), "sugdgestion", 3));+ iw.addDocument(document);+ document.clear();+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggdestion", 2));+ document.add(new ContextSuggestField("suggest_field", Collections.singletonList("type4"), "suggestion", 1));+ iw.addDocument(document);++ if (rarely()) {+ iw.commit();+ }++ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ CompletionQuery query = new RegexCompletionQuery(new Term("suggest_field", "[a|s][d|u|s][u|g]"));+ ContextQuery contextQuery = new ContextQuery(query);+ contextQuery.addContext("type1", 6);+ contextQuery.addContext("type3", 7);+ contextQuery.addContext("*");+ TopSuggestDocs suggest = suggestIndexSearcher.suggest(contextQuery, 5);+ assertSuggestions(suggest,+ new Entry("sduggestion", "type1", 5 * 6),+ new Entry("sugdgestion", "type3", 3 * 7),+ new Entry("suggdestion", "type4", 2),+ new Entry("suggestion", "type4", 1));++ reader.close();+ iw.close();+ }+}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/SuggestFieldTest.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.javasimilarity index 54%rename from lucene/suggest/src/test/org/apache/lucene/search/suggest/document/SuggestFieldTest.javarename to lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.javaindex f1df2201929..c1e97a901e5 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/SuggestFieldTest.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.java@@ -17,7 +17,6 @@ package org.apache.lucene.search.suggest.document;* limitations under the License.*/-import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;@@ -29,9 +28,6 @@ import java.util.concurrent.CyclicBarrier;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.MockAnalyzer;-import org.apache.lucene.analysis.MockTokenFilter;-import org.apache.lucene.analysis.MockTokenizer;-import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;import org.apache.lucene.codecs.Codec;import org.apache.lucene.codecs.PostingsFormat;import org.apache.lucene.codecs.lucene50.Lucene50Codec;@@ -41,23 +37,18 @@ import org.apache.lucene.document.IntField;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;-import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.StoredDocument;import org.apache.lucene.index.Term;import org.apache.lucene.queries.TermsQuery;-import org.apache.lucene.search.DocIdSet;-import org.apache.lucene.search.DocIdSetIterator;import org.apache.lucene.search.Filter;import org.apache.lucene.search.NumericRangeQuery;import org.apache.lucene.search.QueryWrapperFilter;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;-import org.apache.lucene.util.BitDocIdSet;-import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;-import org.apache.lucene.util.FixedBitSet;+import org.apache.lucene.util.CharsRefBuilder;import org.apache.lucene.util.LineFileDocs;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.TestUtil;@@ -65,10 +56,10 @@ import org.junit.After;import org.junit.Before;import org.junit.Test;-import static org.apache.lucene.search.suggest.document.TopSuggestDocs.*;+import static org.apache.lucene.search.suggest.document.TopSuggestDocs.SuggestScoreDoc;import static org.hamcrest.core.IsEqual.equalTo;-public class SuggestFieldTest extends LuceneTestCase {+public class TestSuggestField extends LuceneTestCase {public Directory dir;@@ -83,64 +74,63 @@ public class SuggestFieldTest extends LuceneTestCase {}@Test- public void testSimple() throws Exception {- Analyzer analyzer = new MockAnalyzer(random());- RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));- Document document = new Document();-- document.add(newSuggestField("suggest_field", "abc", 3l));- document.add(newSuggestField("suggest_field", "abd", 4l));- document.add(newSuggestField("suggest_field", "The Foo Fighters", 2l));- iw.addDocument(document);- document.clear();- document.add(newSuggestField("suggest_field", "abcdd", 5));- iw.addDocument(document);-- if (rarely()) {- iw.commit();+ public void testEmptySuggestion() throws Exception {+ try {+ new SuggestField("suggest_field", "", 3);+ fail("no exception thrown when indexing zero length suggestion");+ } catch (IllegalArgumentException expected) {+ assertTrue(expected.getMessage().contains("value"));}-- DirectoryReader reader = iw.getReader();- SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader, analyzer);- TopSuggestDocs lookupDocs = suggestIndexSearcher.suggest("suggest_field", "ab", 3);- assertSuggestions(lookupDocs, new Entry("abcdd", 5), new Entry("abd", 4), new Entry("abc", 3));-- reader.close();- iw.close();}@Test- public void testMultipleSuggestFieldsPerDoc() throws Exception {- Analyzer analyzer = new MockAnalyzer(random());- RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "sug_field_1", "sug_field_2"));-- Document document = new Document();- document.add(newSuggestField("sug_field_1", "apple", 4));- document.add(newSuggestField("sug_field_2", "april", 3));- iw.addDocument(document);- document.clear();- document.add(newSuggestField("sug_field_1", "aples", 3));- document.add(newSuggestField("sug_field_2", "apartment", 2));- iw.addDocument(document);-- if (rarely()) {- iw.commit();+ public void testNegativeWeight() throws Exception {+ try {+ new SuggestField("suggest_field", "sugg", -1);+ fail("no exception thrown when indexing suggestion with negative weight");+ } catch (IllegalArgumentException expected) {+ assertTrue(expected.getMessage().contains("weight"));}+ }- DirectoryReader reader = iw.getReader();+ @Test+ public void testReservedChars() throws Exception {+ CharsRefBuilder charsRefBuilder = new CharsRefBuilder();+ charsRefBuilder.append("sugg");+ charsRefBuilder.setCharAt(2, (char) CompletionAnalyzer.SEP_LABEL);+ try {+ new SuggestField("name", charsRefBuilder.toString(), 1);+ fail("no exception thrown for suggestion value containing SEP_LABEL:" + CompletionAnalyzer.SEP_LABEL);+ } catch (IllegalArgumentException e) {+ assertTrue(e.getMessage().contains("[0x1f]"));+ }- SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader, analyzer);- TopSuggestDocs suggestDocs1 = suggestIndexSearcher.suggest("sug_field_1", "ap", 4);- assertSuggestions(suggestDocs1, new Entry("apple", 4), new Entry("aples", 3));- TopSuggestDocs suggestDocs2 = suggestIndexSearcher.suggest("sug_field_2", "ap", 4);- assertSuggestions(suggestDocs2, new Entry("april", 3), new Entry("apartment", 2));+ charsRefBuilder.setCharAt(2, (char) CompletionAnalyzer.HOLE_CHARACTER);+ try {+ new SuggestField("name", charsRefBuilder.toString(), 1);+ fail("no exception thrown for suggestion value containing HOLE_CHARACTER:" + CompletionAnalyzer.HOLE_CHARACTER);+ } catch (IllegalArgumentException e) {+ assertTrue(e.getMessage().contains("[0x1e]"));+ }- // check that the doc ids are consistent- for (int i = 0; i < suggestDocs1.scoreDocs.length; i++) {- ScoreDoc suggestScoreDoc = suggestDocs1.scoreDocs[i];- assertThat(suggestScoreDoc.doc, equalTo(suggestDocs2.scoreDocs[i].doc));+ charsRefBuilder.setCharAt(2, (char) NRTSuggesterBuilder.END_BYTE);+ try {+ new SuggestField("name", charsRefBuilder.toString(), 1);+ fail("no exception thrown for suggestion value containing END_BYTE:" + NRTSuggesterBuilder.END_BYTE);+ } catch (IllegalArgumentException e) {+ assertTrue(e.getMessage().contains("[0x0]"));}+ }+ @Test+ public void testEmpty() throws Exception {+ Analyzer analyzer = new MockAnalyzer(random());+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));+ DirectoryReader reader = iw.getReader();+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "ab"));+ TopSuggestDocs lookupDocs = suggestIndexSearcher.suggest(query, 3);+ assertThat(lookupDocs.totalHits, equalTo(0));reader.close();iw.close();}@@ -150,11 +140,11 @@ public class SuggestFieldTest extends LuceneTestCase {Analyzer analyzer = new MockAnalyzer(random());RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));int num = Math.min(1000, atLeast(300));- long[] weights = new long[num];+ int[] weights = new int[num];for(int i = 0; i < num; i++) {Document document = new Document();- weights[i] = Math.abs(random().nextLong());- document.add(newSuggestField("suggest_field", "abc", weights[i]));+ weights[i] = Math.abs(random().nextInt());+ document.add(new SuggestField("suggest_field", "abc", weights[i]));iw.addDocument(document);if (usually()) {@@ -169,8 +159,9 @@ public class SuggestFieldTest extends LuceneTestCase {expectedEntries[i - 1] = new Entry("abc", weights[num - i]);}- SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader, analyzer);- TopSuggestDocs lookupDocs = suggestIndexSearcher.suggest("suggest_field", "abc", num);+ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc"));+ TopSuggestDocs lookupDocs = suggestIndexSearcher.suggest(query, num);assertSuggestions(lookupDocs, expectedEntries);reader.close();@@ -189,7 +180,7 @@ public class SuggestFieldTest extends LuceneTestCase {int numLive = 0;List<Entry> expectedEntries = new ArrayList<>();for (int i = 0; i < num; i++) {- document.add(newSuggestField("suggest_field", "abc_" + i, num - i));+ document.add(new SuggestField("suggest_field", "abc_" + i, num - i));if (i % 2 == 0) {document.add(newStringField("str_field", "delete", Field.Store.YES));} else {@@ -208,8 +199,9 @@ public class SuggestFieldTest extends LuceneTestCase {iw.deleteDocuments(new Term("str_field", "delete"));DirectoryReader reader = DirectoryReader.open(iw, true);- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", "abc_", numLive);+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, numLive);assertSuggestions(suggest, expectedEntries.toArray(new Entry[expectedEntries.size()]));reader.close();@@ -223,7 +215,7 @@ public class SuggestFieldTest extends LuceneTestCase {int num = Math.min(1000, atLeast(10));Document document = new Document();for (int i = 0; i < num; i++) {- document.add(newSuggestField("suggest_field", "abc_" + i, i));+ document.add(new SuggestField("suggest_field", "abc_" + i, i));document.add(newStringField("str_fld", "deleted", Field.Store.NO));iw.addDocument(document);document.clear();@@ -235,10 +227,11 @@ public class SuggestFieldTest extends LuceneTestCase {Filter filter = new QueryWrapperFilter(new TermsQuery("str_fld", new BytesRef("non_existent")));DirectoryReader reader = iw.getReader();- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);// no random access required;// calling suggest with filter that does not match any documents should early terminate- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", "abc_", num, filter);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"), filter);+ TopSuggestDocs suggest = indexSearcher.suggest(query, num);assertThat(suggest.totalHits, equalTo(0));reader.close();iw.close();@@ -252,7 +245,7 @@ public class SuggestFieldTest extends LuceneTestCase {int num = Math.min(1000, atLeast(10));Document document = new Document();for (int i = 0; i < num; i++) {- document.add(newSuggestField("suggest_field", "abc_" + i, i));+ document.add(new SuggestField("suggest_field", "abc_" + i, i));document.add(newStringField("delete", "delete", Field.Store.NO));iw.addDocument(document);document.clear();@@ -265,8 +258,9 @@ public class SuggestFieldTest extends LuceneTestCase {iw.deleteDocuments(new Term("delete", "delete"));DirectoryReader reader = DirectoryReader.open(iw, true);- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", "abc_", num);+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, num);assertThat(suggest.totalHits, equalTo(0));reader.close();@@ -281,7 +275,7 @@ public class SuggestFieldTest extends LuceneTestCase {int num = Math.min(1000, atLeast(10));Document document = new Document();for (int i = 1; i <= num; i++) {- document.add(newSuggestField("suggest_field", "abc_" + i, i));+ document.add(new SuggestField("suggest_field", "abc_" + i, i));document.add(new IntField("weight_fld", i, Field.Store.YES));iw.addDocument(document);document.clear();@@ -294,8 +288,9 @@ public class SuggestFieldTest extends LuceneTestCase {iw.deleteDocuments(NumericRangeQuery.newIntRange("weight_fld", 2, null, true, false));DirectoryReader reader = DirectoryReader.open(iw, true);- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", "abc_", 1);+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, 1);assertSuggestions(suggest, new Entry("abc_1", 1));reader.close();@@ -303,48 +298,38 @@ public class SuggestFieldTest extends LuceneTestCase {}@Test- public void testSuggestOnMostlyFilteredOutDocuments() throws Exception {+ public void testMultipleSuggestFieldsPerDoc() throws Exception {Analyzer analyzer = new MockAnalyzer(random());- RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));- int num = Math.min(1000, atLeast(10));+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "sug_field_1", "sug_field_2"));+Document document = new Document();- for (int i = 0; i < num; i++) {- document.add(newSuggestField("suggest_field", "abc_" + i, i));- document.add(new IntField("filter_int_fld", i, Field.Store.NO));- iw.addDocument(document);- document.clear();+ document.add(new SuggestField("sug_field_1", "apple", 4));+ document.add(new SuggestField("sug_field_2", "april", 3));+ iw.addDocument(document);+ document.clear();+ document.add(new SuggestField("sug_field_1", "aples", 3));+ document.add(new SuggestField("sug_field_2", "apartment", 2));+ iw.addDocument(document);- if (usually()) {- iw.commit();- }+ if (rarely()) {+ iw.commit();}DirectoryReader reader = iw.getReader();- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);-- int topScore = num/2;- QueryWrapperFilter filterWrapper = new QueryWrapperFilter(NumericRangeQuery.newIntRange("filter_int_fld", 0, topScore, true, true));- Filter filter = randomAccessFilter(filterWrapper);- // if at most half of the top scoring documents have been filtered out- // the search should be admissible for a single segment- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", "abc_", num, filter);- assertTrue(suggest.totalHits >= 1);- assertThat(suggest.scoreLookupDocs()[0].key.toString(), equalTo("abc_" + topScore));- assertThat(suggest.scoreLookupDocs()[0].score, equalTo((float) topScore));-- filterWrapper = new QueryWrapperFilter(NumericRangeQuery.newIntRange("filter_int_fld", 0, 0, true, true));- filter = randomAccessFilter(filterWrapper);- // if more than half of the top scoring documents have been filtered out- // search is not admissible, so # of suggestions requested is num instead of 1- suggest = indexSearcher.suggest("suggest_field", "abc_", num, filter);- assertSuggestions(suggest, new Entry("abc_0", 0));-- filterWrapper = new QueryWrapperFilter(NumericRangeQuery.newIntRange("filter_int_fld", num - 1, num - 1, true, true));- filter = randomAccessFilter(filterWrapper);- // if only lower scoring documents are filtered out- // search is admissible- suggest = indexSearcher.suggest("suggest_field", "abc_", 1, filter);- assertSuggestions(suggest, new Entry("abc_" + (num - 1), num - 1));++ SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("sug_field_1", "ap"));+ TopSuggestDocs suggestDocs1 = suggestIndexSearcher.suggest(query, 4);+ assertSuggestions(suggestDocs1, new Entry("apple", 4), new Entry("aples", 3));+ query = new PrefixCompletionQuery(analyzer, new Term("sug_field_2", "ap"));+ TopSuggestDocs suggestDocs2 = suggestIndexSearcher.suggest(query, 4);+ assertSuggestions(suggestDocs2, new Entry("april", 3), new Entry("apartment", 2));++ // check that the doc ids are consistent+ for (int i = 0; i < suggestDocs1.scoreDocs.length; i++) {+ ScoreDoc suggestScoreDoc = suggestDocs1.scoreDocs[i];+ assertThat(suggestScoreDoc.doc, equalTo(suggestDocs2.scoreDocs[i].doc));+ }reader.close();iw.close();@@ -362,7 +347,7 @@ public class SuggestFieldTest extends LuceneTestCase {// suggest should early terminate for// segments with docs having lower suggestion weightsfor (int i = num; i > 0; i--) {- document.add(newSuggestField("suggest_field", "abc_" + i, i));+ document.add(new SuggestField("suggest_field", "abc_" + i, i));iw.addDocument(document);document.clear();if (i % 4 == 0) {@@ -370,8 +355,9 @@ public class SuggestFieldTest extends LuceneTestCase {}}DirectoryReader reader = iw.getReader();- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", "abc_", 1);+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, 1);assertSuggestions(suggest, new Entry("abc_" + num, num));reader.close();@@ -389,7 +375,7 @@ public class SuggestFieldTest extends LuceneTestCase {// ensure at least some segments have no suggest fieldfor (int i = num; i > 0; i--) {if (random().nextInt(4) == 1) {- document.add(newSuggestField("suggest_field", "abc_" + i, i));+ document.add(new SuggestField("suggest_field", "abc_" + i, i));entries.add(new Entry("abc_" + i, i));}document.add(new IntField("weight_fld", i, Field.Store.YES));@@ -400,54 +386,15 @@ public class SuggestFieldTest extends LuceneTestCase {}}DirectoryReader reader = iw.getReader();- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", "abc_", (entries.size() == 0) ? 1 : entries.size());+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, (entries.size() == 0) ? 1 : entries.size());assertSuggestions(suggest, entries.toArray(new Entry[entries.size()]));reader.close();iw.close();}- @Test- public void testDocFiltering() throws Exception {- Analyzer analyzer = new MockAnalyzer(random());- RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));-- Document document = new Document();- document.add(new IntField("filter_int_fld", 9, Field.Store.NO));- document.add(newSuggestField("suggest_field", "apples", 3));- iw.addDocument(document);-- document.clear();- document.add(new IntField("filter_int_fld", 10, Field.Store.NO));- document.add(newSuggestField("suggest_field", "applle", 4));- iw.addDocument(document);-- document.clear();- document.add(new IntField("filter_int_fld", 4, Field.Store.NO));- document.add(newSuggestField("suggest_field", "apple", 5));- iw.addDocument(document);-- if (rarely()) {- iw.commit();- }-- DirectoryReader reader = iw.getReader();- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);-- // suggest without filter- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", "app", 3);- assertSuggestions(suggest, new Entry("apple", 5), new Entry("applle", 4), new Entry("apples", 3));-- // suggest with filter- QueryWrapperFilter filterWrapper = new QueryWrapperFilter(NumericRangeQuery.newIntRange("filter_int_fld", 5, 12, true, true));- Filter filter = randomAccessFilter(filterWrapper);- suggest = indexSearcher.suggest("suggest_field", "app", 3, filter);- assertSuggestions(suggest, new Entry("applle", 4), new Entry("apples", 3));-- reader.close();- iw.close();- }@Testpublic void testReturnedDocID() throws Exception {@@ -457,7 +404,7 @@ public class SuggestFieldTest extends LuceneTestCase {Document document = new Document();int num = Math.min(1000, atLeast(10));for (int i = 0; i < num; i++) {- document.add(newSuggestField("suggest_field", "abc_" + i, num));+ document.add(new SuggestField("suggest_field", "abc_" + i, num));document.add(new IntField("int_field", i, Field.Store.YES));iw.addDocument(document);document.clear();@@ -468,8 +415,9 @@ public class SuggestFieldTest extends LuceneTestCase {}DirectoryReader reader = iw.getReader();- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", "abc_", num);+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", "abc_"));+ TopSuggestDocs suggest = indexSearcher.suggest(query, num);assertEquals(num, suggest.totalHits);for (SuggestScoreDoc suggestScoreDoc : suggest.scoreLookupDocs()) {String key = suggestScoreDoc.key.toString();@@ -484,70 +432,6 @@ public class SuggestFieldTest extends LuceneTestCase {iw.close();}- @Test- public void testCompletionAnalyzerOptions() throws Exception {- Analyzer analyzer = new MockAnalyzer(random(), MockTokenizer.WHITESPACE, true, MockTokenFilter.ENGLISH_STOPSET);- Map<String, Analyzer> map = new HashMap<>();- map.put("suggest_field_default", new CompletionAnalyzer(analyzer));- CompletionAnalyzer completionAnalyzer = new CompletionAnalyzer(analyzer, false, true);- map.put("suggest_field_no_p_sep", completionAnalyzer);- completionAnalyzer = new CompletionAnalyzer(analyzer, true, false);- map.put("suggest_field_no_p_pos_inc", completionAnalyzer);- completionAnalyzer = new CompletionAnalyzer(analyzer, false, false);- map.put("suggest_field_no_p_sep_or_pos_inc", completionAnalyzer);- PerFieldAnalyzerWrapper analyzerWrapper = new PerFieldAnalyzerWrapper(analyzer, map);- RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzerWrapper, map.keySet()));-- Document document = new Document();- document.add(newSuggestField("suggest_field_default", "foobar", 7));- document.add(newSuggestField("suggest_field_default", "foo bar", 8));- document.add(newSuggestField("suggest_field_default", "the fo", 9));- document.add(newSuggestField("suggest_field_default", "the foo bar", 10));-- document.add(newSuggestField("suggest_field_no_p_sep", "foobar", 7));- document.add(newSuggestField("suggest_field_no_p_sep", "foo bar", 8));- document.add(newSuggestField("suggest_field_no_p_sep", "the fo", 9));- document.add(newSuggestField("suggest_field_no_p_sep", "the foo bar", 10));-- document.add(newSuggestField("suggest_field_no_p_pos_inc", "foobar", 7));- document.add(newSuggestField("suggest_field_no_p_pos_inc", "foo bar", 8));- document.add(newSuggestField("suggest_field_no_p_pos_inc", "the fo", 9));- document.add(newSuggestField("suggest_field_no_p_pos_inc", "the foo bar", 10));-- document.add(newSuggestField("suggest_field_no_p_sep_or_pos_inc", "foobar", 7));- document.add(newSuggestField("suggest_field_no_p_sep_or_pos_inc", "foo bar", 8));- document.add(newSuggestField("suggest_field_no_p_sep_or_pos_inc", "the fo", 9));- document.add(newSuggestField("suggest_field_no_p_sep_or_pos_inc", "the foo bar", 10));- iw.addDocument(document);-- DirectoryReader reader = iw.getReader();- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);-- TopSuggestDocs suggest;- suggest = indexSearcher.suggest("suggest_field_default", "fo", 4);- assertSuggestions(suggest, new Entry("foo bar", 8), new Entry("foobar", 7));- suggest = indexSearcher.suggest("suggest_field_default", "foob", 4);- assertSuggestions(suggest, new Entry("foobar", 7));-- suggest = indexSearcher.suggest("suggest_field_no_p_sep", "fo", 4); // matches all 4- assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("the fo", 9), new Entry("foo bar", 8), new Entry("foobar", 7));- suggest = indexSearcher.suggest("suggest_field_no_p_sep", "foob", 4); // except the fo- assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("foo bar", 8), new Entry("foobar", 7));-- suggest = indexSearcher.suggest("suggest_field_no_p_pos_inc", "fo", 4); //matches all 4- assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("the fo", 9), new Entry("foo bar", 8), new Entry("foobar", 7));- suggest = indexSearcher.suggest("suggest_field_no_p_pos_inc", "foob", 4); // only foobar- assertSuggestions(suggest, new Entry("foobar", 7));-- suggest = indexSearcher.suggest("suggest_field_no_p_sep_or_pos_inc", "fo", 4); // all 4- assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("the fo", 9), new Entry("foo bar", 8), new Entry("foobar", 7));- suggest = indexSearcher.suggest("suggest_field_no_p_sep_or_pos_inc", "foob", 4); // not the fo- assertSuggestions(suggest, new Entry("the foo bar", 10), new Entry("foo bar", 8), new Entry("foobar", 7));-- reader.close();- iw.close();- }-@Testpublic void testScoring() throws Exception {Analyzer analyzer = new MockAnalyzer(random());@@ -555,12 +439,12 @@ public class SuggestFieldTest extends LuceneTestCase {int num = Math.min(1000, atLeast(100));String[] prefixes = {"abc", "bac", "cab"};- Map<String, Long> mappings = new HashMap<>();+ Map<String, Integer> mappings = new HashMap<>();for (int i = 0; i < num; i++) {Document document = new Document();String suggest = prefixes[i % 3] + TestUtil.randomSimpleString(random(), 10) + "_" +String.valueOf(i);- long weight = Math.abs(random().nextLong());- document.add(newSuggestField("suggest_field", suggest, weight));+ int weight = Math.abs(random().nextInt());+ document.add(new SuggestField("suggest_field", suggest, weight));mappings.put(suggest, weight);iw.addDocument(document);@@ -570,9 +454,10 @@ public class SuggestFieldTest extends LuceneTestCase {}DirectoryReader reader = iw.getReader();- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);for (String prefix : prefixes) {- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", prefix, num);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", prefix));+ TopSuggestDocs suggest = indexSearcher.suggest(query, num);assertTrue(suggest.totalHits > 0);float topScore = -1;for (SuggestScoreDoc scoreDoc : suggest.scoreLookupDocs()) {@@ -596,17 +481,17 @@ public class SuggestFieldTest extends LuceneTestCase {RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field"));LineFileDocs lineFileDocs = new LineFileDocs(random());int num = Math.min(1000, atLeast(100));- Map<String, Long> mappings = new HashMap<>();+ Map<String, Integer> mappings = new HashMap<>();for (int i = 0; i < num; i++) {Document document = lineFileDocs.nextDoc();String title = document.getField("title").stringValue();- long weight = Math.abs(random().nextLong());- Long prevWeight = mappings.get(title);+ int weight = Math.abs(random().nextInt());+ Integer prevWeight = mappings.get(title);if (prevWeight == null || prevWeight < weight) {mappings.put(title, weight);}Document doc = new Document();- doc.add(newSuggestField("suggest_field", title, weight));+ doc.add(new SuggestField("suggest_field", title, weight));iw.addDocument(doc);if (rarely()) {@@ -615,12 +500,13 @@ public class SuggestFieldTest extends LuceneTestCase {}DirectoryReader reader = iw.getReader();- SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);+ SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);- for (Map.Entry<String, Long> entry : mappings.entrySet()) {+ for (Map.Entry<String, Integer> entry : mappings.entrySet()) {String title = entry.getKey();- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field", title, mappings.size());+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field", title));+ TopSuggestDocs suggest = indexSearcher.suggest(query, mappings.size());assertTrue(suggest.totalHits > 0);boolean matched = false;for (ScoreDoc scoreDoc : suggest.scoreDocs) {@@ -638,7 +524,7 @@ public class SuggestFieldTest extends LuceneTestCase {@Testpublic void testThreads() throws Exception {- Analyzer analyzer = new MockAnalyzer(random());+ final Analyzer analyzer = new MockAnalyzer(random());RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "suggest_field_1", "suggest_field_2", "suggest_field_3"));int num = Math.min(1000, atLeast(100));final String prefix1 = "abc1_";@@ -655,9 +541,9 @@ public class SuggestFieldTest extends LuceneTestCase {}for (int i = 0; i < num; i++) {Document doc = new Document();- doc.add(newSuggestField("suggest_field_1", prefix1 + i, i));- doc.add(newSuggestField("suggest_field_2", prefix2 + i, i));- doc.add(newSuggestField("suggest_field_3", prefix3 + i, i));+ doc.add(new SuggestField("suggest_field_1", prefix1 + i, i));+ doc.add(new SuggestField("suggest_field_2", prefix2 + i, i));+ doc.add(new SuggestField("suggest_field_3", prefix3 + i, i));iw.addDocument(doc);if (rarely()) {@@ -670,18 +556,21 @@ public class SuggestFieldTest extends LuceneTestCase {Thread threads[] = new Thread[numThreads];final CyclicBarrier startingGun = new CyclicBarrier(numThreads+1);final CopyOnWriteArrayList<Throwable> errors = new CopyOnWriteArrayList<>();- final SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader, analyzer);+ final SuggestIndexSearcher indexSearcher = new SuggestIndexSearcher(reader);for (int i = 0; i < threads.length; i++) {threads[i] = new Thread() {@Overridepublic void run() {try {startingGun.await();- TopSuggestDocs suggest = indexSearcher.suggest("suggest_field_1", prefix1, num);+ PrefixCompletionQuery query = new PrefixCompletionQuery(analyzer, new Term("suggest_field_1", prefix1));+ TopSuggestDocs suggest = indexSearcher.suggest(query, num);assertSuggestions(suggest, entries1);- suggest = indexSearcher.suggest("suggest_field_2", prefix2, num);+ query = new PrefixCompletionQuery(analyzer, new Term("suggest_field_2", prefix2));+ suggest = indexSearcher.suggest(query, num);assertSuggestions(suggest, entries2);- suggest = indexSearcher.suggest("suggest_field_3", prefix3, num);+ query = new PrefixCompletionQuery(analyzer, new Term("suggest_field_3", prefix3));+ suggest = indexSearcher.suggest(query, num);assertSuggestions(suggest, entries3);} catch (Throwable e) {errors.add(e);@@ -701,77 +590,47 @@ public class SuggestFieldTest extends LuceneTestCase {iw.close();}- private static class RandomAccessFilter extends Filter {+ static class Entry {+ final String output;+ final float value;+ final String context;- private final Filter in;-- private RandomAccessFilter(Filter in) {- this.in = in;+ Entry(String output, float value) {+ this(output, null, value);}- @Override- public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) throws IOException {- DocIdSet docIdSet = in.getDocIdSet(context, acceptDocs);- DocIdSetIterator iterator = docIdSet.iterator();- FixedBitSet bits = new FixedBitSet(context.reader().maxDoc());- if (iterator != null) {- bits.or(iterator);- }- return new BitDocIdSet(bits);- }-- @Override- public String toString(String field) {- return in.toString(field);- }-- @Override- public boolean equals(Object obj) {- if (super.equals(obj) == false) {- return false;- }- return in.equals(((RandomAccessFilter) obj).in);- }-- @Override- public int hashCode() {- return 31 * super.hashCode() + in.hashCode();- }- }-- private static Filter randomAccessFilter(Filter filter) {- return new RandomAccessFilter(filter);- }-- private static class Entry {- private final String output;- private final float value;-- private Entry(String output, float value) {+ Entry(String output, String context, float value) {this.output = output;this.value = value;+ this.context = context;}}- private void assertSuggestions(TopDocs actual, Entry... expected) {+ static void assertSuggestions(TopDocs actual, Entry... expected) {SuggestScoreDoc[] suggestScoreDocs = (SuggestScoreDoc[]) actual.scoreDocs;assertThat(suggestScoreDocs.length, equalTo(expected.length));for (int i = 0; i < suggestScoreDocs.length; i++) {SuggestScoreDoc lookupDoc = suggestScoreDocs[i];- assertThat(lookupDoc.key.toString(), equalTo(expected[i].output));- assertThat(lookupDoc.score, equalTo(expected[i].value));+ String msg = "Expected: " + toString(expected[i]) + " Actual: " + toString(lookupDoc);+ assertThat(msg, lookupDoc.key.toString(), equalTo(expected[i].output));+ assertThat(msg, lookupDoc.score, equalTo(expected[i].value));+ assertThat(msg, lookupDoc.context, equalTo(expected[i].context));}}- private SuggestField newSuggestField(String name, String value, long weight) throws IOException {- return new SuggestField(name, value, weight);+ private static String toString(Entry expected) {+ return "key:"+ expected.output+" score:"+expected.value+" context:"+expected.context;+ }++ private static String toString(SuggestScoreDoc actual) {+ return "key:"+ actual.key.toString()+" score:"+actual.score+" context:"+actual.context;}- private IndexWriterConfig iwcWithSuggestField(Analyzer analyzer, String... suggestFields) {+ static IndexWriterConfig iwcWithSuggestField(Analyzer analyzer, String... suggestFields) {return iwcWithSuggestField(analyzer, asSet(suggestFields));}- private IndexWriterConfig iwcWithSuggestField(Analyzer analyzer, Set<String> suggestFields) {+ static IndexWriterConfig iwcWithSuggestField(Analyzer analyzer, Set<String> suggestFields) {IndexWriterConfig iwc = newIndexWriterConfig(random(), analyzer);iwc.setMergePolicy(newLogMergePolicy());Codec filterCodec = new Lucene50Codec() {