Skip to content

Apache Lucene open-source search software

LUCENE-5666: move sortedset sortfield out of sandbox

Robert Muirac43e0a68df9
diff --git a/lucene/core/src/java/org/apache/lucene/search/SortedSetSelector.java b/lucene/core/src/java/org/apache/lucene/search/SortedSetSelector.java
new file mode 100644
index 00000000000..5ae4febb8ce
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/SortedSetSelector.java
@@ -0,0 +1,228 @@
+package org.apache.lucene.search;
+
+/*
+ * 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.index.DocValues;
+import org.apache.lucene.index.RandomAccessOrds;
+import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedSetDocValues;
+import org.apache.lucene.util.BytesRef;
+
+/** Selects a value from the document's set to use as the representative value */
+public class SortedSetSelector {
+
+ /**
+ * Type of selection to perform.
+ * <p>
+ * Limitations:
+ * <ul>
+ * <li>Fields containing {@link Integer#MAX_VALUE} or more unique values
+ * are unsupported.
+ * <li>Selectors other than ({@link Type#MIN}) require
+ * optional codec support. However several codecs provided by Lucene,
+ * including the current default codec, support this.
+ * </ul>
+ */
+ public enum Type {
+ /**
+ * 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
+ }
+
+ /** Wraps a multi-valued SortedSetDocValues as a single-valued view, using the specified selector */
+ public static SortedDocValues wrap(SortedSetDocValues sortedSet, Type selector) {
+ if (sortedSet.getValueCount() >= Integer.MAX_VALUE) {
+ throw new UnsupportedOperationException("fields containing more than " + (Integer.MAX_VALUE-1) + " unique terms are unsupported");
+ }
+
+ SortedDocValues singleton = DocValues.unwrapSingleton(sortedSet);
+ if (singleton != null) {
+ // 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 singleton;
+ } else if (selector == Type.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/core/src/java/org/apache/lucene/search/SortedSetSortField.java b/lucene/core/src/java/org/apache/lucene/search/SortedSetSortField.java
new file mode 100644
index 00000000000..157d4a3f1cf
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/SortedSetSortField.java
@@ -0,0 +1,133 @@
+package org.apache.lucene.search;
+
+/*
+ * 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.DocValues;
+import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedSetDocValues;
+import org.apache.lucene.search.FieldComparator;
+import org.apache.lucene.search.SortField;
+
+/**
+ * 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
+ * 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>
+ * @see SortedSetSelector
+ */
+public class SortedSetSortField extends SortField {
+
+ private final SortedSetSelector.Type 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, SortedSetSelector.Type.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 type for choosing the sort value from the set.
+ * <p>
+ * NOTE: selectors other than {@link SortedSetSelector.Type#MIN} require optional codec support.
+ */
+ public SortedSetSortField(String field, boolean reverse, SortedSetSelector.Type 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 SortedSetSelector.Type 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 = DocValues.getSortedSet(context.reader(), field);
+ return SortedSetSelector.wrap(sortedSet, selector);
+ }
+ };
+ }
+}
diff --git a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortFieldSelectors.java b/lucene/core/src/test/org/apache/lucene/search/TestSortedSetSelector.java
similarity index 97%
rename from lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortFieldSelectors.java
rename to lucene/core/src/test/org/apache/lucene/search/TestSortedSetSelector.java
index 4d3705f7156..0468c0fd1d7 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortFieldSelectors.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestSortedSetSelector.java
@@ -1,4 +1,4 @@
-package org.apache.lucene.sandbox.queries;
+package org.apache.lucene.search;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -40,7 +40,7 @@ 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 {
+public class TestSortedSetSelector extends LuceneTestCase {
static Codec savedCodec;
@BeforeClass
@@ -78,7 +78,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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));
+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSelector.Type.MAX));
TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
assertEquals(2, td.totalHits);
@@ -108,7 +108,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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));
+ Sort sort = new Sort(new SortedSetSortField("value", true, SortedSetSelector.Type.MAX));
TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
assertEquals(2, td.totalHits);
@@ -141,7 +141,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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 sortField = new SortedSetSortField("value", false, SortedSetSelector.Type.MAX);
sortField.setMissingValue(SortField.STRING_FIRST);
Sort sort = new Sort(sortField);
@@ -178,7 +178,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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 sortField = new SortedSetSortField("value", false, SortedSetSelector.Type.MAX);
sortField.setMissingValue(SortField.STRING_LAST);
Sort sort = new Sort(sortField);
@@ -210,7 +210,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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));
+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSelector.Type.MAX));
TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
assertEquals(2, td.totalHits);
@@ -241,7 +241,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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));
+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSelector.Type.MIDDLE_MIN));
TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
assertEquals(2, td.totalHits);
@@ -272,7 +272,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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));
+ Sort sort = new Sort(new SortedSetSortField("value", true, SortedSetSelector.Type.MIDDLE_MIN));
TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
assertEquals(2, td.totalHits);
@@ -306,7 +306,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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 sortField = new SortedSetSortField("value", false, SortedSetSelector.Type.MIDDLE_MIN);
sortField.setMissingValue(SortField.STRING_FIRST);
Sort sort = new Sort(sortField);
@@ -344,7 +344,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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 sortField = new SortedSetSortField("value", false, SortedSetSelector.Type.MIDDLE_MIN);
sortField.setMissingValue(SortField.STRING_LAST);
Sort sort = new Sort(sortField);
@@ -376,7 +376,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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));
+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSelector.Type.MIDDLE_MIN));
TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
assertEquals(2, td.totalHits);
@@ -407,7 +407,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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));
+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSelector.Type.MIDDLE_MAX));
TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
assertEquals(2, td.totalHits);
@@ -438,7 +438,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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));
+ Sort sort = new Sort(new SortedSetSortField("value", true, SortedSetSelector.Type.MIDDLE_MAX));
TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
assertEquals(2, td.totalHits);
@@ -472,7 +472,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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 sortField = new SortedSetSortField("value", false, SortedSetSelector.Type.MIDDLE_MAX);
sortField.setMissingValue(SortField.STRING_FIRST);
Sort sort = new Sort(sortField);
@@ -510,7 +510,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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 sortField = new SortedSetSortField("value", false, SortedSetSelector.Type.MIDDLE_MAX);
sortField.setMissingValue(SortField.STRING_LAST);
Sort sort = new Sort(sortField);
@@ -542,7 +542,7 @@ public class TestSortedSetSortFieldSelectors extends LuceneTestCase {
// 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));
+ Sort sort = new Sort(new SortedSetSortField("value", false, SortedSetSelector.Type.MIDDLE_MAX));
TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
assertEquals(2, td.totalHits);
diff --git a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortField.java b/lucene/core/src/test/org/apache/lucene/search/TestSortedSetSortField.java
similarity index 98%
rename from lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortField.java
rename to lucene/core/src/test/org/apache/lucene/search/TestSortedSetSortField.java
index aae5d154f1e..6a35e42bc4b 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSortedSetSortField.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestSortedSetSortField.java
@@ -1,4 +1,4 @@
-package org.apache.lucene.sandbox.queries;
+package org.apache.lucene.search;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -50,7 +50,7 @@ public class TestSortedSetSortField extends LuceneTestCase {
assertEquals(0, td.totalHits);
// for an empty index, any selector should work
- for (SortedSetSortField.Selector v : SortedSetSortField.Selector.values()) {
+ for (SortedSetSelector.Type v : SortedSetSelector.Type.values()) {
sort.setSort(new SortedSetSortField("sortedset", false, v));
td = empty.search(query, null, 10, sort, true, true);
assertEquals(0, td.totalHits);
@@ -69,7 +69,7 @@ public class TestSortedSetSortField extends LuceneTestCase {
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(new SortedSetSortField("a", false, SortedSetSelector.Type.MAX)));
assertFalse(sf.equals("foo"));
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SortedSetSortField.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SortedSetSortField.java
deleted file mode 100644
index b3dc1757073..00000000000
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SortedSetSortField.java
+++ /dev/null
@@ -1,327 +0,0 @@
-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.DocValues;
-import org.apache.lucene.index.RandomAccessOrds;
-import org.apache.lucene.index.SortedDocValues;
-import org.apache.lucene.index.SortedSetDocValues;
-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 = DocValues.getSortedSet(context.reader(), field);
-
- if (sortedSet.getValueCount() >= Integer.MAX_VALUE) {
- throw new UnsupportedOperationException("fields containing more than " + (Integer.MAX_VALUE-1) + " unique terms are unsupported");
- }
-
- SortedDocValues singleton = DocValues.unwrapSingleton(sortedSet);
- if (singleton != null) {
- // 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 singleton;
- } 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);
- }
- }
-}