Apache Lucene open-source search software
LUCENE-5454: SortField for SortedSetDV
Robert Muir736adc4756dc
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 95405627945..9b83c007fd9 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -68,6 +68,16 @@ Optimizations======================= Lucene 4.8.0 =======================+New Features++* LUCENE-5454: Add SortedSetSortField to lucene/sandbox, to allow sorting+ on multi-valued field. (Robert Muir)++API Changes++* LUCENE-5454: Add RandomAccessOrds, an optional extension of SortedSetDocValues+ that supports random access to the ordinals in a document. (Robert Muir)+Bug fixes* LUCENE-5450: Fix getField() NPE issues with SpanOr/SpanNear when they have andiff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesProducer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesProducer.javaindex a56baaa9e6b..bf7c5789d9c 100644--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesProducer.java+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesProducer.java@@ -29,6 +29,7 @@ import org.apache.lucene.index.CorruptIndexException;import org.apache.lucene.index.FieldInfo;import org.apache.lucene.index.IndexFileNames;import org.apache.lucene.index.NumericDocValues;+import org.apache.lucene.index.RandomAccessOrds;import org.apache.lucene.index.SegmentReadState;import org.apache.lucene.index.SortedDocValues;import org.apache.lucene.index.SortedSetDocValues;@@ -350,7 +351,8 @@ class DirectDocValuesProducer extends DocValuesProducer {final BinaryDocValues values = instance.values;// Must make a new instance since the iterator has state:- return new SortedSetDocValues() {+ return new RandomAccessOrds() {+ int ordStart;int ordUpto;int ordLimit;@@ -365,7 +367,7 @@ class DirectDocValuesProducer extends DocValuesProducer {@Overridepublic void setDocument(int docID) {- ordUpto = (int) docToOrdAddress.get(docID);+ ordStart = ordUpto = (int) docToOrdAddress.get(docID);ordLimit = (int) docToOrdAddress.get(docID+1);}@@ -379,6 +381,16 @@ class DirectDocValuesProducer extends DocValuesProducer {return entry.values.count;}+ @Override+ public long ordAt(int index) {+ return ords.get(ordStart + index);+ }++ @Override+ public int cardinality() {+ return ordLimit - ordStart;+ }+// Leave lookupTerm to super's binary search// Leave termsEnum to superdiff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesProducer.javaindex 5671bc0222e..25c3842424f 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesProducer.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesProducer.java@@ -43,6 +43,7 @@ import org.apache.lucene.index.FieldInfo;import org.apache.lucene.index.FieldInfos;import org.apache.lucene.index.IndexFileNames;import org.apache.lucene.index.NumericDocValues;+import org.apache.lucene.index.RandomAccessOrds;import org.apache.lucene.index.SegmentReadState;import org.apache.lucene.index.SingletonSortedSetDocValues;import org.apache.lucene.index.SortedDocValues;@@ -523,7 +524,8 @@ public class Lucene45DocValuesProducer extends DocValuesProducer implements Clos// but the addresses to the ord stream are in RAMfinal MonotonicBlockPackedReader ordIndex = getOrdIndexInstance(data, field, ordIndexes.get(field.number));- return new SortedSetDocValues() {+ return new RandomAccessOrds() {+ long startOffset;long offset;long endOffset;@@ -540,7 +542,7 @@ public class Lucene45DocValuesProducer extends DocValuesProducer implements Clos@Overridepublic void setDocument(int docID) {- offset = (docID == 0 ? 0 : ordIndex.get(docID-1));+ startOffset = offset = (docID == 0 ? 0 : ordIndex.get(docID-1));endOffset = ordIndex.get(docID);}@@ -571,6 +573,16 @@ public class Lucene45DocValuesProducer extends DocValuesProducer implements Closreturn super.termsEnum();}}++ @Override+ public long ordAt(int index) {+ return ordinals.get(startOffset + index);+ }++ @Override+ public int cardinality() {+ return (int) (endOffset - startOffset);+ }};}diff --git a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.javaindex 1786c8c7ea9..4b915f1635f 100644--- a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java+++ b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java@@ -1401,25 +1401,43 @@ public class CheckIndex {if (docsWithField.get(i)) {int ordCount = 0;while ((ord = dv.nextOrd()) != SortedSetDocValues.NO_MORE_ORDS) {- ordCount++;if (ord <= lastOrd) {throw new RuntimeException("ords out of order: " + ord + " <= " + lastOrd + " for doc: " + i);}if (ord < 0 || ord > maxOrd) {throw new RuntimeException("ord out of bounds: " + ord);}+ if (dv instanceof RandomAccessOrds) {+ long ord2 = ((RandomAccessOrds)dv).ordAt(ordCount);+ if (ord != ord2) {+ throw new RuntimeException("ordAt(" + ordCount + ") inconsistent, expected=" + ord + ",got=" + ord2 + " for doc: " + i);+ }+ }lastOrd = ord;maxOrd2 = Math.max(maxOrd2, ord);seenOrds.set(ord);+ ordCount++;}if (ordCount == 0) {throw new RuntimeException("dv for field: " + fieldName + " has no ordinals but is not marked missing for doc: " + i);}+ if (dv instanceof RandomAccessOrds) {+ long ordCount2 = ((RandomAccessOrds)dv).cardinality();+ if (ordCount != ordCount2) {+ throw new RuntimeException("cardinality inconsistent, expected=" + ordCount + ",got=" + ordCount2 + " for doc: " + i);+ }+ }} else {long o = dv.nextOrd();if (o != SortedSetDocValues.NO_MORE_ORDS) {throw new RuntimeException("dv for field: " + fieldName + " is marked missing but has ord=" + o + " for doc: " + i);}+ if (dv instanceof RandomAccessOrds) {+ long ordCount2 = ((RandomAccessOrds)dv).cardinality();+ if (ordCount2 != 0) {+ throw new RuntimeException("dv for field: " + fieldName + " is marked missing but has cardinality " + ordCount2 + " for doc: " + i);+ }+ }}}if (maxOrd != maxOrd2) {diff --git a/lucene/core/src/java/org/apache/lucene/index/RandomAccessOrds.java b/lucene/core/src/java/org/apache/lucene/index/RandomAccessOrds.javanew file mode 100644index 00000000000..eafff937a5b--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/index/RandomAccessOrds.java@@ -0,0 +1,53 @@+package org.apache.lucene.index;++/*+ * 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.+ */++/**+ * Extension of {@link SortedSetDocValues} that supports random access+ * to the ordinals of a document.+ * <p>+ * Operations via this API are independent of the iterator api ({@link #nextOrd()})+ * and do not impact its state.+ * <p>+ * Codecs can optionally extend this API if they support constant-time access+ * to ordinals for the document.+ */+public abstract class RandomAccessOrds extends SortedSetDocValues {++ /** Sole constructor. (For invocation by subclass+ * constructors, typically implicit.) */+ protected RandomAccessOrds() {}++ /**+ * Retrieve the ordinal for the current document (previously+ * set by {@link #setDocument(int)} at the specified index.+ * <p>+ * An index ranges from {@code 0} to {@code cardinality()-1}.+ * The first ordinal value is at index {@code 0}, the next at index {@code 1},+ * and so on, as for array indexing.+ * @param index index of the ordinal for the document.+ * @return ordinal for the document at the specified index.+ */+ public abstract long ordAt(int index);++ /**+ * Returns the cardinality for the current document (previously+ * set by {@link #setDocument(int)}.+ */+ public abstract int cardinality();+}diff --git a/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValues.java b/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValues.javaindex 77e6e165b0e..fd9e99ef5e9 100644--- a/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValues.java+++ b/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValues.java@@ -69,7 +69,7 @@ public abstract class SortedSetDocValues {/** An empty SortedDocValues which returns {@link #NO_MORE_ORDS} for every document */- public static final SortedSetDocValues EMPTY = new SortedSetDocValues() {+ public static final SortedSetDocValues EMPTY = new RandomAccessOrds() {@Overridepublic long nextOrd() {@@ -88,6 +88,16 @@ public abstract class SortedSetDocValues {public long getValueCount() {return 0;}++ @Override+ public long ordAt(int index) {+ throw new IndexOutOfBoundsException();+ }++ @Override+ public int cardinality() {+ return 0;+ }};/** If {@code key} exists, returns its ordinal, elsediff --git a/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java b/lucene/core/src/java/org/apache/lucene/search/FieldComparator.javaindex 44bec130998..5c81ab57417 100644--- a/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java+++ b/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java@@ -717,7 +717,7 @@ public abstract class FieldComparator<T> {* to large results, this comparator will be much faster* than {@link org.apache.lucene.search.FieldComparator.TermValComparator}. For very small* result sets it may be slower. */- public static final class TermOrdValComparator extends FieldComparator<BytesRef> {+ public static class TermOrdValComparator extends FieldComparator<BytesRef> {/* Ords for each slot.@lucene.internal */final int[] ords;@@ -767,8 +767,6 @@ public abstract class FieldComparator<T> {boolean topSameReader;int topOrd;- private int docBase;-final BytesRef tempBR = new BytesRef();/** -1 if missing values are sorted first, 1 if they are@@ -856,10 +854,14 @@ public abstract class FieldComparator<T> {readerGen[slot] = currentReaderGen;}+ /** Retrieves the SortedDocValues for the field in this segment */+ protected SortedDocValues getSortedDocValues(AtomicReaderContext context, String field) throws IOException {+ return FieldCache.DEFAULT.getTermsIndex(context.reader(), field);+ }+@Overridepublic FieldComparator<BytesRef> setNextReader(AtomicReaderContext context) throws IOException {- docBase = context.docBase;- termsIndex = FieldCache.DEFAULT.getTermsIndex(context.reader(), field);+ termsIndex = getSortedDocValues(context, field);currentReaderGen++;if (topValue != null) {diff --git a/lucene/core/src/java/org/apache/lucene/search/SortField.java b/lucene/core/src/java/org/apache/lucene/search/SortField.javaindex 07a4932444d..2987f9572e0 100644--- a/lucene/core/src/java/org/apache/lucene/search/SortField.java+++ b/lucene/core/src/java/org/apache/lucene/search/SortField.java@@ -23,10 +23,6 @@ import java.util.Comparator;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.StringHelper;-// TODO(simonw) -- for cleaner transition, maybe we should make-// a new SortField that subclasses this one and always uses-// index values?-/*** Stores information about how to sort documents by terms in an individual* field. Fields must be indexed in order to sort by them.@@ -106,9 +102,6 @@ public class SortField {// Used for 'sortMissingFirst/Last'public Object missingValue = null;- // Only used with type=STRING- public boolean sortMissingLast;-/** Creates a sort by terms in the given field with the type of term* values explicitly given.* @param field Name of field to sort by. Can be <code>null</code> ifdiff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SortedSetSortField.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SortedSetSortField.javanew file mode 100644index 00000000000..2bfc7437b14--- /dev/null+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SortedSetSortField.java@@ -0,0 +1,327 @@+package org.apache.lucene.sandbox.queries;++/*+ * 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.AtomicReaderContext;+import org.apache.lucene.index.RandomAccessOrds;+import org.apache.lucene.index.SingletonSortedSetDocValues;+import org.apache.lucene.index.SortedDocValues;+import org.apache.lucene.index.SortedSetDocValues;+import org.apache.lucene.search.FieldCache;+import org.apache.lucene.search.FieldComparator;+import org.apache.lucene.search.SortField;+import org.apache.lucene.util.BytesRef;++/**+ * SortField for {@link SortedSetDocValues}.+ * <p>+ * A SortedSetDocValues contains multiple values for a field, so sorting with+ * this technique "selects" a value as the representative sort value for the document.+ * <p>+ * By default, the minimum value in the set is selected as the sort value, but+ * this can be customized. Selectors other than the default do have some limitations+ * (see below) to ensure that all selections happen in constant-time for performance.+ * <p>+ * Like sorting by string, this also supports sorting missing values as first or last,+ * via {@link #setMissingValue(Object)}.+ * <p>+ * Limitations:+ * <ul>+ * <li>Fields containing {@link Integer#MAX_VALUE} or more unique values+ * are unsupported.+ * <li>Selectors other than the default ({@link Selector#MIN}) require+ * optional codec support. However several codecs provided by Lucene,+ * including the current default codec, support this.+ * </ul>+ */+public class SortedSetSortField extends SortField {++ /** Selects a value from the document's set to use as the sort value */+ public static enum Selector {+ /**+ * Selects the minimum value in the set+ */+ MIN,+ /**+ * Selects the maximum value in the set+ */+ MAX,+ /**+ * Selects the middle value in the set.+ * <p>+ * If the set has an even number of values, the lower of the middle two is chosen.+ */+ MIDDLE_MIN,+ /**+ * Selects the middle value in the set.+ * <p>+ * If the set has an even number of values, the higher of the middle two is chosen+ */+ MIDDLE_MAX+ }++ private final Selector selector;++ /**+ * Creates a sort, possibly in reverse, by the minimum value in the set+ * for the document.+ * @param field Name of field to sort by. Must not be null.+ * @param reverse True if natural order should be reversed.+ */+ public SortedSetSortField(String field, boolean reverse) {+ this(field, reverse, Selector.MIN);+ }++ /**+ * Creates a sort, possibly in reverse, specifying how the sort value from+ * the document's set is selected.+ * @param field Name of field to sort by. Must not be null.+ * @param reverse True if natural order should be reversed.+ * @param selector custom selector for choosing the sort value from the set.+ * <p>+ * NOTE: selectors other than {@link Selector#MIN} require optional codec support.+ */+ public SortedSetSortField(String field, boolean reverse, Selector selector) {+ super(field, SortField.Type.CUSTOM, reverse);+ if (selector == null) {+ throw new NullPointerException();+ }+ this.selector = selector;+ }++ /** Returns the selector in use for this sort */+ public Selector getSelector() {+ return selector;+ }++ @Override+ public int hashCode() {+ return 31 * super.hashCode() + selector.hashCode();+ }++ @Override+ public boolean equals(Object obj) {+ if (this == obj) return true;+ if (!super.equals(obj)) return false;+ if (getClass() != obj.getClass()) return false;+ SortedSetSortField other = (SortedSetSortField) obj;+ if (selector != other.selector) return false;+ return true;+ }++ @Override+ public String toString() {+ StringBuilder buffer = new StringBuilder();+ buffer.append("<sortedset" + ": \"").append(getField()).append("\">");+ if (getReverse()) buffer.append('!');+ if (missingValue != null) {+ buffer.append(" missingValue=");+ buffer.append(missingValue);+ }+ buffer.append(" selector=");+ buffer.append(selector);++ return buffer.toString();+ }++ /**+ * Set how missing values (the empty set) are sorted.+ * <p>+ * Note that this must be {@link #STRING_FIRST} or {@link #STRING_LAST}.+ */+ @Override+ public void setMissingValue(Object missingValue) {+ if (missingValue != STRING_FIRST && missingValue != STRING_LAST) {+ throw new IllegalArgumentException("For SORTED_SET type, missing value must be either STRING_FIRST or STRING_LAST");+ }+ this.missingValue = missingValue;+ }++ @Override+ public FieldComparator<?> getComparator(int numHits, int sortPos) throws IOException {+ return new FieldComparator.TermOrdValComparator(numHits, getField(), missingValue == STRING_LAST) {+ @Override+ protected SortedDocValues getSortedDocValues(AtomicReaderContext context, String field) throws IOException {+ SortedSetDocValues sortedSet = FieldCache.DEFAULT.getDocTermOrds(context.reader(), field);++ if (sortedSet.getValueCount() >= Integer.MAX_VALUE) {+ throw new UnsupportedOperationException("fields containing more than " + (Integer.MAX_VALUE-1) + " unique terms are unsupported");+ }++ if (sortedSet instanceof SingletonSortedSetDocValues) {+ // it's actually single-valued in practice, but indexed as multi-valued,+ // so just sort on the underlying single-valued dv directly.+ // regardless of selector type, this optimization is safe!+ return ((SingletonSortedSetDocValues) sortedSet).getSortedDocValues();+ } else if (selector == Selector.MIN) {+ return new MinValue(sortedSet);+ } else {+ if (sortedSet instanceof RandomAccessOrds == false) {+ throw new UnsupportedOperationException("codec does not support random access ordinals, cannot use selector: " + selector);+ }+ RandomAccessOrds randomOrds = (RandomAccessOrds) sortedSet;+ switch(selector) {+ case MAX: return new MaxValue(randomOrds);+ case MIDDLE_MIN: return new MiddleMinValue(randomOrds);+ case MIDDLE_MAX: return new MiddleMaxValue(randomOrds);+ case MIN:+ default:+ throw new AssertionError();+ }+ }+ }+ };+ }++ /** Wraps a SortedSetDocValues and returns the first ordinal (min) */+ static class MinValue extends SortedDocValues {+ final SortedSetDocValues in;++ MinValue(SortedSetDocValues in) {+ this.in = in;+ }++ @Override+ public int getOrd(int docID) {+ in.setDocument(docID);+ return (int) in.nextOrd();+ }++ @Override+ public void lookupOrd(int ord, BytesRef result) {+ in.lookupOrd(ord, result);+ }++ @Override+ public int getValueCount() {+ return (int) in.getValueCount();+ }++ @Override+ public int lookupTerm(BytesRef key) {+ return (int) in.lookupTerm(key);+ }+ }++ /** Wraps a SortedSetDocValues and returns the last ordinal (max) */+ static class MaxValue extends SortedDocValues {+ final RandomAccessOrds in;++ MaxValue(RandomAccessOrds in) {+ this.in = in;+ }++ @Override+ public int getOrd(int docID) {+ in.setDocument(docID);+ final int count = in.cardinality();+ if (count == 0) {+ return -1;+ } else {+ return (int) in.ordAt(count-1);+ }+ }++ @Override+ public void lookupOrd(int ord, BytesRef result) {+ in.lookupOrd(ord, result);+ }++ @Override+ public int getValueCount() {+ return (int) in.getValueCount();+ }++ @Override+ public int lookupTerm(BytesRef key) {+ return (int) in.lookupTerm(key);+ }+ }++ /** Wraps a SortedSetDocValues and returns the middle ordinal (or min of the two) */+ static class MiddleMinValue extends SortedDocValues {+ final RandomAccessOrds in;++ MiddleMinValue(RandomAccessOrds in) {+ this.in = in;+ }++ @Override+ public int getOrd(int docID) {+ in.setDocument(docID);+ final int count = in.cardinality();+ if (count == 0) {+ return -1;+ } else {+ return (int) in.ordAt((count-1) >>> 1);+ }+ }++ @Override+ public void lookupOrd(int ord, BytesRef result) {+ in.lookupOrd(ord, result);+ }++ @Override+ public int getValueCount() {+ return (int) in.getValueCount();+ }++ @Override+ public int lookupTerm(BytesRef key) {+ return (int) in.lookupTerm(key);+ }+ }++ /** Wraps a SortedSetDocValues and returns the middle ordinal (or max of the two) */+ static class MiddleMaxValue extends SortedDocValues {+ final RandomAccessOrds in;++ MiddleMaxValue(RandomAccessOrds in) {+ this.in = in;+ }++ @Override+ public int getOrd(int docID) {+ in.setDocument(docID);+ final int count = in.cardinality();+ if (count == 0) {+ return -1;+ } else {+ return (int) in.ordAt(count >>> 1);+ }+ }++ @Override+ public void lookupOrd(int ord, BytesRef result) {+ in.lookupOrd(ord, result);+ }++ @Override+ public int getValueCount() {+ return (int) in.getValueCount();+ }++ @Override+ public int lookupTerm(BytesRef key) {+ return (int) in.lookupTerm(key);+ }+ }+}diff --git a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortField.java b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortField.javanew file mode 100644index 00000000000..42b086adfde--- /dev/null+++ b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortField.java@@ -0,0 +1,225 @@+package org.apache.lucene.sandbox.queries;++/*+ * 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 org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.MultiReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.MatchAllDocsQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.Sort;+import org.apache.lucene.search.SortField;+import org.apache.lucene.search.TermQuery;+import org.apache.lucene.search.TopDocs;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.LuceneTestCase;++/** Simple tests for SortedSetSortField */+public class TestSortedSetSortField extends LuceneTestCase {++ public void testForward() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("value", "baz", Field.Store.NO));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(newStringField("value", "foo", Field.Store.NO));+ doc.add(newStringField("value", "bar", Field.Store.NO));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ Sort sort = new Sort(new SortedSetSortField("value", false));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));++ ir.close();+ dir.close();+ }++ public void testReverse() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("value", "foo", Field.Store.NO));+ doc.add(newStringField("value", "bar", Field.Store.NO));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(newStringField("value", "baz", Field.Store.NO));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);++ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ Sort sort = new Sort(new SortedSetSortField("value", true));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("2", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("1", searcher.doc(td.scoreDocs[1].doc).get("id"));++ ir.close();+ dir.close();+ }++ public void testMissingFirst() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("value", "baz", Field.Store.NO));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(newStringField("value", "foo", Field.Store.NO));+ doc.add(newStringField("value", "bar", Field.Store.NO));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ SortField sortField = new SortedSetSortField("value", false);+ sortField.setMissingValue(SortField.STRING_FIRST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // 'bar' comes before 'baz'+ // null comes first+ assertEquals("3", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("1", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[2].doc).get("id"));++ ir.close();+ dir.close();+ }++ public void testMissingLast() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("value", "baz", Field.Store.NO));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(newStringField("value", "foo", Field.Store.NO));+ doc.add(newStringField("value", "bar", Field.Store.NO));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ SortField sortField = new SortedSetSortField("value", false);+ sortField.setMissingValue(SortField.STRING_LAST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ // null comes last+ assertEquals("3", searcher.doc(td.scoreDocs[2].doc).get("id"));++ ir.close();+ dir.close();+ }++ public void testSingleton() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("value", "baz", Field.Store.NO));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(newStringField("value", "bar", Field.Store.NO));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ Sort sort = new Sort(new SortedSetSortField("value", false));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));++ ir.close();+ dir.close();+ }++ public void testEmptyIndex() throws Exception {+ IndexSearcher empty = newSearcher(new MultiReader());+ Query query = new TermQuery(new Term("contents", "foo"));++ Sort sort = new Sort();+ sort.setSort(new SortedSetSortField("sortedset", false));+ TopDocs td = empty.search(query, null, 10, sort, true, true);+ assertEquals(0, td.totalHits);++ // for an empty index, any selector should work+ for (SortedSetSortField.Selector v : SortedSetSortField.Selector.values()) {+ sort.setSort(new SortedSetSortField("sortedset", false, v));+ td = empty.search(query, null, 10, sort, true, true);+ assertEquals(0, td.totalHits);+ }+ }++ public void testEquals() throws Exception {+ SortField sf = new SortedSetSortField("a", false);+ assertFalse(sf.equals(null));++ assertEquals(sf, sf);++ SortField sf2 = new SortedSetSortField("a", false);+ assertEquals(sf, sf2);+ assertEquals(sf.hashCode(), sf2.hashCode());++ assertFalse(sf.equals(new SortedSetSortField("a", true)));+ assertFalse(sf.equals(new SortedSetSortField("b", false)));+ assertFalse(sf.equals(new SortedSetSortField("a", false, SortedSetSortField.Selector.MAX)));+ assertFalse(sf.equals("foo"));+ }+}diff --git a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortFieldDocValues.java b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortFieldDocValues.javanew file mode 100644index 00000000000..16228b87826--- /dev/null+++ b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortFieldDocValues.java@@ -0,0 +1,210 @@+package org.apache.lucene.sandbox.queries;++/*+ * 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 org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.SortedSetDocValuesField;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.search.FieldCache;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.MatchAllDocsQuery;+import org.apache.lucene.search.Sort;+import org.apache.lucene.search.SortField;+import org.apache.lucene.search.TopDocs;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;++/** Simple tests for SortedSetSortField, indexing the sortedset up front */+@SuppressCodecs({"Lucene40", "Lucene41"}) // avoid codecs that don't support sortedset+public class TestSortedSetSortFieldDocValues extends LuceneTestCase {++ @Override+ public void setUp() throws Exception {+ super.setUp();+ // ensure there is nothing in fieldcache before test starts+ FieldCache.DEFAULT.purgeAllCaches();+ }++ private void assertNoFieldCaches() {+ // docvalues sorting should NOT create any fieldcache entries!+ assertEquals(0, FieldCache.DEFAULT.getCacheEntries().length);+ }++ public void testForward() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("foo")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ Sort sort = new Sort(new SortedSetSortField("value", false));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testReverse() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("foo")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);++ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ Sort sort = new Sort(new SortedSetSortField("value", true));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("2", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("1", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMissingFirst() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("foo")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ SortField sortField = new SortedSetSortField("value", false);+ sortField.setMissingValue(SortField.STRING_FIRST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // 'bar' comes before 'baz'+ // null comes first+ assertEquals("3", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("1", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[2].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMissingLast() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("foo")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ SortField sortField = new SortedSetSortField("value", false);+ sortField.setMissingValue(SortField.STRING_LAST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ // null comes last+ assertEquals("3", searcher.doc(td.scoreDocs[2].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testSingleton() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ IndexSearcher searcher = newSearcher(ir);+ Sort sort = new Sort(new SortedSetSortField("value", false));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }+}diff --git a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortFieldSelectors.java b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortFieldSelectors.javanew file mode 100644index 00000000000..b68c1cede4b--- /dev/null+++ b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortFieldSelectors.java@@ -0,0 +1,584 @@+package org.apache.lucene.sandbox.queries;++/*+ * 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 org.apache.lucene.codecs.Codec;+import org.apache.lucene.codecs.diskdv.DiskDocValuesFormat;+import org.apache.lucene.codecs.lucene45.Lucene45DocValuesFormat;+import org.apache.lucene.codecs.memory.DirectDocValuesFormat;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.SortedSetDocValuesField;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.search.FieldCache;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.MatchAllDocsQuery;+import org.apache.lucene.search.Sort;+import org.apache.lucene.search.SortField;+import org.apache.lucene.search.TopDocs;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.LuceneTestCase;+import org.apache.lucene.util.TestUtil;+import org.junit.AfterClass;+import org.junit.BeforeClass;++/** Tests for SortedSetSortField selectors other than MIN,+ * these require optional codec support (random access to ordinals) */+public class TestSortedSetSortFieldSelectors extends LuceneTestCase {+ static Codec savedCodec;++ @BeforeClass+ public static void beforeClass() throws Exception {+ savedCodec = Codec.getDefault();+ // currently only these codecs that support random access ordinals+ int victim = random().nextInt(3);+ switch(victim) {+ case 0: Codec.setDefault(TestUtil.alwaysDocValuesFormat(new DirectDocValuesFormat()));+ case 1: Codec.setDefault(TestUtil.alwaysDocValuesFormat(new DiskDocValuesFormat()));+ default: Codec.setDefault(TestUtil.alwaysDocValuesFormat(new Lucene45DocValuesFormat()));+ }+ }++ @AfterClass+ public static void afterClass() throws Exception {+ Codec.setDefault(savedCodec);+ }++ @Override+ public void setUp() throws Exception {+ super.setUp();+ // ensure there is nothing in fieldcache before test starts+ FieldCache.DEFAULT.purgeAllCaches();+ }++ private void assertNoFieldCaches() {+ // docvalues sorting should NOT create any fieldcache entries!+ assertEquals(0, FieldCache.DEFAULT.getCacheEntries().length);+ }++ public void testMax() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("foo")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);++ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSortField.Selector.MAX));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'baz' comes before 'foo'+ assertEquals("2", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("1", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMaxReverse() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("foo")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);++ Sort sort = new Sort(new SortedSetSortField("value", true, SortedSetSortField.Selector.MAX));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'baz' comes before 'foo'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMaxMissingFirst() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("foo")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);++ SortField sortField = new SortedSetSortField("value", false, SortedSetSortField.Selector.MAX);+ sortField.setMissingValue(SortField.STRING_FIRST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // null comes first+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ // 'baz' comes before 'foo'+ assertEquals("3", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[2].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMaxMissingLast() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("foo")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);++ SortField sortField = new SortedSetSortField("value", false, SortedSetSortField.Selector.MAX);+ sortField.setMissingValue(SortField.STRING_LAST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // 'baz' comes before 'foo'+ assertEquals("3", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ // null comes last+ assertEquals("1", searcher.doc(td.scoreDocs[2].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMaxSingleton() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSortField.Selector.MAX));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMin() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("a")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("d")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSortField.Selector.MIDDLE_MIN));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'b' comes before 'c'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMinReverse() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("a")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("d")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ Sort sort = new Sort(new SortedSetSortField("value", true, SortedSetSortField.Selector.MIDDLE_MIN));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'b' comes before 'c'+ assertEquals("2", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("1", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMinMissingFirst() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("a")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("d")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ SortField sortField = new SortedSetSortField("value", false, SortedSetSortField.Selector.MIDDLE_MIN);+ sortField.setMissingValue(SortField.STRING_FIRST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // null comes first+ assertEquals("3", searcher.doc(td.scoreDocs[0].doc).get("id"));+ // 'b' comes before 'c'+ assertEquals("1", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[2].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMinMissingLast() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("a")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("d")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ SortField sortField = new SortedSetSortField("value", false, SortedSetSortField.Selector.MIDDLE_MIN);+ sortField.setMissingValue(SortField.STRING_LAST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // 'b' comes before 'c'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ // null comes last+ assertEquals("3", searcher.doc(td.scoreDocs[2].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMinSingleton() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSortField.Selector.MIDDLE_MIN));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMax() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("a")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("d")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSortField.Selector.MIDDLE_MAX));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'b' comes before 'c'+ assertEquals("2", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("1", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMaxReverse() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("a")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("d")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ Sort sort = new Sort(new SortedSetSortField("value", true, SortedSetSortField.Selector.MIDDLE_MAX));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'b' comes before 'c'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMaxMissingFirst() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("a")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("d")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ SortField sortField = new SortedSetSortField("value", false, SortedSetSortField.Selector.MIDDLE_MAX);+ sortField.setMissingValue(SortField.STRING_FIRST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // null comes first+ assertEquals("3", searcher.doc(td.scoreDocs[0].doc).get("id"));+ // 'b' comes before 'c'+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertEquals("1", searcher.doc(td.scoreDocs[2].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMaxMissingLast() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(newStringField("id", "3", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("a")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("c")));+ doc.add(new SortedSetDocValuesField("value", new BytesRef("d")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("b")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ SortField sortField = new SortedSetSortField("value", false, SortedSetSortField.Selector.MIDDLE_MAX);+ sortField.setMissingValue(SortField.STRING_LAST);+ Sort sort = new Sort(sortField);++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(3, td.totalHits);+ // 'b' comes before 'c'+ assertEquals("2", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("1", searcher.doc(td.scoreDocs[1].doc).get("id"));+ // null comes last+ assertEquals("3", searcher.doc(td.scoreDocs[2].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }++ public void testMiddleMaxSingleton() throws Exception {+ Directory dir = newDirectory();+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);+ Document doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("baz")));+ doc.add(newStringField("id", "2", Field.Store.YES));+ writer.addDocument(doc);+ doc = new Document();+ doc.add(new SortedSetDocValuesField("value", new BytesRef("bar")));+ doc.add(newStringField("id", "1", Field.Store.YES));+ writer.addDocument(doc);+ IndexReader ir = writer.getReader();+ writer.close();++ // slow wrapper does not support random access ordinals (there is no need for that!)+ IndexSearcher searcher = newSearcher(ir, false);+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSortField.Selector.MIDDLE_MAX));++ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);+ assertEquals(2, td.totalHits);+ // 'bar' comes before 'baz'+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));+ assertNoFieldCaches();++ ir.close();+ dir.close();+ }+}