Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

LUCENE-5748: Add SORTED_NUMERIC docvalues type

Robert Muir398af4596bd7
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index d60f4b8b267..96d03360bb5 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -132,6 +132,9 @@ New Features
* LUCENE-5743: Add Lucene49NormsFormat, which can compress in some cases
such as very short fields. (Ryan Ernst, Adrien Grand, Robert Muir)
+* LUCENE-5748: Add SORTED_NUMERIC docvalues type, which is efficient
+ for processing numeric fields with multiple values. (Robert Muir)
+
Changes in Backwards Compatibility Policy
* LUCENE-5634: Add reuse argument to IndexableField.tokenStream. This
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesConsumer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesConsumer.java
index 9c3b7bca0c3..41172baf315 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesConsumer.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesConsumer.java
@@ -32,7 +32,10 @@ import org.apache.lucene.util.IOUtils;
import static org.apache.lucene.codecs.memory.DirectDocValuesProducer.VERSION_CURRENT;
import static org.apache.lucene.codecs.memory.DirectDocValuesProducer.BYTES;
import static org.apache.lucene.codecs.memory.DirectDocValuesProducer.SORTED;
+import static org.apache.lucene.codecs.memory.DirectDocValuesProducer.SORTED_NUMERIC;
+import static org.apache.lucene.codecs.memory.DirectDocValuesProducer.SORTED_NUMERIC_SINGLETON;
import static org.apache.lucene.codecs.memory.DirectDocValuesProducer.SORTED_SET;
+import static org.apache.lucene.codecs.memory.DirectDocValuesProducer.SORTED_SET_SINGLETON;
import static org.apache.lucene.codecs.memory.DirectDocValuesProducer.NUMBER;
/**
@@ -238,67 +241,102 @@ class DirectDocValuesConsumer extends DocValuesConsumer {
// write the values as binary
addBinaryFieldValues(field, values);
}
-
- // note: this might not be the most efficient... but its fairly simple
+
@Override
- public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, final Iterable<Number> docToOrdCount, final Iterable<Number> ords) throws IOException {
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
meta.writeVInt(field.number);
- meta.writeByte(SORTED_SET);
-
- // First write docToOrdCounts, except we "aggregate" the
- // counts so they turn into addresses, and add a final
- // value = the total aggregate:
- addNumericFieldValues(field, new Iterable<Number>() {
-
- // Just aggregates the count values so they become
- // "addresses", and adds one more value in the end
- // (the final sum):
-
- @Override
- public Iterator<Number> iterator() {
- final Iterator<Number> iter = docToOrdCount.iterator();
+ if (isSingleValued(docToValueCount)) {
+ meta.writeByte(SORTED_NUMERIC_SINGLETON);
+ addNumericFieldValues(field, singletonView(docToValueCount, values, null));
+ } else {
+ meta.writeByte(SORTED_NUMERIC);
- return new Iterator<Number>() {
+ // First write docToValueCounts, except we "aggregate" the
+ // counts so they turn into addresses, and add a final
+ // value = the total aggregate:
+ addNumericFieldValues(field, countToAddressIterator(docToValueCount));
- long sum;
- boolean ended;
+ // Write values for all docs, appended into one big
+ // numerics:
+ addNumericFieldValues(field, values);
+ }
+ }
- @Override
- public boolean hasNext() {
- return iter.hasNext() || !ended;
- }
+ // note: this might not be the most efficient... but its fairly simple
+ @Override
+ public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, final Iterable<Number> docToOrdCount, final Iterable<Number> ords) throws IOException {
+ meta.writeVInt(field.number);
+
+ if (isSingleValued(docToOrdCount)) {
+ meta.writeByte(SORTED_SET_SINGLETON);
+ // Write ordinals for all docs, appended into one big
+ // numerics:
+ addNumericFieldValues(field, singletonView(docToOrdCount, ords, -1L));
+
+ // write the values as binary
+ addBinaryFieldValues(field, values);
+ } else {
+ meta.writeByte(SORTED_SET);
- @Override
- public Number next() {
- long toReturn = sum;
+ // First write docToOrdCounts, except we "aggregate" the
+ // counts so they turn into addresses, and add a final
+ // value = the total aggregate:
+ addNumericFieldValues(field, countToAddressIterator(docToOrdCount));
- if (iter.hasNext()) {
- Number n = iter.next();
- if (n != null) {
- sum += n.longValue();
- }
- } else if (!ended) {
- ended = true;
- } else {
- assert false;
+ // Write ordinals for all docs, appended into one big
+ // numerics:
+ addNumericFieldValues(field, ords);
+
+ // write the values as binary
+ addBinaryFieldValues(field, values);
+ }
+ }
+
+ /**
+ * Just aggregates the count values so they become
+ * "addresses", and adds one more value in the end
+ * (the final sum)
+ */
+ private Iterable<Number> countToAddressIterator(final Iterable<Number> counts) {
+ return new Iterable<Number>() {
+ @Override
+ public Iterator<Number> iterator() {
+ final Iterator<Number> iter = counts.iterator();
+
+ return new Iterator<Number>() {
+
+ long sum;
+ boolean ended;
+
+ @Override
+ public boolean hasNext() {
+ return iter.hasNext() || !ended;
+ }
+
+ @Override
+ public Number next() {
+ long toReturn = sum;
+
+ if (iter.hasNext()) {
+ Number n = iter.next();
+ if (n != null) {
+ sum += n.longValue();
}
-
- return toReturn;
+ } else if (!ended) {
+ ended = true;
+ } else {
+ assert false;
}
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
- });
-
- // Write ordinals for all docs, appended into one big
- // numerics:
- addNumericFieldValues(field, ords);
-
- // write the values as binary
- addBinaryFieldValues(field, values);
+
+ return toReturn;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+ };
}
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesProducer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectDocValuesProducer.java
index a5f238aadd1..175f1164e78 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
@@ -33,6 +33,7 @@ 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.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.store.ChecksumIndexInput;
import org.apache.lucene.store.IndexInput;
@@ -52,6 +53,7 @@ class DirectDocValuesProducer extends DocValuesProducer {
private final Map<Integer,BinaryEntry> binaries = new HashMap<>();
private final Map<Integer,SortedEntry> sorteds = new HashMap<>();
private final Map<Integer,SortedSetEntry> sortedSets = new HashMap<>();
+ private final Map<Integer,SortedNumericEntry> sortedNumerics = new HashMap<>();
private final IndexInput data;
// ram instances we have already loaded
@@ -63,6 +65,8 @@ class DirectDocValuesProducer extends DocValuesProducer {
new HashMap<>();
private final Map<Integer,SortedSetRawValues> sortedSetInstances =
new HashMap<>();
+ private final Map<Integer,SortedNumericRawValues> sortedNumericInstances =
+ new HashMap<>();
private final Map<Integer,Bits> docsWithFieldInstances = new HashMap<>();
private final int maxDoc;
@@ -73,10 +77,12 @@ class DirectDocValuesProducer extends DocValuesProducer {
static final byte BYTES = 1;
static final byte SORTED = 2;
static final byte SORTED_SET = 3;
+ static final byte SORTED_SET_SINGLETON = 4;
+ static final byte SORTED_NUMERIC = 5;
+ static final byte SORTED_NUMERIC_SINGLETON = 6;
- static final int VERSION_START = 0;
- static final int VERSION_CHECKSUM = 1;
- static final int VERSION_CURRENT = VERSION_CHECKSUM;
+ static final int VERSION_START = 2;
+ static final int VERSION_CURRENT = VERSION_START;
DirectDocValuesProducer(SegmentReadState state, String dataCodec, String dataExtension, String metaCodec, String metaExtension) throws IOException {
maxDoc = state.segmentInfo.getDocCount();
@@ -91,11 +97,7 @@ class DirectDocValuesProducer extends DocValuesProducer {
VERSION_CURRENT);
readFields(in);
- if (version >= VERSION_CHECKSUM) {
- CodecUtil.checkFooter(in);
- } else {
- CodecUtil.checkEOF(in);
- }
+ CodecUtil.checkFooter(in);
success = true;
} finally {
if (success) {
@@ -161,13 +163,24 @@ class DirectDocValuesProducer extends DocValuesProducer {
return entry;
}
- private SortedSetEntry readSortedSetEntry(IndexInput meta) throws IOException {
+ private SortedSetEntry readSortedSetEntry(IndexInput meta, boolean singleton) throws IOException {
SortedSetEntry entry = new SortedSetEntry();
- entry.docToOrdAddress = readNumericEntry(meta);
+ if (singleton == false) {
+ entry.docToOrdAddress = readNumericEntry(meta);
+ }
entry.ords = readNumericEntry(meta);
entry.values = readBinaryEntry(meta);
return entry;
}
+
+ private SortedNumericEntry readSortedNumericEntry(IndexInput meta, boolean singleton) throws IOException {
+ SortedNumericEntry entry = new SortedNumericEntry();
+ if (singleton == false) {
+ entry.docToAddress = readNumericEntry(meta);
+ }
+ entry.values = readNumericEntry(meta);
+ return entry;
+ }
private void readFields(IndexInput meta) throws IOException {
int fieldNumber = meta.readVInt();
@@ -182,9 +195,19 @@ class DirectDocValuesProducer extends DocValuesProducer {
sorteds.put(fieldNumber, entry);
binaries.put(fieldNumber, entry.values);
} else if (fieldType == SORTED_SET) {
- SortedSetEntry entry = readSortedSetEntry(meta);
+ SortedSetEntry entry = readSortedSetEntry(meta, false);
+ sortedSets.put(fieldNumber, entry);
+ binaries.put(fieldNumber, entry.values);
+ } else if (fieldType == SORTED_SET_SINGLETON) {
+ SortedSetEntry entry = readSortedSetEntry(meta, true);
sortedSets.put(fieldNumber, entry);
binaries.put(fieldNumber, entry.values);
+ } else if (fieldType == SORTED_NUMERIC) {
+ SortedNumericEntry entry = readSortedNumericEntry(meta, false);
+ sortedNumerics.put(fieldNumber, entry);
+ } else if (fieldType == SORTED_NUMERIC_SINGLETON) {
+ SortedNumericEntry entry = readSortedNumericEntry(meta, true);
+ sortedNumerics.put(fieldNumber, entry);
} else {
throw new CorruptIndexException("invalid entry type: " + fieldType + ", input=" + meta);
}
@@ -199,9 +222,7 @@ class DirectDocValuesProducer extends DocValuesProducer {
@Override
public void checkIntegrity() throws IOException {
- if (version >= VERSION_CHECKSUM) {
- CodecUtil.checksumEntireFile(data);
- }
+ CodecUtil.checksumEntireFile(data);
}
@Override
@@ -337,9 +358,10 @@ class DirectDocValuesProducer extends DocValuesProducer {
sortedInstances.put(field.number, instance);
}
}
- final NumericDocValues docToOrd = instance.docToOrd;
- final BinaryDocValues values = getBinary(field);
-
+ return newSortedInstance(instance.docToOrd, getBinary(field), entry.values.count);
+ }
+
+ private SortedDocValues newSortedInstance(final NumericDocValues docToOrd, final BinaryDocValues values, final int count) {
return new SortedDocValues() {
@Override
@@ -354,7 +376,7 @@ class DirectDocValuesProducer extends DocValuesProducer {
@Override
public int getValueCount() {
- return entry.values.count;
+ return count;
}
// Leave lookupTerm to super's binary search
@@ -371,6 +393,56 @@ class DirectDocValuesProducer extends DocValuesProducer {
return values;
}
+ @Override
+ public synchronized SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ SortedNumericRawValues instance = sortedNumericInstances.get(field.number);
+ final SortedNumericEntry entry = sortedNumerics.get(field.number);
+ if (instance == null) {
+ // Lazy load
+ instance = loadSortedNumeric(entry);
+ sortedNumericInstances.put(field.number, instance);
+ }
+
+ if (entry.docToAddress == null) {
+ final NumericDocValues single = instance.values;
+ final Bits docsWithField = getMissingBits(field.number, entry.values.missingOffset, entry.values.missingBytes);
+ return DocValues.singleton(single, docsWithField);
+ } else {
+ final NumericDocValues docToAddress = instance.docToAddress;
+ final NumericDocValues values = instance.values;
+
+ return new SortedNumericDocValues() {
+ int valueStart;
+ int valueLimit;
+
+ @Override
+ public void setDocument(int doc) {
+ valueStart = (int) docToAddress.get(doc);
+ valueLimit = (int) docToAddress.get(doc+1);
+ }
+
+ @Override
+ public long valueAt(int index) {
+ return values.get(valueStart + index);
+ }
+
+ @Override
+ public int count() {
+ return valueLimit - valueStart;
+ }
+ };
+ }
+ }
+
+ private SortedNumericRawValues loadSortedNumeric(SortedNumericEntry entry) throws IOException {
+ SortedNumericRawValues instance = new SortedNumericRawValues();
+ if (entry.docToAddress != null) {
+ instance.docToAddress = loadNumeric(entry.docToAddress);
+ }
+ instance.values = loadNumeric(entry.values);
+ return instance;
+ }
+
@Override
public synchronized SortedSetDocValues getSortedSet(FieldInfo field) throws IOException {
SortedSetRawValues instance = sortedSetInstances.get(field.number);
@@ -381,60 +453,67 @@ class DirectDocValuesProducer extends DocValuesProducer {
sortedSetInstances.put(field.number, instance);
}
- final NumericDocValues docToOrdAddress = instance.docToOrdAddress;
- final NumericDocValues ords = instance.ords;
- final BinaryDocValues values = getBinary(field);
-
- // Must make a new instance since the iterator has state:
- return new RandomAccessOrds() {
- int ordStart;
- int ordUpto;
- int ordLimit;
-
- @Override
- public long nextOrd() {
- if (ordUpto == ordLimit) {
- return NO_MORE_ORDS;
- } else {
- return ords.get(ordUpto++);
- }
- }
+ if (instance.docToOrdAddress == null) {
+ SortedDocValues sorted = newSortedInstance(instance.ords, getBinary(field), entry.values.count);
+ return DocValues.singleton(sorted);
+ } else {
+ final NumericDocValues docToOrdAddress = instance.docToOrdAddress;
+ final NumericDocValues ords = instance.ords;
+ final BinaryDocValues values = getBinary(field);
- @Override
- public void setDocument(int docID) {
- ordStart = ordUpto = (int) docToOrdAddress.get(docID);
- ordLimit = (int) docToOrdAddress.get(docID+1);
- }
-
- @Override
- public BytesRef lookupOrd(long ord) {
- return values.get((int) ord);
- }
-
- @Override
- public long getValueCount() {
- 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 super
- };
+ // Must make a new instance since the iterator has state:
+ return new RandomAccessOrds() {
+ int ordStart;
+ int ordUpto;
+ int ordLimit;
+
+ @Override
+ public long nextOrd() {
+ if (ordUpto == ordLimit) {
+ return NO_MORE_ORDS;
+ } else {
+ return ords.get(ordUpto++);
+ }
+ }
+
+ @Override
+ public void setDocument(int docID) {
+ ordStart = ordUpto = (int) docToOrdAddress.get(docID);
+ ordLimit = (int) docToOrdAddress.get(docID+1);
+ }
+
+ @Override
+ public BytesRef lookupOrd(long ord) {
+ return values.get((int) ord);
+ }
+
+ @Override
+ public long getValueCount() {
+ 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 super
+ };
+ }
}
private SortedSetRawValues loadSortedSet(SortedSetEntry entry) throws IOException {
SortedSetRawValues instance = new SortedSetRawValues();
- instance.docToOrdAddress = loadNumeric(entry.docToOrdAddress);
+ if (entry.docToOrdAddress != null) {
+ instance.docToOrdAddress = loadNumeric(entry.docToOrdAddress);
+ }
instance.ords = loadNumeric(entry.ords);
return instance;
}
@@ -467,6 +546,8 @@ class DirectDocValuesProducer extends DocValuesProducer {
switch(field.getDocValuesType()) {
case SORTED_SET:
return DocValues.docsWithValue(getSortedSet(field), maxDoc);
+ case SORTED_NUMERIC:
+ return DocValues.docsWithValue(getSortedNumeric(field), maxDoc);
case SORTED:
return DocValues.docsWithValue(getSorted(field), maxDoc);
case BINARY:
@@ -493,6 +574,11 @@ class DirectDocValuesProducer extends DocValuesProducer {
static class SortedRawValues {
NumericDocValues docToOrd;
}
+
+ static class SortedNumericRawValues {
+ NumericDocValues docToAddress;
+ NumericDocValues values;
+ }
static class SortedSetRawValues {
NumericDocValues docToOrdAddress;
@@ -531,6 +617,11 @@ class DirectDocValuesProducer extends DocValuesProducer {
BinaryEntry values;
}
+ static class SortedNumericEntry {
+ NumericEntry docToAddress;
+ NumericEntry values;
+ }
+
static class FSTEntry {
long offset;
long numOrds;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesConsumer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesConsumer.java
index f58581caa01..c2f80a24660 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesConsumer.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesConsumer.java
@@ -50,6 +50,10 @@ import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.BLOCK_SIZE
import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.BYTES;
import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.NUMBER;
import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.FST;
+import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.SORTED_SET;
+import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.SORTED_SET_SINGLETON;
+import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.SORTED_NUMERIC;
+import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.SORTED_NUMERIC_SINGLETON;
import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.DELTA_COMPRESSED;
import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.BLOCK_COMPRESSED;
import static org.apache.lucene.codecs.memory.MemoryDocValuesProducer.GCD_COMPRESSED;
@@ -98,10 +102,11 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
boolean missing = false;
// TODO: more efficient?
HashSet<Long> uniqueValues = null;
+ long count = 0;
+
if (optimizeStorage) {
uniqueValues = new HashSet<>();
- long count = 0;
long currentBlockMin = Long.MAX_VALUE;
long currentBlockMax = Long.MIN_VALUE;
for (Number nv : values) {
@@ -148,12 +153,12 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
currentBlockMin = Long.MAX_VALUE;
}
}
- assert count == maxDoc;
} else {
for (Number nv : values) {
long v = nv.longValue();
maxValue = Math.max(v, maxValue);
minValue = Math.min(v, minValue);
+ count++;
}
}
@@ -171,14 +176,14 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
final FormatAndBits deltaBPV = PackedInts.fastestFormatAndBits(maxDoc, deltaRequired, acceptableOverheadRatio);
final FormatAndBits tableBPV;
- if (uniqueValues != null) {
+ if (count < Integer.MAX_VALUE && uniqueValues != null) {
tableBPV = PackedInts.fastestFormatAndBits(maxDoc, PackedInts.bitsRequired(uniqueValues.size()-1), acceptableOverheadRatio);
} else {
tableBPV = null;
}
final FormatAndBits gcdBPV;
- if (gcd != 0 && gcd != 1) {
+ if (count < Integer.MAX_VALUE && gcd != 0 && gcd != 1) {
final long gcdDelta = (maxValue - minValue) / gcd;
final int gcdRequired = gcdDelta < 0 ? 64 : PackedInts.bitsRequired(gcdDelta);
gcdBPV = PackedInts.fastestFormatAndBits(maxDoc, gcdRequired, acceptableOverheadRatio);
@@ -196,6 +201,10 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
doBlock = true;
}
}
+ // blockpackedreader allows us to read in huge streams of ints
+ if (count >= Integer.MAX_VALUE) {
+ doBlock = true;
+ }
if (tableBPV != null && (tableBPV.bitsPerValue+tableBPV.bitsPerValue*acceptableOverheadRatio) < deltaBPV.bitsPerValue) {
// small number of unique values
@@ -213,10 +222,11 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
}
meta.writeVInt(PackedInts.VERSION_CURRENT);
+ meta.writeLong(count);
data.writeVInt(tableBPV.format.getId());
data.writeVInt(tableBPV.bitsPerValue);
- final PackedInts.Writer writer = PackedInts.getWriterNoHeader(data, tableBPV.format, maxDoc, tableBPV.bitsPerValue, PackedInts.DEFAULT_BUFFER_SIZE);
+ final PackedInts.Writer writer = PackedInts.getWriterNoHeader(data, tableBPV.format, (int)count, tableBPV.bitsPerValue, PackedInts.DEFAULT_BUFFER_SIZE);
for(Number nv : values) {
writer.add(encode.get(nv == null ? 0 : nv.longValue()));
}
@@ -224,12 +234,13 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
} else if (gcdBPV != null && (gcdBPV.bitsPerValue+gcdBPV.bitsPerValue*acceptableOverheadRatio) < deltaBPV.bitsPerValue) {
meta.writeByte(GCD_COMPRESSED);
meta.writeVInt(PackedInts.VERSION_CURRENT);
+ meta.writeLong(count);
data.writeLong(minValue);
data.writeLong(gcd);
data.writeVInt(gcdBPV.format.getId());
data.writeVInt(gcdBPV.bitsPerValue);
- final PackedInts.Writer writer = PackedInts.getWriterNoHeader(data, gcdBPV.format, maxDoc, gcdBPV.bitsPerValue, PackedInts.DEFAULT_BUFFER_SIZE);
+ final PackedInts.Writer writer = PackedInts.getWriterNoHeader(data, gcdBPV.format, (int)count, gcdBPV.bitsPerValue, PackedInts.DEFAULT_BUFFER_SIZE);
for (Number nv : values) {
long value = nv == null ? 0 : nv.longValue();
writer.add((value - minValue) / gcd);
@@ -238,6 +249,7 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
} else if (doBlock) {
meta.writeByte(BLOCK_COMPRESSED); // block delta-compressed
meta.writeVInt(PackedInts.VERSION_CURRENT);
+ meta.writeLong(count);
data.writeVInt(BLOCK_SIZE);
final BlockPackedWriter writer = new BlockPackedWriter(data, BLOCK_SIZE);
for (Number nv : values) {
@@ -247,12 +259,13 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
} else {
meta.writeByte(DELTA_COMPRESSED); // delta-compressed
meta.writeVInt(PackedInts.VERSION_CURRENT);
+ meta.writeLong(count);
final long minDelta = deltaBPV.bitsPerValue == 64 ? 0 : minValue;
data.writeLong(minDelta);
data.writeVInt(deltaBPV.format.getId());
data.writeVInt(deltaBPV.bitsPerValue);
- final PackedInts.Writer writer = PackedInts.getWriterNoHeader(data, deltaBPV.format, maxDoc, deltaBPV.bitsPerValue, PackedInts.DEFAULT_BUFFER_SIZE);
+ final PackedInts.Writer writer = PackedInts.getWriterNoHeader(data, deltaBPV.format, (int)count, deltaBPV.bitsPerValue, PackedInts.DEFAULT_BUFFER_SIZE);
for (Number nv : values) {
long v = nv == null ? 0 : nv.longValue();
writer.add(v - minDelta);
@@ -388,20 +401,58 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
// write the values as FST
writeFST(field, values);
}
+
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ meta.writeVInt(field.number);
+
+ if (isSingleValued(docToValueCount)) {
+ meta.writeByte(SORTED_NUMERIC_SINGLETON);
+ addNumericField(field, singletonView(docToValueCount, values, null), true);
+ } else {
+ meta.writeByte(SORTED_NUMERIC);
+
+ // write the addresses:
+ meta.writeVInt(PackedInts.VERSION_CURRENT);
+ meta.writeVInt(BLOCK_SIZE);
+ meta.writeLong(data.getFilePointer());
+ final MonotonicBlockPackedWriter writer = new MonotonicBlockPackedWriter(data, BLOCK_SIZE);
+ long addr = 0;
+ writer.add(addr);
+ for (Number v : docToValueCount) {
+ addr += v.longValue();
+ writer.add(addr);
+ }
+ writer.finish();
+ long valueCount = writer.ord();
+ meta.writeLong(valueCount);
+
+ // write the values
+ addNumericField(field, values, true);
+ }
+ }
// note: this might not be the most efficient... but its fairly simple
@Override
public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, final Iterable<Number> docToOrdCount, final Iterable<Number> ords) throws IOException {
- // write the ordinals as a binary field
- addBinaryField(field, new Iterable<BytesRef>() {
- @Override
- public Iterator<BytesRef> iterator() {
- return new SortedSetIterator(docToOrdCount.iterator(), ords.iterator());
- }
- });
+ meta.writeVInt(field.number);
+
+ if (isSingleValued(docToOrdCount)) {
+ meta.writeByte(SORTED_SET_SINGLETON);
+ addSortedField(field, values, singletonView(docToOrdCount, ords, -1L));
+ } else {
+ meta.writeByte(SORTED_SET);
+ // write the ordinals as a binary field
+ addBinaryField(field, new Iterable<BytesRef>() {
+ @Override
+ public Iterator<BytesRef> iterator() {
+ return new SortedSetIterator(docToOrdCount.iterator(), ords.iterator());
+ }
+ });
- // write the values as FST
- writeFST(field, values);
+ // write the values as FST
+ writeFST(field, values);
+ }
}
// per-document vint-encoded byte[]
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesProducer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesProducer.java
index e926a834e64..5fc6295da34 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesProducer.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesProducer.java
@@ -35,6 +35,7 @@ import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.store.ByteArrayDataInput;
@@ -45,6 +46,7 @@ import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.LongValues;
import org.apache.lucene.util.PagedBytes;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.BytesRefFSTEnum;
@@ -63,9 +65,11 @@ import org.apache.lucene.util.packed.PackedInts;
*/
class MemoryDocValuesProducer extends DocValuesProducer {
// metadata maps (just file pointers and minimal stuff)
- private final Map<Integer,NumericEntry> numerics;
- private final Map<Integer,BinaryEntry> binaries;
- private final Map<Integer,FSTEntry> fsts;
+ private final Map<Integer,NumericEntry> numerics = new HashMap<>();
+ private final Map<Integer,BinaryEntry> binaries = new HashMap<>();
+ private final Map<Integer,FSTEntry> fsts = new HashMap<>();
+ private final Map<Integer,SortedSetEntry> sortedSets = new HashMap<>();
+ private final Map<Integer,SortedNumericEntry> sortedNumerics = new HashMap<>();
private final IndexInput data;
// ram instances we have already loaded
@@ -76,6 +80,7 @@ class MemoryDocValuesProducer extends DocValuesProducer {
private final Map<Integer,FST<Long>> fstInstances =
new HashMap<>();
private final Map<Integer,Bits> docsWithFieldInstances = new HashMap<>();
+ private final Map<Integer,MonotonicBlockPackedReader> addresses = new HashMap<>();
private final int maxDoc;
private final AtomicLong ramBytesUsed;
@@ -84,6 +89,10 @@ class MemoryDocValuesProducer extends DocValuesProducer {
static final byte NUMBER = 0;
static final byte BYTES = 1;
static final byte FST = 2;
+ static final byte SORTED_SET = 4;
+ static final byte SORTED_SET_SINGLETON = 5;
+ static final byte SORTED_NUMERIC = 6;
+ static final byte SORTED_NUMERIC_SINGLETON = 7;
static final int BLOCK_SIZE = 4096;
@@ -92,11 +101,8 @@ class MemoryDocValuesProducer extends DocValuesProducer {
static final byte BLOCK_COMPRESSED = 2;
static final byte GCD_COMPRESSED = 3;
- static final int VERSION_START = 0;
- static final int VERSION_GCD_COMPRESSION = 1;
- static final int VERSION_CHECKSUM = 2;
- static final int VERSION_BLOCKDETECTION = 3;
- static final int VERSION_CURRENT = VERSION_BLOCKDETECTION;
+ static final int VERSION_START = 3;
+ static final int VERSION_CURRENT = VERSION_START;
MemoryDocValuesProducer(SegmentReadState state, String dataCodec, String dataExtension, String metaCodec, String metaExtension) throws IOException {
maxDoc = state.segmentInfo.getDocCount();
@@ -108,15 +114,8 @@ class MemoryDocValuesProducer extends DocValuesProducer {
version = CodecUtil.checkHeader(in, metaCodec,
VERSION_START,
VERSION_CURRENT);
- numerics = new HashMap<>();
- binaries = new HashMap<>();
- fsts = new HashMap<>();
readFields(in, state.fieldInfos);
- if (version >= VERSION_CHECKSUM) {
- CodecUtil.checkFooter(in);
- } else {
- CodecUtil.checkEOF(in);
- }
+ CodecUtil.checkFooter(in);
ramBytesUsed = new AtomicLong(RamUsageEstimator.shallowSizeOfInstance(getClass()));
success = true;
} finally {
@@ -146,53 +145,86 @@ class MemoryDocValuesProducer extends DocValuesProducer {
}
}
+ private NumericEntry readNumericEntry(IndexInput meta) throws IOException {
+ NumericEntry entry = new NumericEntry();
+ entry.offset = meta.readLong();
+ entry.missingOffset = meta.readLong();
+ if (entry.missingOffset != -1) {
+ entry.missingBytes = meta.readLong();
+ } else {
+ entry.missingBytes = 0;
+ }
+ entry.format = meta.readByte();
+ switch(entry.format) {
+ case DELTA_COMPRESSED:
+ case TABLE_COMPRESSED:
+ case BLOCK_COMPRESSED:
+ case GCD_COMPRESSED:
+ break;
+ default:
+ throw new CorruptIndexException("Unknown format: " + entry.format + ", input=" + meta);
+ }
+ entry.packedIntsVersion = meta.readVInt();
+ entry.count = meta.readLong();
+ return entry;
+ }
+
+ private BinaryEntry readBinaryEntry(IndexInput meta) throws IOException {
+ BinaryEntry entry = new BinaryEntry();
+ entry.offset = meta.readLong();
+ entry.numBytes = meta.readLong();
+ entry.missingOffset = meta.readLong();
+ if (entry.missingOffset != -1) {
+ entry.missingBytes = meta.readLong();
+ } else {
+ entry.missingBytes = 0;
+ }
+ entry.minLength = meta.readVInt();
+ entry.maxLength = meta.readVInt();
+ if (entry.minLength != entry.maxLength) {
+ entry.packedIntsVersion = meta.readVInt();
+ entry.blockSize = meta.readVInt();
+ }
+ return entry;
+ }
+
+ private FSTEntry readFSTEntry(IndexInput meta) throws IOException {
+ FSTEntry entry = new FSTEntry();
+ entry.offset = meta.readLong();
+ entry.numOrds = meta.readVLong();
+ return entry;
+ }
+
private void readFields(IndexInput meta, FieldInfos infos) throws IOException {
int fieldNumber = meta.readVInt();
while (fieldNumber != -1) {
int fieldType = meta.readByte();
if (fieldType == NUMBER) {
- NumericEntry entry = new NumericEntry();
- entry.offset = meta.readLong();
- entry.missingOffset = meta.readLong();
- if (entry.missingOffset != -1) {
- entry.missingBytes = meta.readLong();
- } else {
- entry.missingBytes = 0;
- }
- entry.format = meta.readByte();
- switch(entry.format) {
- case DELTA_COMPRESSED:
- case TABLE_COMPRESSED:
- case BLOCK_COMPRESSED:
- case GCD_COMPRESSED:
- break;
- default:
- throw new CorruptIndexException("Unknown format: " + entry.format + ", input=" + meta);
- }
- entry.packedIntsVersion = meta.readVInt();
- numerics.put(fieldNumber, entry);
+ numerics.put(fieldNumber, readNumericEntry(meta));
} else if (fieldType == BYTES) {
- BinaryEntry entry = new BinaryEntry();
- entry.offset = meta.readLong();
- entry.numBytes = meta.readLong();
- entry.missingOffset = meta.readLong();
- if (entry.missingOffset != -1) {
- entry.missingBytes = meta.readLong();
- } else {
- entry.missingBytes = 0;
- }
- entry.minLength = meta.readVInt();
- entry.maxLength = meta.readVInt();
- if (entry.minLength != entry.maxLength) {
- entry.packedIntsVersion = meta.readVInt();
- entry.blockSize = meta.readVInt();
- }
- binaries.put(fieldNumber, entry);
+ binaries.put(fieldNumber, readBinaryEntry(meta));
} else if (fieldType == FST) {
- FSTEntry entry = new FSTEntry();
- entry.offset = meta.readLong();
- entry.numOrds = meta.readVLong();
- fsts.put(fieldNumber, entry);
+ fsts.put(fieldNumber,readFSTEntry(meta));
+ } else if (fieldType == SORTED_SET) {
+ SortedSetEntry entry = new SortedSetEntry();
+ entry.singleton = false;
+ sortedSets.put(fieldNumber, entry);
+ } else if (fieldType == SORTED_SET_SINGLETON) {
+ SortedSetEntry entry = new SortedSetEntry();
+ entry.singleton = true;
+ sortedSets.put(fieldNumber, entry);
+ } else if (fieldType == SORTED_NUMERIC) {
+ SortedNumericEntry entry = new SortedNumericEntry();
+ entry.singleton = false;
+ entry.packedIntsVersion = meta.readVInt();
+ entry.blockSize = meta.readVInt();
+ entry.addressOffset = meta.readLong();
+ entry.valueCount = meta.readLong();
+ sortedNumerics.put(fieldNumber, entry);
+ } else if (fieldType == SORTED_NUMERIC_SINGLETON) {
+ SortedNumericEntry entry = new SortedNumericEntry();
+ entry.singleton = true;
+ sortedNumerics.put(fieldNumber, entry);
} else {
throw new CorruptIndexException("invalid entry type: " + fieldType + ", input=" + meta);
}
@@ -217,9 +249,7 @@ class MemoryDocValuesProducer extends DocValuesProducer {
@Override
public void checkIntegrity() throws IOException {
- if (version >= VERSION_CHECKSUM) {
- CodecUtil.checksumEntireFile(data);
- }
+ CodecUtil.checksumEntireFile(data);
}
private NumericDocValues loadNumeric(FieldInfo field) throws IOException {
@@ -237,7 +267,7 @@ class MemoryDocValuesProducer extends DocValuesProducer {
}
final int formatID = data.readVInt();
final int bitsPerValue = data.readVInt();
- final PackedInts.Reader ordsReader = PackedInts.getReaderNoHeader(data, PackedInts.Format.byId(formatID), entry.packedIntsVersion, maxDoc, bitsPerValue);
+ final PackedInts.Reader ordsReader = PackedInts.getReaderNoHeader(data, PackedInts.Format.byId(formatID), entry.packedIntsVersion, (int)entry.count, bitsPerValue);
ramBytesUsed.addAndGet(RamUsageEstimator.sizeOf(decode) + ordsReader.ramBytesUsed());
return new NumericDocValues() {
@Override
@@ -249,7 +279,7 @@ class MemoryDocValuesProducer extends DocValuesProducer {
final long minDelta = data.readLong();
final int formatIDDelta = data.readVInt();
final int bitsPerValueDelta = data.readVInt();
- final PackedInts.Reader deltaReader = PackedInts.getReaderNoHeader(data, PackedInts.Format.byId(formatIDDelta), entry.packedIntsVersion, maxDoc, bitsPerValueDelta);
+ final PackedInts.Reader deltaReader = PackedInts.getReaderNoHeader(data, PackedInts.Format.byId(formatIDDelta), entry.packedIntsVersion, (int)entry.count, bitsPerValueDelta);
ramBytesUsed.addAndGet(deltaReader.ramBytesUsed());
return new NumericDocValues() {
@Override
@@ -259,7 +289,7 @@ class MemoryDocValuesProducer extends DocValuesProducer {
};
case BLOCK_COMPRESSED:
final int blockSize = data.readVInt();
- final BlockPackedReader reader = new BlockPackedReader(data, entry.packedIntsVersion, blockSize, maxDoc, false);
+ final BlockPackedReader reader = new BlockPackedReader(data, entry.packedIntsVersion, blockSize, entry.count, false);
ramBytesUsed.addAndGet(reader.ramBytesUsed());
return reader;
case GCD_COMPRESSED:
@@ -267,7 +297,7 @@ class MemoryDocValuesProducer extends DocValuesProducer {
final long mult = data.readLong();
final int formatIDGCD = data.readVInt();
final int bitsPerValueGCD = data.readVInt();
- final PackedInts.Reader quotientReader = PackedInts.getReaderNoHeader(data, PackedInts.Format.byId(formatIDGCD), entry.packedIntsVersion, maxDoc, bitsPerValueGCD);
+ final PackedInts.Reader quotientReader = PackedInts.getReaderNoHeader(data, PackedInts.Format.byId(formatIDGCD), entry.packedIntsVersion, (int)entry.count, bitsPerValueGCD);
ramBytesUsed.addAndGet(quotientReader.ramBytesUsed());
return new NumericDocValues() {
@Override
@@ -413,8 +443,81 @@ class MemoryDocValuesProducer extends DocValuesProducer {
};
}
+ @Override
+ public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ SortedNumericEntry entry = sortedNumerics.get(field.number);
+ if (entry.singleton) {
+ NumericDocValues values = getNumeric(field);
+ NumericEntry ne = numerics.get(field.number);
+ Bits docsWithField = getMissingBits(field.number, ne.missingOffset, ne.missingBytes);
+ return DocValues.singleton(values, docsWithField);
+ } else {
+ final NumericDocValues values = getNumeric(field);
+ final MonotonicBlockPackedReader addr;
+ synchronized (this) {
+ MonotonicBlockPackedReader res = addresses.get(field.number);
+ if (res == null) {
+ data.seek(entry.addressOffset);
+ res = MonotonicBlockPackedReader.of(data, entry.packedIntsVersion, entry.blockSize, entry.valueCount, false);
+ addresses.put(field.number, res);
+ }
+ addr = res;
+ }
+ if (values instanceof LongValues) {
+ // probably not the greatest codec choice for this situation, but we support it
+ final LongValues longValues = (LongValues) values;
+ return new SortedNumericDocValues() {
+ long startOffset;
+ long endOffset;
+
+ @Override
+ public void setDocument(int doc) {
+ startOffset = (int) addr.get(doc);
+ endOffset = (int) addr.get(doc+1L);
+ }
+
+ @Override
+ public long valueAt(int index) {
+ return longValues.get(startOffset + index);
+ }
+
+ @Override
+ public int count() {
+ return (int) (endOffset - startOffset);
+ }
+ };
+ } else {
+ return new SortedNumericDocValues() {
+ int startOffset;
+ int endOffset;
+
+ @Override
+ public void setDocument(int doc) {
+ startOffset = (int) addr.get(doc);
+ endOffset = (int) addr.get(doc+1);
+ }
+
+ @Override
+ public long valueAt(int index) {
+ return values.get(startOffset + index);
+ }
+
+ @Override
+ public int count() {
+ return (endOffset - startOffset);
+ }
+ };
+ }
+ }
+ }
+
@Override
public SortedSetDocValues getSortedSet(FieldInfo field) throws IOException {
+ SortedSetEntry sortedSetEntry = sortedSets.get(field.number);
+ if (sortedSetEntry.singleton) {
+ return DocValues.singleton(getSorted(field));
+ }
+
final FSTEntry entry = fsts.get(field.number);
if (entry.numOrds == 0) {
return DocValues.emptySortedSet(); // empty FST!
@@ -530,6 +633,8 @@ class MemoryDocValuesProducer extends DocValuesProducer {
switch(field.getDocValuesType()) {
case SORTED_SET:
return DocValues.docsWithValue(getSortedSet(field), maxDoc);
+ case SORTED_NUMERIC:
+ return DocValues.docsWithValue(getSortedNumeric(field), maxDoc);
case SORTED:
return DocValues.docsWithValue(getSorted(field), maxDoc);
case BINARY:
@@ -550,6 +655,7 @@ class MemoryDocValuesProducer extends DocValuesProducer {
static class NumericEntry {
long offset;
+ long count;
long missingOffset;
long missingBytes;
byte format;
@@ -571,6 +677,18 @@ class MemoryDocValuesProducer extends DocValuesProducer {
long offset;
long numOrds;
}
+
+ static class SortedSetEntry {
+ boolean singleton;
+ }
+
+ static class SortedNumericEntry {
+ boolean singleton;
+ long addressOffset;
+ int packedIntsVersion;
+ int blockSize;
+ long valueCount;
+ }
static class BytesAndAddresses {
PagedBytes.Reader reader;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesFormat.java
index c256367f23f..7de4276f826 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesFormat.java
@@ -114,6 +114,9 @@ import org.apache.lucene.index.SegmentWriteState;
* this is a comma-separated list, and its padded with spaces to be fixed width. so trim() and split() it.
* and beware the empty string!
* an ord's value can be retrieved by seeking to startOffset + (9+pattern.length+maxlength)*ord
+ *
+ * for sorted numerics, its encoded (not very creatively) as a comma-separated list of strings the same as binary.
+ * beware the empty string!
*
* the reader can just scan this file when it opens, skipping over the data blocks
* and saving the offset/etc for each field.
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesReader.java
index 77f34911ea0..0f91e3d46c4 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesReader.java
@@ -48,6 +48,7 @@ import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.store.BufferedChecksumIndexInput;
import org.apache.lucene.store.ChecksumIndexInput;
@@ -347,6 +348,38 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
}
};
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ final BinaryDocValues binary = getBinary(field);
+ return new SortedNumericDocValues() {
+ long values[];
+
+ @Override
+ public void setDocument(int doc) {
+ String csv = binary.get(doc).utf8ToString();
+ if (csv.length() == 0) {
+ values = new long[0];
+ } else {
+ String s[] = csv.split(",");
+ values = new long[s.length];
+ for (int i = 0; i < values.length; i++) {
+ values[i] = Long.parseLong(s[i]);
+ }
+ }
+ }
+
+ @Override
+ public long valueAt(int index) {
+ return values[index];
+ }
+
+ @Override
+ public int count() {
+ return values.length;
+ }
+ };
+ }
@Override
public SortedSetDocValues getSortedSet(FieldInfo fieldInfo) throws IOException {
@@ -431,6 +464,8 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
switch (field.getDocValuesType()) {
case SORTED_SET:
return DocValues.docsWithValue(getSortedSet(field), maxDoc);
+ case SORTED_NUMERIC:
+ return DocValues.docsWithValue(getSortedNumeric(field), maxDoc);
case SORTED:
return DocValues.docsWithValue(getSorted(field), maxDoc);
case BINARY:
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesWriter.java
index 07efc296869..1e7bbfed37a 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesWriter.java
@@ -136,6 +136,10 @@ class SimpleTextDocValuesWriter extends DocValuesConsumer {
public void addBinaryField(FieldInfo field, Iterable<BytesRef> values) throws IOException {
assert fieldSeen(field.name);
assert field.getDocValuesType() == DocValuesType.BINARY;
+ doAddBinary(field, values);
+ }
+
+ private void doAddBinary(FieldInfo field, Iterable<BytesRef> values) throws IOException {
int maxLength = 0;
for(BytesRef value : values) {
final int length = value == null ? 0 : value.length;
@@ -267,6 +271,48 @@ class SimpleTextDocValuesWriter extends DocValuesConsumer {
}
}
+ @Override
+ public void addSortedNumericField(FieldInfo field, final Iterable<Number> docToValueCount, final Iterable<Number> values) throws IOException {
+ assert fieldSeen(field.name);
+ assert field.getDocValuesType() == DocValuesType.SORTED_NUMERIC;
+ doAddBinary(field, new Iterable<BytesRef>() {
+ @Override
+ public Iterator<BytesRef> iterator() {
+ final StringBuilder builder = new StringBuilder();
+ final BytesRef scratch = new BytesRef();
+ final Iterator<Number> counts = docToValueCount.iterator();
+ final Iterator<Number> numbers = values.iterator();
+
+ return new Iterator<BytesRef>() {
+
+ @Override
+ public boolean hasNext() {
+ return counts.hasNext();
+ }
+
+ @Override
+ public BytesRef next() {
+ builder.setLength(0);
+ long count = counts.next().longValue();
+ for (int i = 0; i < count; i++) {
+ if (i > 0) {
+ builder.append(',');
+ }
+ builder.append(Long.toString(numbers.next().longValue()));
+ }
+ scratch.copyChars(builder);
+ return scratch;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+ });
+ }
+
@Override
public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrdCount, Iterable<Number> ords) throws IOException {
assert fieldSeen(field.name);
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/DocValuesConsumer.java b/lucene/core/src/java/org/apache/lucene/codecs/DocValuesConsumer.java
index 977983a95fb..878c9d9cebf 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/DocValuesConsumer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/DocValuesConsumer.java
@@ -32,6 +32,7 @@ import org.apache.lucene.index.MultiDocValues.OrdinalMap;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.ArrayUtil;
@@ -93,6 +94,16 @@ public abstract class DocValuesConsumer implements Closeable {
* @throws IOException if an I/O error occurred.
*/
public abstract void addSortedField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrd) throws IOException;
+
+ /**
+ * Writes pre-sorted numeric docvalues for a field
+ * @param field field information
+ * @param docToValueCount Iterable of the number of values for each document. A zero
+ * count indicates a missing value.
+ * @param values Iterable of numeric values in sorted order (not deduplicated).
+ * @throws IOException if an I/O error occurred.
+ */
+ public abstract void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException;
/**
* Writes pre-sorted set docvalues for a field
@@ -265,6 +276,156 @@ public abstract class DocValuesConsumer implements Closeable {
});
}
+ /**
+ * Merges the sorted docvalues from <code>toMerge</code>.
+ * <p>
+ * The default implementation calls {@link #addSortedNumericField}, passing
+ * iterables that filter deleted documents.
+ */
+ public void mergeSortedNumericField(FieldInfo fieldInfo, final MergeState mergeState, List<SortedNumericDocValues> toMerge) throws IOException {
+ final AtomicReader readers[] = mergeState.readers.toArray(new AtomicReader[toMerge.size()]);
+ final SortedNumericDocValues dvs[] = toMerge.toArray(new SortedNumericDocValues[toMerge.size()]);
+
+ // step 3: add field
+ addSortedNumericField(fieldInfo,
+ // doc -> value count
+ new Iterable<Number>() {
+ @Override
+ public Iterator<Number> iterator() {
+ return new Iterator<Number>() {
+ int readerUpto = -1;
+ int docIDUpto;
+ int nextValue;
+ AtomicReader currentReader;
+ Bits currentLiveDocs;
+ boolean nextIsSet;
+
+ @Override
+ public boolean hasNext() {
+ return nextIsSet || setNext();
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Number next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ assert nextIsSet;
+ nextIsSet = false;
+ return nextValue;
+ }
+
+ private boolean setNext() {
+ while (true) {
+ if (readerUpto == readers.length) {
+ return false;
+ }
+
+ if (currentReader == null || docIDUpto == currentReader.maxDoc()) {
+ readerUpto++;
+ if (readerUpto < readers.length) {
+ currentReader = readers[readerUpto];
+ currentLiveDocs = currentReader.getLiveDocs();
+ }
+ docIDUpto = 0;
+ continue;
+ }
+
+ if (currentLiveDocs == null || currentLiveDocs.get(docIDUpto)) {
+ nextIsSet = true;
+ SortedNumericDocValues dv = dvs[readerUpto];
+ dv.setDocument(docIDUpto);
+ nextValue = dv.count();
+ docIDUpto++;
+ return true;
+ }
+
+ docIDUpto++;
+ }
+ }
+ };
+ }
+ },
+ // values
+ new Iterable<Number>() {
+ @Override
+ public Iterator<Number> iterator() {
+ return new Iterator<Number>() {
+ int readerUpto = -1;
+ int docIDUpto;
+ long nextValue;
+ AtomicReader currentReader;
+ Bits currentLiveDocs;
+ boolean nextIsSet;
+ int valueUpto;
+ int valueLength;
+
+ @Override
+ public boolean hasNext() {
+ return nextIsSet || setNext();
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Number next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ assert nextIsSet;
+ nextIsSet = false;
+ return nextValue;
+ }
+
+ private boolean setNext() {
+ while (true) {
+ if (readerUpto == readers.length) {
+ return false;
+ }
+
+ if (valueUpto < valueLength) {
+ nextValue = dvs[readerUpto].valueAt(valueUpto);
+ valueUpto++;
+ nextIsSet = true;
+ return true;
+ }
+
+ if (currentReader == null || docIDUpto == currentReader.maxDoc()) {
+ readerUpto++;
+ if (readerUpto < readers.length) {
+ currentReader = readers[readerUpto];
+ currentLiveDocs = currentReader.getLiveDocs();
+ }
+ docIDUpto = 0;
+ continue;
+ }
+
+ if (currentLiveDocs == null || currentLiveDocs.get(docIDUpto)) {
+ assert docIDUpto < currentReader.maxDoc();
+ SortedNumericDocValues dv = dvs[readerUpto];
+ dv.setDocument(docIDUpto);
+ valueUpto = 0;
+ valueLength = dv.count();
+ docIDUpto++;
+ continue;
+ }
+
+ docIDUpto++;
+ }
+ }
+ };
+ }
+ }
+ );
+ }
/**
* Merges the sorted docvalues from <code>toMerge</code>.
@@ -640,4 +801,49 @@ public abstract class DocValuesConsumer implements Closeable {
}
}
}
+
+ /** Helper: returns true if the given docToValue count contains only at most one value */
+ public static boolean isSingleValued(Iterable<Number> docToValueCount) {
+ for (Number count : docToValueCount) {
+ if (count.longValue() > 1) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /** Helper: returns single-valued view, using {@code missingValue} when count is zero */
+ public static Iterable<Number> singletonView(final Iterable<Number> docToValueCount, final Iterable<Number> values, final Number missingValue) {
+ assert isSingleValued(docToValueCount);
+ return new Iterable<Number>() {
+
+ @Override
+ public Iterator<Number> iterator() {
+ final Iterator<Number> countIterator = docToValueCount.iterator();
+ final Iterator<Number> valuesIterator = values.iterator();
+ return new Iterator<Number>() {
+
+ @Override
+ public boolean hasNext() {
+ return countIterator.hasNext();
+ }
+
+ @Override
+ public Number next() {
+ int count = countIterator.next().intValue();
+ if (count == 0) {
+ return missingValue;
+ } else {
+ return valuesIterator.next();
+ }
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+ };
+ }
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/DocValuesProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/DocValuesProducer.java
index 4741a856d1b..4e1783997da 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/DocValuesProducer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/DocValuesProducer.java
@@ -24,6 +24,7 @@ import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.Bits;
@@ -54,6 +55,11 @@ public abstract class DocValuesProducer implements Closeable, Accountable {
* used by a single thread. */
public abstract SortedDocValues getSorted(FieldInfo field) throws IOException;
+ /** Returns {@link SortedNumericDocValues} for this field.
+ * The returned instance need not be thread-safe: it will only be
+ * used by a single thread. */
+ public abstract SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException;
+
/** Returns {@link SortedSetDocValues} for this field.
* The returned instance need not be thread-safe: it will only be
* used by a single thread. */
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40DocValuesReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40DocValuesReader.java
index e8dc27eba42..3176a7fe761 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40DocValuesReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40DocValuesReader.java
@@ -32,6 +32,7 @@ import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.store.CompoundFileDirectory;
import org.apache.lucene.store.Directory;
@@ -628,6 +629,11 @@ final class Lucene40DocValuesReader extends DocValuesProducer {
}
};
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ throw new IllegalStateException("Lucene 4.0 does not support SortedNumeric: how did you pull this off?");
+ }
@Override
public SortedSetDocValues getSortedSet(FieldInfo field) throws IOException {
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesProducer.java
index 566f0efb5dc..eca68894355 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesProducer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesProducer.java
@@ -35,6 +35,7 @@ import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.store.ByteArrayDataInput;
@@ -490,6 +491,11 @@ class Lucene42DocValuesProducer extends DocValuesProducer {
return new Bits.MatchAllBits(maxDoc);
}
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ throw new IllegalStateException("Lucene 4.2 does not support SortedNumeric: how did you pull this off?");
+ }
@Override
public void close() throws IOException {
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42NormsConsumer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42NormsConsumer.java
index c7afc622e43..f3364863657 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42NormsConsumer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42NormsConsumer.java
@@ -205,6 +205,11 @@ class Lucene42NormsConsumer extends DocValuesConsumer {
throw new UnsupportedOperationException();
}
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, final Iterable<Number> docToOrdCount, final Iterable<Number> ords) throws IOException {
throw new UnsupportedOperationException();
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesConsumer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesConsumer.java
index 710ab7e078e..46b93e54c0a 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesConsumer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesConsumer.java
@@ -21,7 +21,6 @@ import java.io.Closeable; // javadocs
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.DocValuesConsumer;
@@ -43,7 +42,6 @@ class Lucene45DocValuesConsumer extends DocValuesConsumer implements Closeable {
static final int BLOCK_SIZE = 16384;
static final int ADDRESS_INTERVAL = 16;
- static final Number MISSING_ORD = Long.valueOf(-1);
/** Compressed using packed blocks of ints. */
public static final int DELTA_COMPRESSED = 0;
@@ -349,14 +347,10 @@ class Lucene45DocValuesConsumer extends DocValuesConsumer implements Closeable {
addTermsDict(field, values);
addNumericField(field, docToOrd, false);
}
-
- private static boolean isSingleValued(Iterable<Number> docToOrdCount) {
- for (Number ordCount : docToOrdCount) {
- if (ordCount.longValue() > 1) {
- return false;
- }
- }
- return true;
+
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ throw new UnsupportedOperationException("Lucene 4.5 does not support SORTED_NUMERIC");
}
@Override
@@ -367,40 +361,7 @@ class Lucene45DocValuesConsumer extends DocValuesConsumer implements Closeable {
if (isSingleValued(docToOrdCount)) {
meta.writeVInt(SORTED_SET_SINGLE_VALUED_SORTED);
// The field is single-valued, we can encode it as SORTED
- addSortedField(field, values, new Iterable<Number>() {
-
- @Override
- public Iterator<Number> iterator() {
- final Iterator<Number> docToOrdCountIt = docToOrdCount.iterator();
- final Iterator<Number> ordsIt = ords.iterator();
- return new Iterator<Number>() {
-
- @Override
- public boolean hasNext() {
- assert ordsIt.hasNext() ? docToOrdCountIt.hasNext() : true;
- return docToOrdCountIt.hasNext();
- }
-
- @Override
- public Number next() {
- final Number ordCount = docToOrdCountIt.next();
- if (ordCount.longValue() == 0) {
- return MISSING_ORD;
- } else {
- assert ordCount.longValue() == 1;
- return ordsIt.next();
- }
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- };
- }
-
- });
+ addSortedField(field, values, singletonView(docToOrdCount, ords, -1L));
return;
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesProducer.java
index 9ad611cc9e5..228da385d4d 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
@@ -47,6 +47,7 @@ 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.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.index.TermsEnum.SeekStatus;
@@ -541,6 +542,11 @@ public class Lucene45DocValuesProducer extends DocValuesProducer implements Clos
}
return ordIndex;
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ throw new IllegalStateException("Lucene 4.5 does not support SortedNumeric: how did you pull this off?");
+ }
@Override
public SortedSetDocValues getSortedSet(FieldInfo field) throws IOException {
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosFormat.java
index 82b98cd349f..809aac84fed 100755
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosFormat.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosFormat.java
@@ -115,7 +115,8 @@ public final class Lucene46FieldInfosFormat extends FieldInfosFormat {
static final String CODEC_NAME = "Lucene46FieldInfos";
static final int FORMAT_START = 0;
static final int FORMAT_CHECKSUM = 1;
- static final int FORMAT_CURRENT = FORMAT_CHECKSUM;
+ static final int FORMAT_SORTED_NUMERIC = 2;
+ static final int FORMAT_CURRENT = FORMAT_SORTED_NUMERIC;
// Field flags
static final byte IS_INDEXED = 0x1;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosReader.java
index c65c471aed5..41b887e8f46 100755
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosReader.java
@@ -120,6 +120,8 @@ final class Lucene46FieldInfosReader extends FieldInfosReader {
return DocValuesType.SORTED;
} else if (b == 4) {
return DocValuesType.SORTED_SET;
+ } else if (b == 5) {
+ return DocValuesType.SORTED_NUMERIC;
} else {
throw new CorruptIndexException("invalid docvalues byte: " + b + " (resource=" + input + ")");
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosWriter.java
index 5aed57b5f54..1aca1fe9208 100755
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene46/Lucene46FieldInfosWriter.java
@@ -103,6 +103,8 @@ final class Lucene46FieldInfosWriter extends FieldInfosWriter {
return 3;
} else if (type == DocValuesType.SORTED_SET) {
return 4;
+ } else if (type == DocValuesType.SORTED_NUMERIC) {
+ return 5;
} else {
throw new AssertionError();
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesConsumer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesConsumer.java
index 329676b87d7..cfe0b1a9310 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesConsumer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesConsumer.java
@@ -22,7 +22,6 @@ import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.DocValuesConsumer;
@@ -44,7 +43,6 @@ public class Lucene49DocValuesConsumer extends DocValuesConsumer implements Clos
static final int BLOCK_SIZE = 16384;
static final int ADDRESS_INTERVAL = 16;
- static final Number MISSING_ORD = Long.valueOf(-1);
/** Compressed using packed blocks of ints. */
public static final int DELTA_COMPRESSED = 0;
@@ -64,10 +62,10 @@ public class Lucene49DocValuesConsumer extends DocValuesConsumer implements Clos
/** Standard storage for sorted set values with 1 level of indirection:
* docId -> address -> ord. */
- public static final int SORTED_SET_WITH_ADDRESSES = 0;
+ public static final int SORTED_WITH_ADDRESSES = 0;
/** Single-valued sorted set values, encoded as sorted values, so no level
* of indirection: docId -> ord. */
- public static final int SORTED_SET_SINGLE_VALUED_SORTED = 1;
+ public static final int SORTED_SINGLE_VALUED = 1;
IndexOutput data, meta;
final int maxDoc;
@@ -366,13 +364,21 @@ public class Lucene49DocValuesConsumer extends DocValuesConsumer implements Clos
addNumericField(field, docToOrd, false);
}
- private static boolean isSingleValued(Iterable<Number> docToOrdCount) {
- for (Number ordCount : docToOrdCount) {
- if (ordCount.longValue() > 1) {
- return false;
- }
+ @Override
+ public void addSortedNumericField(FieldInfo field, final Iterable<Number> docToValueCount, final Iterable<Number> values) throws IOException {
+ meta.writeVInt(field.number);
+ meta.writeByte(Lucene49DocValuesFormat.SORTED_NUMERIC);
+ if (isSingleValued(docToValueCount)) {
+ meta.writeVInt(SORTED_SINGLE_VALUED);
+ // The field is single-valued, we can encode it as NUMERIC
+ addNumericField(field, singletonView(docToValueCount, values, null));
+ } else {
+ meta.writeVInt(SORTED_WITH_ADDRESSES);
+ // write the stream of values as a numeric field
+ addNumericField(field, values, true);
+ // write the doc -> ord count as a absolute index to the stream
+ addAddresses(field, docToValueCount);
}
- return true;
}
@Override
@@ -381,55 +387,26 @@ public class Lucene49DocValuesConsumer extends DocValuesConsumer implements Clos
meta.writeByte(Lucene49DocValuesFormat.SORTED_SET);
if (isSingleValued(docToOrdCount)) {
- meta.writeVInt(SORTED_SET_SINGLE_VALUED_SORTED);
+ meta.writeVInt(SORTED_SINGLE_VALUED);
// The field is single-valued, we can encode it as SORTED
- addSortedField(field, values, new Iterable<Number>() {
-
- @Override
- public Iterator<Number> iterator() {
- final Iterator<Number> docToOrdCountIt = docToOrdCount.iterator();
- final Iterator<Number> ordsIt = ords.iterator();
- return new Iterator<Number>() {
+ addSortedField(field, values, singletonView(docToOrdCount, ords, -1L));
+ } else {
+ meta.writeVInt(SORTED_WITH_ADDRESSES);
- @Override
- public boolean hasNext() {
- assert ordsIt.hasNext() ? docToOrdCountIt.hasNext() : true;
- return docToOrdCountIt.hasNext();
- }
+ // write the ord -> byte[] as a binary field
+ addTermsDict(field, values);
- @Override
- public Number next() {
- final Number ordCount = docToOrdCountIt.next();
- if (ordCount.longValue() == 0) {
- return MISSING_ORD;
- } else {
- assert ordCount.longValue() == 1;
- return ordsIt.next();
- }
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
+ // write the stream of ords as a numeric field
+ // NOTE: we could return an iterator that delta-encodes these within a doc
+ addNumericField(field, ords, false);
- };
- }
-
- });
- return;
+ // write the doc -> ord count as a absolute index to the stream
+ addAddresses(field, docToOrdCount);
}
-
- meta.writeVInt(SORTED_SET_WITH_ADDRESSES);
-
- // write the ord -> byte[] as a binary field
- addTermsDict(field, values);
-
- // write the stream of ords as a numeric field
- // NOTE: we could return an iterator that delta-encodes these within a doc
- addNumericField(field, ords, false);
-
- // write the doc -> ord count as a absolute index to the stream
+ }
+
+ // writes addressing information as MONOTONIC_COMPRESSED integer
+ private void addAddresses(FieldInfo field, Iterable<Number> values) throws IOException {
meta.writeVInt(field.number);
meta.writeByte(Lucene49DocValuesFormat.NUMERIC);
meta.writeVInt(MONOTONIC_COMPRESSED);
@@ -442,7 +419,7 @@ public class Lucene49DocValuesConsumer extends DocValuesConsumer implements Clos
final MonotonicBlockPackedWriter writer = new MonotonicBlockPackedWriter(data, BLOCK_SIZE);
long addr = 0;
writer.add(addr);
- for (Number v : docToOrdCount) {
+ for (Number v : values) {
addr += v.longValue();
writer.add(addr);
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesFormat.java
index 9fdbbaf6635..9fc1879d253 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesFormat.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesFormat.java
@@ -35,7 +35,7 @@ import org.apache.lucene.util.packed.MonotonicBlockPackedWriter;
/**
* Lucene 4.9 DocValues format.
* <p>
- * Encodes the four per-document value types (Numeric,Binary,Sorted,SortedSet) with these strategies:
+ * Encodes the five per-document value types (Numeric,Binary,Sorted,SortedSet,SortedNumeric) with these strategies:
* <p>
* {@link DocValuesType#NUMERIC NUMERIC}:
* <ul>
@@ -75,6 +75,12 @@ import org.apache.lucene.util.packed.MonotonicBlockPackedWriter;
* above.
* </ul>
* <p>
+ * {@link DocValuesType#SORTED_NUMERIC SORTED_NUMERIC}:
+ * <ul>
+ * <li>SortedNumeric: a value list and per-document index into this list are written using the numeric
+ * strategies above.
+ * </ul>
+ * <p>
* Files:
* <ol>
* <li><tt>.dvd</tt>: DocValues data</li>
@@ -87,7 +93,7 @@ import org.apache.lucene.util.packed.MonotonicBlockPackedWriter;
* DocValues data (.dvd)</p>
* <p>DocValues metadata (.dvm) --&gt; Header,&lt;Entry&gt;<sup>NumFields</sup>,Footer</p>
* <ul>
- * <li>Entry --&gt; NumericEntry | BinaryEntry | SortedEntry | SortedSetEntry</li>
+ * <li>Entry --&gt; NumericEntry | BinaryEntry | SortedEntry | SortedSetEntry | SortedNumericEntry</li>
* <li>NumericEntry --&gt; GCDNumericEntry | TableNumericEntry | DeltaNumericEntry</li>
* <li>GCDNumericEntry --&gt; NumericHeader,MinValue,GCD,BitsPerValue</li>
* <li>TableNumericEntry --&gt; NumericHeader,TableSize,{@link DataOutput#writeLong Int64}<sup>TableSize</sup>,BitsPerValue</li>
@@ -101,6 +107,7 @@ import org.apache.lucene.util.packed.MonotonicBlockPackedWriter;
* <li>BinaryHeader --&gt; FieldNumber,EntryType,BinaryType,MissingOffset,MinLength,MaxLength,DataOffset</li>
* <li>SortedEntry --&gt; FieldNumber,EntryType,BinaryEntry,NumericEntry</li>
* <li>SortedSetEntry --&gt; EntryType,BinaryEntry,NumericEntry,NumericEntry</li>
+ * <li>SortedNumericEntry --&gt; EntryType,NumericEntry,NumericEntry</li>
* <li>FieldNumber,PackedVersion,MinLength,MaxLength,BlockSize,ValueCount --&gt; {@link DataOutput#writeVInt VInt}</li>
* <li>EntryType,CompressionType --&gt; {@link DataOutput#writeByte Byte}</li>
* <li>Header --&gt; {@link CodecUtil#writeHeader CodecHeader}</li>
@@ -112,6 +119,8 @@ import org.apache.lucene.util.packed.MonotonicBlockPackedWriter;
* and an ordinary NumericEntry for the document-to-ord metadata.</p>
* <p>SortedSet fields have three entries: a BinaryEntry with the value metadata,
* and two NumericEntries for the document-to-ord-index and ordinal list metadata.</p>
+ * <p>SortedNumeric fields have two entries: A NumericEntry with the value metadata,
+ * and a numeric entry with the document-to-value index.</p>
* <p>FieldNumber of -1 indicates the end of metadata.</p>
* <p>EntryType is a 0 (NumericEntry) or 1 (BinaryEntry)</p>
* <p>DataOffset is the pointer to the start of the data in the DocValues data (.dvd)</p>
@@ -182,4 +191,5 @@ public final class Lucene49DocValuesFormat extends DocValuesFormat {
static final byte BINARY = 1;
static final byte SORTED = 2;
static final byte SORTED_SET = 3;
+ static final byte SORTED_NUMERIC = 4;
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesProducer.java
index 43b7c65ccb7..bc455ee42da 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesProducer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesProducer.java
@@ -23,8 +23,8 @@ import static org.apache.lucene.codecs.lucene49.Lucene49DocValuesConsumer.BINARY
import static org.apache.lucene.codecs.lucene49.Lucene49DocValuesConsumer.DELTA_COMPRESSED;
import static org.apache.lucene.codecs.lucene49.Lucene49DocValuesConsumer.GCD_COMPRESSED;
import static org.apache.lucene.codecs.lucene49.Lucene49DocValuesConsumer.MONOTONIC_COMPRESSED;
-import static org.apache.lucene.codecs.lucene49.Lucene49DocValuesConsumer.SORTED_SET_SINGLE_VALUED_SORTED;
-import static org.apache.lucene.codecs.lucene49.Lucene49DocValuesConsumer.SORTED_SET_WITH_ADDRESSES;
+import static org.apache.lucene.codecs.lucene49.Lucene49DocValuesConsumer.SORTED_SINGLE_VALUED;
+import static org.apache.lucene.codecs.lucene49.Lucene49DocValuesConsumer.SORTED_WITH_ADDRESSES;
import static org.apache.lucene.codecs.lucene49.Lucene49DocValuesConsumer.TABLE_COMPRESSED;
import java.io.Closeable; // javadocs
@@ -47,6 +47,7 @@ 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.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.index.TermsEnum.SeekStatus;
@@ -66,6 +67,7 @@ public class Lucene49DocValuesProducer extends DocValuesProducer implements Clos
private final Map<Integer,NumericEntry> numerics;
private final Map<Integer,BinaryEntry> binaries;
private final Map<Integer,SortedSetEntry> sortedSets;
+ private final Map<Integer,SortedSetEntry> sortedNumerics;
private final Map<Integer,NumericEntry> ords;
private final Map<Integer,NumericEntry> ordIndexes;
private final AtomicLong ramBytesUsed;
@@ -93,6 +95,7 @@ public class Lucene49DocValuesProducer extends DocValuesProducer implements Clos
ordIndexes = new HashMap<>();
binaries = new HashMap<>();
sortedSets = new HashMap<>();
+ sortedNumerics = new HashMap<>();
readFields(in, state.fieldInfos);
CodecUtil.checkFooter(in);
@@ -196,9 +199,9 @@ public class Lucene49DocValuesProducer extends DocValuesProducer implements Clos
} else if (type == Lucene49DocValuesFormat.SORTED_SET) {
SortedSetEntry ss = readSortedSetEntry(meta);
sortedSets.put(fieldNumber, ss);
- if (ss.format == SORTED_SET_WITH_ADDRESSES) {
+ if (ss.format == SORTED_WITH_ADDRESSES) {
readSortedSetFieldWithAddresses(fieldNumber, meta, infos);
- } else if (ss.format == SORTED_SET_SINGLE_VALUED_SORTED) {
+ } else if (ss.format == SORTED_SINGLE_VALUED) {
if (meta.readVInt() != fieldNumber) {
throw new CorruptIndexException("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
@@ -209,6 +212,28 @@ public class Lucene49DocValuesProducer extends DocValuesProducer implements Clos
} else {
throw new AssertionError();
}
+ } else if (type == Lucene49DocValuesFormat.SORTED_NUMERIC) {
+ SortedSetEntry ss = readSortedSetEntry(meta);
+ sortedNumerics.put(fieldNumber, ss);
+ if (meta.readVInt() != fieldNumber) {
+ throw new CorruptIndexException("sortednumeric entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
+ }
+ if (meta.readByte() != Lucene49DocValuesFormat.NUMERIC) {
+ throw new CorruptIndexException("sortednumeric entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
+ }
+ numerics.put(fieldNumber, readNumericEntry(meta));
+ if (ss.format == SORTED_WITH_ADDRESSES) {
+ if (meta.readVInt() != fieldNumber) {
+ throw new CorruptIndexException("sortednumeric entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
+ }
+ if (meta.readByte() != Lucene49DocValuesFormat.NUMERIC) {
+ throw new CorruptIndexException("sortednumeric entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
+ }
+ NumericEntry ordIndex = readNumericEntry(meta);
+ ordIndexes.put(fieldNumber, ordIndex);
+ } else if (ss.format != SORTED_SINGLE_VALUED) {
+ throw new AssertionError();
+ }
} else {
throw new CorruptIndexException("invalid type: " + type + ", resource=" + meta);
}
@@ -285,7 +310,7 @@ public class Lucene49DocValuesProducer extends DocValuesProducer implements Clos
SortedSetEntry readSortedSetEntry(IndexInput meta) throws IOException {
SortedSetEntry entry = new SortedSetEntry();
entry.format = meta.readVInt();
- if (entry.format != SORTED_SET_SINGLE_VALUED_SORTED && entry.format != SORTED_SET_WITH_ADDRESSES) {
+ if (entry.format != SORTED_SINGLE_VALUED && entry.format != SORTED_WITH_ADDRESSES) {
throw new CorruptIndexException("Unknown format: " + entry.format + ", input=" + meta);
}
return entry;
@@ -309,7 +334,6 @@ public class Lucene49DocValuesProducer extends DocValuesProducer implements Clos
LongValues getNumeric(NumericEntry entry) throws IOException {
RandomAccessInput slice = this.data.randomAccessSlice(entry.offset, entry.endOffset - entry.offset);
-
switch (entry.format) {
case DELTA_COMPRESSED:
final long delta = entry.minValue;
@@ -519,14 +543,51 @@ public class Lucene49DocValuesProducer extends DocValuesProducer implements Clos
}
return ordIndex;
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ SortedSetEntry ss = sortedNumerics.get(field.number);
+ NumericEntry numericEntry = numerics.get(field.number);
+ final LongValues values = getNumeric(numericEntry);
+ if (ss.format == SORTED_SINGLE_VALUED) {
+ final Bits docsWithField = getMissingBits(numericEntry.missingOffset);
+ return DocValues.singleton(values, docsWithField);
+ } else if (ss.format == SORTED_WITH_ADDRESSES) {
+ final IndexInput data = this.data.clone();
+ final MonotonicBlockPackedReader ordIndex = getOrdIndexInstance(data, field, ordIndexes.get(field.number));
+
+ return new SortedNumericDocValues() {
+ long startOffset;
+ long endOffset;
+
+ @Override
+ public void setDocument(int doc) {
+ startOffset = ordIndex.get(doc);
+ endOffset = ordIndex.get(doc+1L);
+ }
+
+ @Override
+ public long valueAt(int index) {
+ return values.get(startOffset + index);
+ }
+
+ @Override
+ public int count() {
+ return (int) (endOffset - startOffset);
+ }
+ };
+ } else {
+ throw new AssertionError();
+ }
+ }
@Override
public SortedSetDocValues getSortedSet(FieldInfo field) throws IOException {
SortedSetEntry ss = sortedSets.get(field.number);
- if (ss.format == SORTED_SET_SINGLE_VALUED_SORTED) {
+ if (ss.format == SORTED_SINGLE_VALUED) {
final SortedDocValues values = getSorted(field);
return DocValues.singleton(values);
- } else if (ss.format != SORTED_SET_WITH_ADDRESSES) {
+ } else if (ss.format != SORTED_WITH_ADDRESSES) {
throw new AssertionError();
}
@@ -629,6 +690,8 @@ public class Lucene49DocValuesProducer extends DocValuesProducer implements Clos
switch(field.getDocValuesType()) {
case SORTED_SET:
return DocValues.docsWithValue(getSortedSet(field), maxDoc);
+ case SORTED_NUMERIC:
+ return DocValues.docsWithValue(getSortedNumeric(field), maxDoc);
case SORTED:
return DocValues.docsWithValue(getSorted(field), maxDoc);
case BINARY:
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49NormsConsumer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49NormsConsumer.java
index fc81b3c3205..1e0d6c6782d 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49NormsConsumer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49NormsConsumer.java
@@ -205,4 +205,9 @@ class Lucene49NormsConsumer extends DocValuesConsumer {
public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, final Iterable<Number> docToOrdCount, final Iterable<Number> ords) throws IOException {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ throw new UnsupportedOperationException();
+ }
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49NormsProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49NormsProducer.java
index b3b4781bed6..4c5d9a411a0 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49NormsProducer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49NormsProducer.java
@@ -32,6 +32,7 @@ import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.store.ChecksumIndexInput;
import org.apache.lucene.store.IndexInput;
@@ -216,6 +217,11 @@ class Lucene49NormsProducer extends DocValuesProducer {
throw new IllegalStateException();
}
+ @Override
+ public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ throw new IllegalStateException();
+ }
+
@Override
public Bits getDocsWithField(FieldInfo field) throws IOException {
throw new IllegalStateException();
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/package.html b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/package.html
index bbf7101ff9a..f2d104e0e65 100755
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/package.html
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/package.html
@@ -386,6 +386,9 @@ allow updating NumericDocValues fields.</li>
<li>In version 4.8, checksum footers were added to the end of each index file
for improved data integrity. Specifically, the last 8 bytes of every index file
contain the zlib-crc32 checksum of the file.</li>
+<li>In version 4.9, DocValues has a new multi-valued numeric type (SortedNumeric)
+that is suitable for faceting/sorting/analytics.
+</li>
</ul>
<a name="Limitations" id="Limitations"></a>
<h2>Limitations</h2>
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldDocValuesFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldDocValuesFormat.java
index 4461ae54d40..60a6211abd7 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldDocValuesFormat.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/perfield/PerFieldDocValuesFormat.java
@@ -35,6 +35,7 @@ import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
@@ -116,6 +117,11 @@ public abstract class PerFieldDocValuesFormat extends DocValuesFormat {
getInstance(field).addSortedField(field, values, docToOrd);
}
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ getInstance(field).addSortedNumericField(field, docToValueCount, values);
+ }
+
@Override
public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrdCount, Iterable<Number> ords) throws IOException {
getInstance(field).addSortedSetField(field, values, docToOrdCount, ords);
@@ -279,6 +285,12 @@ public abstract class PerFieldDocValuesFormat extends DocValuesFormat {
return producer == null ? null : producer.getSorted(field);
}
+ @Override
+ public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ DocValuesProducer producer = fields.get(field.name);
+ return producer == null ? null : producer.getSortedNumeric(field);
+ }
+
@Override
public SortedSetDocValues getSortedSet(FieldInfo field) throws IOException {
DocValuesProducer producer = fields.get(field.name);
diff --git a/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesField.java
new file mode 100644
index 00000000000..5af1aca8ba2
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesField.java
@@ -0,0 +1,67 @@
+package org.apache.lucene.document;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.util.NumericUtils;
+
+/**
+ * <p>
+ * Field that stores a per-document <code>long</code> values for scoring,
+ * sorting or value retrieval. Here's an example usage:
+ *
+ * <pre class="prettyprint">
+ * document.add(new SortedNumericDocValuesField(name, 5L));
+ * document.add(new SortedNumericDocValuesField(name, 14L));
+ * </pre>
+ *
+ * <p>
+ * Note that if you want to encode doubles or floats with proper sort order,
+ * you will need to encode them with {@link NumericUtils}:
+ *
+ * <pre class="prettyprint">
+ * document.add(new SortedNumericDocValuesField(name, NumericUtils.floatToSortableInt(-5.3f)));
+ * </pre>
+ *
+ * <p>
+ * If you also need to store the value, you should add a
+ * separate {@link StoredField} instance.
+ * */
+
+public class SortedNumericDocValuesField extends Field {
+
+ /**
+ * Type for sorted numeric DocValues.
+ */
+ public static final FieldType TYPE = new FieldType();
+ static {
+ TYPE.setDocValueType(FieldInfo.DocValuesType.SORTED_NUMERIC);
+ TYPE.freeze();
+ }
+
+ /**
+ * Creates a new DocValues field with the specified 64-bit long value
+ * @param name field name
+ * @param value 64-bit long value
+ * @throws IllegalArgumentException if the field name is null
+ */
+ public SortedNumericDocValuesField(String name, long value) {
+ super(name, TYPE);
+ fieldsData = Long.valueOf(value);
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/index/AtomicReader.java b/lucene/core/src/java/org/apache/lucene/index/AtomicReader.java
index a3fa7268046..3f622516a36 100644
--- a/lucene/core/src/java/org/apache/lucene/index/AtomicReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/AtomicReader.java
@@ -275,6 +275,12 @@ public abstract class AtomicReader extends IndexReader {
* this field. The returned instance should only be
* used by a single thread. */
public abstract SortedDocValues getSortedDocValues(String field) throws IOException;
+
+ /** Returns {@link SortedNumericDocValues} for this field, or
+ * null if no {@link SortedNumericDocValues} were indexed for
+ * this field. The returned instance should only be
+ * used by a single thread. */
+ public abstract SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException;
/** Returns {@link SortedSetDocValues} for this field, or
* null if no {@link SortedSetDocValues} were indexed for
diff --git a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
index 8f5dd472c69..4c22e58900b 100644
--- a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
+++ b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
@@ -30,7 +30,6 @@ import java.util.Map;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.blocktree.BlockTreeTermsReader;
import org.apache.lucene.codecs.blocktree.FieldReader;
import org.apache.lucene.codecs.blocktree.Stats;
import org.apache.lucene.index.CheckIndex.Status.DocValuesStatus;
@@ -299,6 +298,9 @@ public class CheckIndex {
/** Total number of sorted fields */
public long totalSortedFields;
+ /** Total number of sortednumeric fields */
+ public long totalSortedNumericFields;
+
/** Total number of sortedset fields */
public long totalSortedSetFields;
@@ -1380,6 +1382,7 @@ public class CheckIndex {
+ status.totalBinaryFields + " BINARY; "
+ status.totalNumericFields + " NUMERIC; "
+ status.totalSortedFields + " SORTED; "
+ + status.totalSortedNumericFields + " SORTED_NUMERIC; "
+ status.totalSortedSetFields + " SORTED_SET]");
} catch (Throwable e) {
msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");
@@ -1510,6 +1513,30 @@ public class CheckIndex {
lastValue = BytesRef.deepCopyOf(term);
}
}
+
+ private static void checkSortedNumericDocValues(String fieldName, AtomicReader reader, SortedNumericDocValues ndv, Bits docsWithField) {
+ for (int i = 0; i < reader.maxDoc(); i++) {
+ ndv.setDocument(i);
+ int count = ndv.count();
+ if (docsWithField.get(i)) {
+ if (count == 0) {
+ throw new RuntimeException("dv for field: " + fieldName + " is not marked missing but has zero count for doc: " + i);
+ }
+ long previous = Long.MIN_VALUE;
+ for (int j = 0; j < count; j++) {
+ long value = ndv.valueAt(j);
+ if (value < previous) {
+ throw new RuntimeException("values out of order: " + value + " < " + previous + " for doc: " + i);
+ }
+ previous = value;
+ }
+ } else {
+ if (count != 0) {
+ throw new RuntimeException("dv for field: " + fieldName + " is marked missing but has count=" + count + " for doc: " + i);
+ }
+ }
+ }
+ }
private static void checkNumericDocValues(String fieldName, AtomicReader reader, NumericDocValues ndv, Bits docsWithField) {
for (int i = 0; i < reader.maxDoc(); i++) {
@@ -1533,15 +1560,27 @@ public class CheckIndex {
checkSortedDocValues(fi.name, reader, reader.getSortedDocValues(fi.name), docsWithField);
if (reader.getBinaryDocValues(fi.name) != null ||
reader.getNumericDocValues(fi.name) != null ||
+ reader.getSortedNumericDocValues(fi.name) != null ||
reader.getSortedSetDocValues(fi.name) != null) {
throw new RuntimeException(fi.name + " returns multiple docvalues types!");
}
break;
+ case SORTED_NUMERIC:
+ status.totalSortedNumericFields++;
+ checkSortedNumericDocValues(fi.name, reader, reader.getSortedNumericDocValues(fi.name), docsWithField);
+ if (reader.getBinaryDocValues(fi.name) != null ||
+ reader.getNumericDocValues(fi.name) != null ||
+ reader.getSortedSetDocValues(fi.name) != null ||
+ reader.getSortedDocValues(fi.name) != null) {
+ throw new RuntimeException(fi.name + " returns multiple docvalues types!");
+ }
+ break;
case SORTED_SET:
status.totalSortedSetFields++;
checkSortedSetDocValues(fi.name, reader, reader.getSortedSetDocValues(fi.name), docsWithField);
if (reader.getBinaryDocValues(fi.name) != null ||
reader.getNumericDocValues(fi.name) != null ||
+ reader.getSortedNumericDocValues(fi.name) != null ||
reader.getSortedDocValues(fi.name) != null) {
throw new RuntimeException(fi.name + " returns multiple docvalues types!");
}
@@ -1551,6 +1590,7 @@ public class CheckIndex {
checkBinaryDocValues(fi.name, reader, reader.getBinaryDocValues(fi.name), docsWithField);
if (reader.getNumericDocValues(fi.name) != null ||
reader.getSortedDocValues(fi.name) != null ||
+ reader.getSortedNumericDocValues(fi.name) != null ||
reader.getSortedSetDocValues(fi.name) != null) {
throw new RuntimeException(fi.name + " returns multiple docvalues types!");
}
@@ -1560,6 +1600,7 @@ public class CheckIndex {
checkNumericDocValues(fi.name, reader, reader.getNumericDocValues(fi.name), docsWithField);
if (reader.getBinaryDocValues(fi.name) != null ||
reader.getSortedDocValues(fi.name) != null ||
+ reader.getSortedNumericDocValues(fi.name) != null ||
reader.getSortedSetDocValues(fi.name) != null) {
throw new RuntimeException(fi.name + " returns multiple docvalues types!");
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java b/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java
index 2a2454e5a7c..998d12134f6 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java
@@ -64,9 +64,6 @@ final class DefaultIndexingChain extends DocConsumer {
private int totalFieldCount;
private long nextFieldGen;
- // Lazy init:
- private NumericDocValuesWriter norms;
-
// Holds fields seen in each document
private PerField[] fields = new PerField[1];
@@ -426,6 +423,13 @@ final class DefaultIndexingChain extends DocConsumer {
}
((SortedDocValuesWriter) fp.docValuesWriter).addValue(docID, field.binaryValue());
break;
+
+ case SORTED_NUMERIC:
+ if (fp.docValuesWriter == null) {
+ fp.docValuesWriter = new SortedNumericDocValuesWriter(fp.fieldInfo, bytesUsed);
+ }
+ ((SortedNumericDocValuesWriter) fp.docValuesWriter).addValue(docID, field.numericValue().longValue());
+ break;
case SORTED_SET:
if (fp.docValuesWriter == null) {
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocValues.java b/lucene/core/src/java/org/apache/lucene/index/DocValues.java
index 61acb79e859..90eab2ac9d8 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocValues.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocValues.java
@@ -77,6 +77,26 @@ public final class DocValues {
}
};
}
+
+ /**
+ * An empty SortedNumericDocValues which returns zero values for every document
+ */
+ public static final SortedNumericDocValues emptySortedNumeric() {
+ return new SortedNumericDocValues() {
+ @Override
+ public void setDocument(int doc) {}
+
+ @Override
+ public long valueAt(int index) {
+ throw new IndexOutOfBoundsException();
+ }
+
+ @Override
+ public int count() {
+ return 0;
+ }
+ };
+ }
/**
* An empty SortedDocValues which returns {@link SortedSetDocValues#NO_MORE_ORDS} for every document
@@ -122,7 +142,7 @@ public final class DocValues {
/**
* Returns a single-valued view of the SortedSetDocValues, if it was previously
- * wrapped with {@link #singleton}, or null.
+ * wrapped with {@link #singleton(SortedDocValues)}, or null.
*/
public static SortedDocValues unwrapSingleton(SortedSetDocValues dv) {
if (dv instanceof SingletonSortedSetDocValues) {
@@ -132,6 +152,38 @@ public final class DocValues {
}
}
+ /**
+ * Returns a single-valued view of the SortedNumericDocValues, if it was previously
+ * wrapped with {@link #singleton(NumericDocValues, Bits)}, or null.
+ * @see #unwrapSingletonBits(SortedNumericDocValues)
+ */
+ public static NumericDocValues unwrapSingleton(SortedNumericDocValues dv) {
+ if (dv instanceof SingletonSortedNumericDocValues) {
+ return ((SingletonSortedNumericDocValues)dv).getNumericDocValues();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the documents with a value for the SortedNumericDocValues, if it was previously
+ * wrapped with {@link #singleton(NumericDocValues, Bits)}, or null.
+ */
+ public static Bits unwrapSingletonBits(SortedNumericDocValues dv) {
+ if (dv instanceof SingletonSortedNumericDocValues) {
+ return ((SingletonSortedNumericDocValues)dv).getDocsWithField();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns a multi-valued view over the provided NumericDocValues
+ */
+ public static SortedNumericDocValues singleton(NumericDocValues dv, Bits docsWithField) {
+ return new SingletonSortedNumericDocValues(dv, docsWithField);
+ }
+
/**
* Returns a Bits representing all documents from <code>dv</code> that have a value.
*/
@@ -167,6 +219,24 @@ public final class DocValues {
};
}
+ /**
+ * Returns a Bits representing all documents from <code>dv</code> that have a value.
+ */
+ public static Bits docsWithValue(final SortedNumericDocValues dv, final int maxDoc) {
+ return new Bits() {
+ @Override
+ public boolean get(int index) {
+ dv.setDocument(index);
+ return dv.count() != 0;
+ }
+
+ @Override
+ public int length() {
+ return maxDoc;
+ }
+ };
+ }
+
// some helpers, for transition from fieldcache apis.
// as opposed to the AtomicReader apis (which must be strict for consistency), these are lenient
@@ -208,6 +278,22 @@ public final class DocValues {
}
}
+ /**
+ * Returns SortedNumericDocValues for the reader, or {@link #emptySortedNumeric} if it has none.
+ */
+ public static SortedNumericDocValues getSortedNumeric(AtomicReader in, String field) throws IOException {
+ SortedNumericDocValues dv = in.getSortedNumericDocValues(field);
+ if (dv == null) {
+ NumericDocValues single = in.getNumericDocValues(field);
+ if (single == null) {
+ return emptySortedNumeric();
+ }
+ Bits bits = in.getDocsWithField(field);
+ return singleton(single, bits);
+ }
+ return dv;
+ }
+
/**
* Returns SortedSetDocValues for the reader, or {@link #emptySortedSet} if it has none.
*/
diff --git a/lucene/core/src/java/org/apache/lucene/index/FieldInfo.java b/lucene/core/src/java/org/apache/lucene/index/FieldInfo.java
index 1238fc441c1..e608f752f9f 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FieldInfo.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FieldInfo.java
@@ -105,6 +105,11 @@ public final class FieldInfo {
* ordinal and by-value. Values must be <= 32766 bytes.
*/
SORTED,
+ /**
+ * A pre-sorted Number[]. Fields with this type store numeric values in sorted
+ * order according to {@link Long#compare(long, long)}.
+ */
+ SORTED_NUMERIC,
/**
* A pre-sorted Set&lt;byte[]&gt;. Fields with this type only store distinct byte values
* and store additional offset pointers per document to dereference the shared
diff --git a/lucene/core/src/java/org/apache/lucene/index/FilterAtomicReader.java b/lucene/core/src/java/org/apache/lucene/index/FilterAtomicReader.java
index d7ee68ff336..52f542d2aaa 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FilterAtomicReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FilterAtomicReader.java
@@ -413,6 +413,12 @@ public class FilterAtomicReader extends AtomicReader {
ensureOpen();
return in.getSortedDocValues(field);
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException {
+ ensureOpen();
+ return in.getSortedNumericDocValues(field);
+ }
@Override
public SortedSetDocValues getSortedSetDocValues(String field) throws IOException {
diff --git a/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java b/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java
index 856dde03e5a..9513bae9700 100644
--- a/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java
+++ b/lucene/core/src/java/org/apache/lucene/index/MultiDocValues.java
@@ -228,6 +228,63 @@ public class MultiDocValues {
}
}
+ /** Returns a SortedNumericDocValues for a reader's docvalues (potentially merging on-the-fly)
+ * <p>
+ * This is a slow way to access sorted numeric values. Instead, access them per-segment
+ * with {@link AtomicReader#getSortedNumericDocValues(String)}
+ * </p>
+ * */
+ public static SortedNumericDocValues getSortedNumericValues(final IndexReader r, final String field) throws IOException {
+ final List<AtomicReaderContext> leaves = r.leaves();
+ final int size = leaves.size();
+ if (size == 0) {
+ return null;
+ } else if (size == 1) {
+ return leaves.get(0).reader().getSortedNumericDocValues(field);
+ }
+
+ boolean anyReal = false;
+ final SortedNumericDocValues[] values = new SortedNumericDocValues[size];
+ final int[] starts = new int[size+1];
+ for (int i = 0; i < size; i++) {
+ AtomicReaderContext context = leaves.get(i);
+ SortedNumericDocValues v = context.reader().getSortedNumericDocValues(field);
+ if (v == null) {
+ v = DocValues.emptySortedNumeric();
+ } else {
+ anyReal = true;
+ }
+ values[i] = v;
+ starts[i] = context.docBase;
+ }
+ starts[size] = r.maxDoc();
+
+ if (!anyReal) {
+ return null;
+ } else {
+ return new SortedNumericDocValues() {
+ SortedNumericDocValues current;
+
+ @Override
+ public void setDocument(int doc) {
+ int subIndex = ReaderUtil.subIndex(doc, starts);
+ current = values[subIndex];
+ current.setDocument(doc - starts[subIndex]);
+ }
+
+ @Override
+ public long valueAt(int index) {
+ return current.valueAt(index);
+ }
+
+ @Override
+ public int count() {
+ return current.count();
+ }
+ };
+ }
+ }
+
/** Returns a SortedDocValues for a reader's docvalues (potentially doing extremely slow things).
* <p>
* This is an extremely slow way to access sorted values. Instead, access them per-segment
diff --git a/lucene/core/src/java/org/apache/lucene/index/ParallelAtomicReader.java b/lucene/core/src/java/org/apache/lucene/index/ParallelAtomicReader.java
index 293b3f3585b..56b060219cd 100644
--- a/lucene/core/src/java/org/apache/lucene/index/ParallelAtomicReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/ParallelAtomicReader.java
@@ -287,6 +287,13 @@ public class ParallelAtomicReader extends AtomicReader {
AtomicReader reader = fieldToReader.get(field);
return reader == null ? null : reader.getSortedDocValues(field);
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException {
+ ensureOpen();
+ AtomicReader reader = fieldToReader.get(field);
+ return reader == null ? null : reader.getSortedNumericDocValues(field);
+ }
@Override
public SortedSetDocValues getSortedSetDocValues(String field) throws IOException {
diff --git a/lucene/core/src/java/org/apache/lucene/index/SegmentMerger.java b/lucene/core/src/java/org/apache/lucene/index/SegmentMerger.java
index 465d233bb0b..e96ae64f6c1 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SegmentMerger.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SegmentMerger.java
@@ -209,6 +209,16 @@ final class SegmentMerger {
toMerge.add(values);
}
consumer.mergeSortedSetField(field, mergeState, toMerge);
+ } else if (type == DocValuesType.SORTED_NUMERIC) {
+ List<SortedNumericDocValues> toMerge = new ArrayList<>();
+ for (AtomicReader reader : mergeState.readers) {
+ SortedNumericDocValues values = reader.getSortedNumericDocValues(field.name);
+ if (values == null) {
+ values = DocValues.emptySortedNumeric();
+ }
+ toMerge.add(values);
+ }
+ consumer.mergeSortedNumericField(field, mergeState, toMerge);
} else {
throw new AssertionError("type=" + type);
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java b/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java
index 1a70e7dd558..8ae3ffddad1 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java
@@ -33,7 +33,6 @@ import org.apache.lucene.codecs.FieldInfosFormat;
import org.apache.lucene.codecs.StoredFieldsReader;
import org.apache.lucene.codecs.TermVectorsReader;
import org.apache.lucene.index.FieldInfo.DocValuesType;
-import org.apache.lucene.search.CachingWrapperFilter;
import org.apache.lucene.store.CompoundFileDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
@@ -531,6 +530,27 @@ public final class SegmentReader extends AtomicReader implements Accountable {
return dv;
}
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException {
+ ensureOpen();
+ Map<String,Object> dvFields = docValuesLocal.get();
+
+ Object previous = dvFields.get(field);
+ if (previous != null && previous instanceof SortedNumericDocValues) {
+ return (SortedNumericDocValues) previous;
+ } else {
+ FieldInfo fi = getDVField(field, DocValuesType.SORTED_NUMERIC);
+ if (fi == null) {
+ return null;
+ }
+ DocValuesProducer dvProducer = dvProducersByField.get(field);
+ assert dvProducer != null;
+ SortedNumericDocValues dv = dvProducer.getSortedNumeric(fi);
+ dvFields.put(field, dv);
+ return dv;
+ }
+ }
@Override
public SortedSetDocValues getSortedSetDocValues(String field) throws IOException {
diff --git a/lucene/core/src/java/org/apache/lucene/index/SimpleMergedSegmentWarmer.java b/lucene/core/src/java/org/apache/lucene/index/SimpleMergedSegmentWarmer.java
index 82d3045d51c..378c6841a9d 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SimpleMergedSegmentWarmer.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SimpleMergedSegmentWarmer.java
@@ -65,6 +65,9 @@ public class SimpleMergedSegmentWarmer extends IndexReaderWarmer {
case SORTED:
reader.getSortedDocValues(info.name);
break;
+ case SORTED_NUMERIC:
+ reader.getSortedNumericDocValues(info.name);
+ break;
case SORTED_SET:
reader.getSortedSetDocValues(info.name);
break;
diff --git a/lucene/core/src/java/org/apache/lucene/index/SingletonSortedNumericDocValues.java b/lucene/core/src/java/org/apache/lucene/index/SingletonSortedNumericDocValues.java
new file mode 100644
index 00000000000..b704df8e577
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/index/SingletonSortedNumericDocValues.java
@@ -0,0 +1,69 @@
+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.
+ */
+
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.Bits.MatchAllBits;
+
+/**
+ * Exposes multi-valued view over a single-valued instance.
+ * <p>
+ * This can be used if you want to have one multi-valued implementation
+ * that works for single or multi-valued types.
+ */
+final class SingletonSortedNumericDocValues extends SortedNumericDocValues {
+ private final NumericDocValues in;
+ private final Bits docsWithField;
+ private long value;
+ private int count;
+
+ public SingletonSortedNumericDocValues(NumericDocValues in, Bits docsWithField) {
+ this.in = in;
+ this.docsWithField = docsWithField instanceof MatchAllBits ? null : docsWithField;
+ }
+
+ /** Return the wrapped {@link NumericDocValues} */
+ public NumericDocValues getNumericDocValues() {
+ return in;
+ }
+
+ /** Return the wrapped {@link Bits} */
+ public Bits getDocsWithField() {
+ return docsWithField;
+ }
+
+ @Override
+ public void setDocument(int doc) {
+ value = in.get(doc);
+ if (docsWithField != null && value == 0 && docsWithField.get(doc) == false) {
+ count = 0;
+ } else {
+ count = 1;
+ }
+ }
+
+ @Override
+ public long valueAt(int index) {
+ return value;
+ }
+
+ @Override
+ public int count() {
+ return count;
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/index/SlowCompositeReaderWrapper.java b/lucene/core/src/java/org/apache/lucene/index/SlowCompositeReaderWrapper.java
index 5af4d914afd..ebf0409b29b 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SlowCompositeReaderWrapper.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SlowCompositeReaderWrapper.java
@@ -110,6 +110,12 @@ public final class SlowCompositeReaderWrapper extends AtomicReader {
ensureOpen();
return MultiDocValues.getBinaryValues(in, field);
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException {
+ ensureOpen();
+ return MultiDocValues.getSortedNumericValues(in, field);
+ }
@Override
public SortedDocValues getSortedDocValues(String field) throws IOException {
diff --git a/lucene/core/src/java/org/apache/lucene/index/SortedNumericDocValues.java b/lucene/core/src/java/org/apache/lucene/index/SortedNumericDocValues.java
new file mode 100644
index 00000000000..da631fe7311
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/index/SortedNumericDocValues.java
@@ -0,0 +1,46 @@
+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.
+ */
+
+/**
+ * A list of per-document numeric values, sorted
+ * according to {@link Long#compare(long, long)}.
+ */
+public abstract class SortedNumericDocValues {
+
+ /** Sole constructor. (For invocation by subclass
+ * constructors, typically implicit.) */
+ protected SortedNumericDocValues() {}
+
+ /**
+ * Positions to the specified document
+ */
+ public abstract void setDocument(int doc);
+
+ /**
+ * Retrieve the value for the current document at the specified index.
+ * An index ranges from {@code 0} to {@code count()-1}.
+ */
+ public abstract long valueAt(int index);
+
+ /**
+ * Retrieves the count of values for the current document.
+ * This may be zero if a document has no values.
+ */
+ public abstract int count();
+}
diff --git a/lucene/core/src/java/org/apache/lucene/index/SortedNumericDocValuesWriter.java b/lucene/core/src/java/org/apache/lucene/index/SortedNumericDocValuesWriter.java
new file mode 100644
index 00000000000..4f41933b8fc
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/index/SortedNumericDocValuesWriter.java
@@ -0,0 +1,171 @@
+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.
+ */
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+import org.apache.lucene.codecs.DocValuesConsumer;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.Counter;
+import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.packed.AppendingDeltaPackedLongBuffer;
+import org.apache.lucene.util.packed.PackedInts;
+
+/** Buffers up pending long[] per doc, sorts, then flushes when segment flushes. */
+class SortedNumericDocValuesWriter extends DocValuesWriter {
+ private AppendingDeltaPackedLongBuffer pending; // stream of all values
+ private AppendingDeltaPackedLongBuffer pendingCounts; // count of values per doc
+ private final Counter iwBytesUsed;
+ private long bytesUsed; // this only tracks differences in 'pending' and 'pendingCounts'
+ private final FieldInfo fieldInfo;
+ private int currentDoc;
+ private long currentValues[] = new long[8];
+ private int currentUpto = 0;
+
+ public SortedNumericDocValuesWriter(FieldInfo fieldInfo, Counter iwBytesUsed) {
+ this.fieldInfo = fieldInfo;
+ this.iwBytesUsed = iwBytesUsed;
+ pending = new AppendingDeltaPackedLongBuffer(PackedInts.COMPACT);
+ pendingCounts = new AppendingDeltaPackedLongBuffer(PackedInts.COMPACT);
+ bytesUsed = pending.ramBytesUsed() + pendingCounts.ramBytesUsed();
+ iwBytesUsed.addAndGet(bytesUsed);
+ }
+
+ public void addValue(int docID, long value) {
+ if (docID != currentDoc) {
+ finishCurrentDoc();
+ }
+
+ // Fill in any holes:
+ while(currentDoc < docID) {
+ pendingCounts.add(0); // no values
+ currentDoc++;
+ }
+
+ addOneValue(value);
+ updateBytesUsed();
+ }
+
+ // finalize currentDoc: this sorts the values in the current doc
+ private void finishCurrentDoc() {
+ Arrays.sort(currentValues, 0, currentUpto);
+ for (int i = 0; i < currentUpto; i++) {
+ pending.add(currentValues[i]);
+ }
+ // record the number of values for this doc
+ pendingCounts.add(currentUpto);
+ currentUpto = 0;
+ currentDoc++;
+ }
+
+ @Override
+ public void finish(int maxDoc) {
+ finishCurrentDoc();
+
+ // fill in any holes
+ for (int i = currentDoc; i < maxDoc; i++) {
+ pendingCounts.add(0); // no values
+ }
+ }
+
+ private void addOneValue(long value) {
+ if (currentUpto == currentValues.length) {
+ currentValues = ArrayUtil.grow(currentValues, currentValues.length+1);
+ }
+
+ currentValues[currentUpto] = value;
+ currentUpto++;
+ }
+
+ private void updateBytesUsed() {
+ final long newBytesUsed = pending.ramBytesUsed() + pendingCounts.ramBytesUsed() + RamUsageEstimator.sizeOf(currentValues);
+ iwBytesUsed.addAndGet(newBytesUsed - bytesUsed);
+ bytesUsed = newBytesUsed;
+ }
+
+ @Override
+ public void flush(SegmentWriteState state, DocValuesConsumer dvConsumer) throws IOException {
+ final int maxDoc = state.segmentInfo.getDocCount();
+ assert pendingCounts.size() == maxDoc;
+
+ dvConsumer.addSortedNumericField(fieldInfo,
+ // doc -> valueCount
+ new Iterable<Number>() {
+ @Override
+ public Iterator<Number> iterator() {
+ return new CountIterator();
+ }
+ },
+
+ // values
+ new Iterable<Number>() {
+ @Override
+ public Iterator<Number> iterator() {
+ return new ValuesIterator();
+ }
+ });
+ }
+
+ // iterates over the values for each doc we have in ram
+ private class ValuesIterator implements Iterator<Number> {
+ final AppendingDeltaPackedLongBuffer.Iterator iter = pending.iterator();
+
+ @Override
+ public boolean hasNext() {
+ return iter.hasNext();
+ }
+
+ @Override
+ public Number next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ return iter.next();
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private class CountIterator implements Iterator<Number> {
+ final AppendingDeltaPackedLongBuffer.Iterator iter = pendingCounts.iterator();
+
+ @Override
+ public boolean hasNext() {
+ return iter.hasNext();
+ }
+
+ @Override
+ public Number next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ return iter.next();
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java b/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java
index 109efb03d69..be78576b66b 100644
--- a/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java
@@ -226,6 +226,7 @@ public abstract class FieldComparator<T> {
protected final T missingValue;
protected final String field;
protected Bits docsWithField;
+ protected NumericDocValues currentReaderValues;
public NumericComparator(String field, T missingValue) {
this.field = field;
@@ -234,6 +235,7 @@ public abstract class FieldComparator<T> {
@Override
public FieldComparator<T> setNextReader(AtomicReaderContext context) throws IOException {
+ currentReaderValues = getNumericDocValues(context, field);
if (missingValue != null) {
docsWithField = DocValues.getDocsWithField(context.reader(), field);
// optimization to remove unneeded checks on the bit interface:
@@ -245,13 +247,17 @@ public abstract class FieldComparator<T> {
}
return this;
}
+
+ /** Retrieves the NumericDocValues for the field in this segment */
+ protected NumericDocValues getNumericDocValues(AtomicReaderContext context, String field) throws IOException {
+ return DocValues.getNumeric(context.reader(), field);
+ }
}
/** Parses field's values as double (using {@link
* AtomicReader#getNumericDocValues} and sorts by ascending value */
- public static final class DoubleComparator extends NumericComparator<Double> {
+ public static class DoubleComparator extends NumericComparator<Double> {
private final double[] values;
- private NumericDocValues currentReaderValues;
private double bottom;
private double topValue;
@@ -288,12 +294,6 @@ public abstract class FieldComparator<T> {
values[slot] = v2;
}
-
- @Override
- public FieldComparator<Double> setNextReader(AtomicReaderContext context) throws IOException {
- currentReaderValues = DocValues.getNumeric(context.reader(), field);
- return super.setNextReader(context);
- }
@Override
public void setBottom(final int bottom) {
@@ -324,9 +324,8 @@ public abstract class FieldComparator<T> {
/** Parses field's values as float (using {@link
* AtomicReader#getNumericDocValues(String)} and sorts by ascending value */
- public static final class FloatComparator extends NumericComparator<Float> {
+ public static class FloatComparator extends NumericComparator<Float> {
private final float[] values;
- private NumericDocValues currentReaderValues;
private float bottom;
private float topValue;
@@ -364,12 +363,6 @@ public abstract class FieldComparator<T> {
values[slot] = v2;
}
-
- @Override
- public FieldComparator<Float> setNextReader(AtomicReaderContext context) throws IOException {
- currentReaderValues = DocValues.getNumeric(context.reader(), field);
- return super.setNextReader(context);
- }
@Override
public void setBottom(final int bottom) {
@@ -400,9 +393,8 @@ public abstract class FieldComparator<T> {
/** Parses field's values as int (using {@link
* AtomicReader#getNumericDocValues(String)} and sorts by ascending value */
- public static final class IntComparator extends NumericComparator<Integer> {
+ public static class IntComparator extends NumericComparator<Integer> {
private final int[] values;
- private NumericDocValues currentReaderValues;
private int bottom; // Value of bottom of queue
private int topValue;
@@ -439,12 +431,6 @@ public abstract class FieldComparator<T> {
values[slot] = v2;
}
-
- @Override
- public FieldComparator<Integer> setNextReader(AtomicReaderContext context) throws IOException {
- currentReaderValues = DocValues.getNumeric(context.reader(), field);
- return super.setNextReader(context);
- }
@Override
public void setBottom(final int bottom) {
@@ -475,9 +461,8 @@ public abstract class FieldComparator<T> {
/** Parses field's values as long (using {@link
* AtomicReader#getNumericDocValues(String)} and sorts by ascending value */
- public static final class LongComparator extends NumericComparator<Long> {
+ public static class LongComparator extends NumericComparator<Long> {
private final long[] values;
- private NumericDocValues currentReaderValues;
private long bottom;
private long topValue;
@@ -516,12 +501,6 @@ public abstract class FieldComparator<T> {
values[slot] = v2;
}
-
- @Override
- public FieldComparator<Long> setNextReader(AtomicReaderContext context) throws IOException {
- currentReaderValues = DocValues.getNumeric(context.reader(), field);
- return super.setNextReader(context);
- }
@Override
public void setBottom(final int bottom) {
diff --git a/lucene/core/src/java/org/apache/lucene/search/SortedNumericSelector.java b/lucene/core/src/java/org/apache/lucene/search/SortedNumericSelector.java
new file mode 100644
index 00000000000..e3f275ac4ac
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/SortedNumericSelector.java
@@ -0,0 +1,137 @@
+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.NumericDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
+import org.apache.lucene.util.NumericUtils;
+
+/**
+ * Selects a value from the document's list to use as the representative value
+ * <p>
+ * This provides a NumericDocValues view over the SortedNumeric, for use with sorting,
+ * expressions, function queries, etc.
+ */
+public class SortedNumericSelector {
+
+ /**
+ * Type of selection to perform.
+ */
+ public enum Type {
+ /**
+ * Selects the minimum value in the set
+ */
+ MIN,
+ /**
+ * Selects the maximum value in the set
+ */
+ MAX,
+ // TODO: we could do MEDIAN in constant time (at most 2 lookups)
+ }
+
+ /**
+ * Wraps a multi-valued SortedNumericDocValues as a single-valued view, using the specified selector
+ * and numericType.
+ */
+ public static NumericDocValues wrap(SortedNumericDocValues sortedNumeric, Type selector, SortField.Type numericType) {
+ if (numericType != SortField.Type.INT &&
+ numericType != SortField.Type.LONG &&
+ numericType != SortField.Type.FLOAT &&
+ numericType != SortField.Type.DOUBLE) {
+ throw new IllegalArgumentException("numericType must be a numeric type");
+ }
+ final NumericDocValues view;
+ NumericDocValues singleton = DocValues.unwrapSingleton(sortedNumeric);
+ 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!
+ view = singleton;
+ } else {
+ switch(selector) {
+ case MIN:
+ view = new MinValue(sortedNumeric);
+ break;
+ case MAX:
+ view = new MaxValue(sortedNumeric);
+ break;
+ default:
+ throw new AssertionError();
+ }
+ }
+ // undo the numericutils sortability
+ switch(numericType) {
+ case FLOAT:
+ return new NumericDocValues() {
+ @Override
+ public long get(int docID) {
+ return NumericUtils.sortableFloatBits((int) view.get(docID));
+ }
+ };
+ case DOUBLE:
+ return new NumericDocValues() {
+ @Override
+ public long get(int docID) {
+ return NumericUtils.sortableDoubleBits(view.get(docID));
+ }
+ };
+ default:
+ return view;
+ }
+ }
+
+ /** Wraps a SortedNumericDocValues and returns the first value (min) */
+ static class MinValue extends NumericDocValues {
+ final SortedNumericDocValues in;
+
+ MinValue(SortedNumericDocValues in) {
+ this.in = in;
+ }
+
+ @Override
+ public long get(int docID) {
+ in.setDocument(docID);
+ if (in.count() == 0) {
+ return 0; // missing
+ } else {
+ return in.valueAt(0);
+ }
+ }
+ }
+
+ /** Wraps a SortedNumericDocValues and returns the last value (max) */
+ static class MaxValue extends NumericDocValues {
+ final SortedNumericDocValues in;
+
+ MaxValue(SortedNumericDocValues in) {
+ this.in = in;
+ }
+
+ @Override
+ public long get(int docID) {
+ in.setDocument(docID);
+ final int count = in.count();
+ if (count == 0) {
+ return 0; // missing
+ } else {
+ return in.valueAt(count-1);
+ }
+ }
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/search/SortedNumericSortField.java b/lucene/core/src/java/org/apache/lucene/search/SortedNumericSortField.java
new file mode 100644
index 00000000000..f948463bcb8
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/SortedNumericSortField.java
@@ -0,0 +1,171 @@
+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.NumericDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
+import org.apache.lucene.search.FieldComparator;
+import org.apache.lucene.search.SortField;
+
+/**
+ * SortField for {@link SortedNumericDocValues}.
+ * <p>
+ * A SortedNumericDocValues 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 list is selected as the sort value, but
+ * this can be customized.
+ * <p>
+ * Like sorting by string, this also supports sorting missing values as first or last,
+ * via {@link #setMissingValue(Object)}.
+ * <p>
+ * @see SortedNumericSelector
+ */
+public class SortedNumericSortField extends SortField {
+
+ private final SortedNumericSelector.Type selector;
+ private final SortField.Type type;
+
+ /**
+ * Creates a sort, by the minimum value in the set
+ * for the document.
+ * @param field Name of field to sort by. Must not be null.
+ * @param type Type of values
+ */
+ public SortedNumericSortField(String field, SortField.Type type) {
+ this(field, type, false);
+ }
+
+ /**
+ * 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 type Type of values
+ * @param reverse True if natural order should be reversed.
+ */
+ public SortedNumericSortField(String field, SortField.Type type, boolean reverse) {
+ this(field, type, reverse, SortedNumericSelector.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 type Type of values
+ * @param reverse True if natural order should be reversed.
+ * @param selector custom selector type for choosing the sort value from the set.
+ */
+ public SortedNumericSortField(String field, SortField.Type type, boolean reverse, SortedNumericSelector.Type selector) {
+ super(field, SortField.Type.CUSTOM, reverse);
+ if (selector == null) {
+ throw new NullPointerException();
+ }
+ if (type == null) {
+ throw new NullPointerException();
+ }
+ this.selector = selector;
+ this.type = type;
+ }
+
+ /** Returns the selector in use for this sort */
+ public SortedNumericSelector.Type getSelector() {
+ return selector;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = super.hashCode();
+ result = prime * result + selector.hashCode();
+ result = prime * result + type.hashCode();
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) return true;
+ if (!super.equals(obj)) return false;
+ if (getClass() != obj.getClass()) return false;
+ SortedNumericSortField other = (SortedNumericSortField) obj;
+ if (selector != other.selector) return false;
+ if (type != other.type) return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("<sortednumeric" + ": \"").append(getField()).append("\">");
+ if (getReverse()) buffer.append('!');
+ if (missingValue != null) {
+ buffer.append(" missingValue=");
+ buffer.append(missingValue);
+ }
+ buffer.append(" selector=");
+ buffer.append(selector);
+ buffer.append(" type=");
+ buffer.append(type);
+
+ return buffer.toString();
+ }
+
+ @Override
+ public void setMissingValue(Object missingValue) {
+ this.missingValue = missingValue;
+ }
+
+ @Override
+ public FieldComparator<?> getComparator(int numHits, int sortPos) throws IOException {
+ switch(type) {
+ case INT:
+ return new FieldComparator.IntComparator(numHits, getField(), (Integer) missingValue) {
+ @Override
+ protected NumericDocValues getNumericDocValues(AtomicReaderContext context, String field) throws IOException {
+ return SortedNumericSelector.wrap(DocValues.getSortedNumeric(context.reader(), field), selector, type);
+ }
+ };
+ case FLOAT:
+ return new FieldComparator.FloatComparator(numHits, getField(), (Float) missingValue) {
+ @Override
+ protected NumericDocValues getNumericDocValues(AtomicReaderContext context, String field) throws IOException {
+ return SortedNumericSelector.wrap(DocValues.getSortedNumeric(context.reader(), field), selector, type);
+ }
+ };
+ case LONG:
+ return new FieldComparator.LongComparator(numHits, getField(), (Long) missingValue) {
+ @Override
+ protected NumericDocValues getNumericDocValues(AtomicReaderContext context, String field) throws IOException {
+ return SortedNumericSelector.wrap(DocValues.getSortedNumeric(context.reader(), field), selector, type);
+ }
+ };
+ case DOUBLE:
+ return new FieldComparator.DoubleComparator(numHits, getField(), (Double) missingValue) {
+ @Override
+ protected NumericDocValues getNumericDocValues(AtomicReaderContext context, String field) throws IOException {
+ return SortedNumericSelector.wrap(DocValues.getSortedNumeric(context.reader(), field), selector, type);
+ }
+ };
+ default:
+ throw new AssertionError();
+ }
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/util/NumericUtils.java b/lucene/core/src/java/org/apache/lucene/util/NumericUtils.java
index e92627e6500..995eb8cbf10 100644
--- a/lucene/core/src/java/org/apache/lucene/util/NumericUtils.java
+++ b/lucene/core/src/java/org/apache/lucene/util/NumericUtils.java
@@ -274,9 +274,7 @@ public final class NumericUtils {
* @see #sortableLongToDouble
*/
public static long doubleToSortableLong(double val) {
- long f = Double.doubleToLongBits(val);
- if (f<0) f ^= 0x7fffffffffffffffL;
- return f;
+ return sortableDoubleBits(Double.doubleToLongBits(val));
}
/**
@@ -284,8 +282,7 @@ public final class NumericUtils {
* @see #doubleToSortableLong
*/
public static double sortableLongToDouble(long val) {
- if (val<0) val ^= 0x7fffffffffffffffL;
- return Double.longBitsToDouble(val);
+ return Double.longBitsToDouble(sortableDoubleBits(val));
}
/**
@@ -298,9 +295,7 @@ public final class NumericUtils {
* @see #sortableIntToFloat
*/
public static int floatToSortableInt(float val) {
- int f = Float.floatToIntBits(val);
- if (f<0) f ^= 0x7fffffff;
- return f;
+ return sortableFloatBits(Float.floatToIntBits(val));
}
/**
@@ -308,8 +303,17 @@ public final class NumericUtils {
* @see #floatToSortableInt
*/
public static float sortableIntToFloat(int val) {
- if (val<0) val ^= 0x7fffffff;
- return Float.intBitsToFloat(val);
+ return Float.intBitsToFloat(sortableFloatBits(val));
+ }
+
+ /** Converts IEEE 754 representation of a double to sortable order (or back to the original) */
+ public static long sortableDoubleBits(long bits) {
+ return bits ^ (bits >> 63) & 0x7fffffffffffffffL;
+ }
+
+ /** Converts IEEE 754 representation of a float to sortable order (or back to the original) */
+ public static int sortableFloatBits(int bits) {
+ return bits ^ (bits >> 31) & 0x7fffffff;
}
/**
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene45/TestLucene45DocValuesFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene45/TestLucene45DocValuesFormat.java
index ad51a936cf4..67654da5549 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene45/TestLucene45DocValuesFormat.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene45/TestLucene45DocValuesFormat.java
@@ -19,14 +19,19 @@ package org.apache.lucene.codecs.lucene45;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.index.BaseCompressingDocValuesFormatTestCase;
-import org.apache.lucene.util.TestUtil;
+import org.junit.BeforeClass;
/**
* Tests Lucene45DocValuesFormat
*/
public class TestLucene45DocValuesFormat extends BaseCompressingDocValuesFormatTestCase {
- private final Codec codec = TestUtil.alwaysDocValuesFormat(new Lucene45DocValuesFormat());
-
+ private final Codec codec = new Lucene45RWCodec();
+
+ @BeforeClass
+ public static void beforeClass() {
+ OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; // explicitly instantiates ancient codec
+ }
+
@Override
protected Codec getCodec() {
return codec;
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDuelingCodecs.java b/lucene/core/src/test/org/apache/lucene/index/TestDuelingCodecs.java
index e41a32189b6..f516bf07257 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDuelingCodecs.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDuelingCodecs.java
@@ -24,6 +24,7 @@ import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.NumericDocValuesField;
+import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
@@ -142,6 +143,14 @@ public class TestDuelingCodecs extends LuceneTestCase {
if (random.nextInt(4) == 2) {
document.add(new NumericDocValuesField("sparsenumeric", random.nextInt()));
}
+ // add sortednumeric sometimes
+ document.removeFields("sparsesortednum");
+ if (random.nextInt(5) == 1) {
+ document.add(new SortedNumericDocValuesField("sparsesortednum", random.nextLong()));
+ if (random.nextBoolean()) {
+ document.add(new SortedNumericDocValuesField("sparsesortednum", random.nextLong()));
+ }
+ }
writer.addDocument(document);
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
index 326e9f45c12..03881d91b9d 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
@@ -48,6 +48,7 @@ import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
+import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
@@ -1018,6 +1019,10 @@ public class TestIndexWriter extends LuceneTestCase {
doc.add(new SortedSetDocValuesField("sortedsetdv", new BytesRef("one")));
doc.add(new SortedSetDocValuesField("sortedsetdv", new BytesRef("two")));
}
+ if (defaultCodecSupportsSortedNumeric()) {
+ doc.add(new SortedNumericDocValuesField("sortednumericdv", 4));
+ doc.add(new SortedNumericDocValuesField("sortednumericdv", 3));
+ }
w.addDocument(doc);
doc = new Document();
doc.add(newStringField(random, "id", "501", Field.Store.NO));
@@ -1029,6 +1034,10 @@ public class TestIndexWriter extends LuceneTestCase {
doc.add(new SortedSetDocValuesField("sortedsetdv", new BytesRef("two")));
doc.add(new SortedSetDocValuesField("sortedsetdv", new BytesRef("three")));
}
+ if (defaultCodecSupportsSortedNumeric()) {
+ doc.add(new SortedNumericDocValuesField("sortednumericdv", 6));
+ doc.add(new SortedNumericDocValuesField("sortednumericdv", 1));
+ }
w.addDocument(doc);
w.deleteDocuments(new Term("id", "500"));
w.shutdown();
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java
index 0b7ef6c4119..e0e33358ede 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java
@@ -41,6 +41,7 @@ import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
+import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
@@ -159,6 +160,10 @@ public class TestIndexWriterExceptions extends LuceneTestCase {
doc.add(new SortedSetDocValuesField("sortedsetdv", new BytesRef("hellllo")));
doc.add(new SortedSetDocValuesField("sortedsetdv", new BytesRef("again")));
}
+ if (defaultCodecSupportsSortedNumeric()) {
+ doc.add(new SortedNumericDocValuesField("sortednumericdv", 10));
+ doc.add(new SortedNumericDocValuesField("sortednumericdv", 5));
+ }
doc.add(newField(r, "content7", "aaa bbb ccc ddd", DocCopyIterator.custom4));
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java
index 658f8b48d3c..9b337a5260b 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java
@@ -36,6 +36,7 @@ import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
+import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
@@ -109,6 +110,10 @@ public class TestIndexWriterExceptions2 extends LuceneTestCase {
doc.add(new SortedSetDocValuesField("dv4", new BytesRef(Integer.toString(i))));
doc.add(new SortedSetDocValuesField("dv4", new BytesRef(Integer.toString(i-1))));
}
+ if (defaultCodecSupportsSortedNumeric()) {
+ doc.add(new SortedNumericDocValuesField("dv5", i));
+ doc.add(new SortedNumericDocValuesField("dv5", i-1));
+ }
doc.add(newTextField("text1", TestUtil.randomAnalysisString(random(), 20, true), Field.Store.NO));
// ensure we store something
doc.add(new StoredField("stored1", "foo"));
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOutOfMemory.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOutOfMemory.java
index 6a53ea394a0..951f03ce9d4 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOutOfMemory.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOutOfMemory.java
@@ -33,6 +33,7 @@ import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
+import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
@@ -129,6 +130,10 @@ public class TestIndexWriterOutOfMemory extends LuceneTestCase {
doc.add(new SortedSetDocValuesField("dv4", new BytesRef(Integer.toString(i))));
doc.add(new SortedSetDocValuesField("dv4", new BytesRef(Integer.toString(i-1))));
}
+ if (defaultCodecSupportsSortedNumeric()) {
+ doc.add(new SortedNumericDocValuesField("dv5", i));
+ doc.add(new SortedNumericDocValuesField("dv5", i-1));
+ }
doc.add(newTextField("text1", TestUtil.randomAnalysisString(random(), 20, true), Field.Store.NO));
// ensure we store something
doc.add(new StoredField("stored1", "foo"));
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestMultiDocValues.java b/lucene/core/src/test/org/apache/lucene/index/TestMultiDocValues.java
index acf2b4747bc..e08a38422ac 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestMultiDocValues.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestMultiDocValues.java
@@ -24,6 +24,7 @@ import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
+import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
@@ -317,6 +318,58 @@ public class TestMultiDocValues extends LuceneTestCase {
dir.close();
}
+ public void testSortedNumeric() throws Exception {
+ assumeTrue("codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ Directory dir = newDirectory();
+
+ IndexWriterConfig iwc = newIndexWriterConfig(random(), TEST_VERSION_CURRENT, null);
+ iwc.setMergePolicy(newLogMergePolicy());
+ RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwc);
+
+ int numDocs = atLeast(500);
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ int numValues = random().nextInt(5);
+ for (int j = 0; j < numValues; j++) {
+ doc.add(new SortedNumericDocValuesField("nums", TestUtil.nextLong(random(), Long.MIN_VALUE, Long.MAX_VALUE)));
+ }
+ iw.addDocument(doc);
+ if (random().nextInt(17) == 0) {
+ iw.commit();
+ }
+ }
+ DirectoryReader ir = iw.getReader();
+ iw.forceMerge(1);
+ DirectoryReader ir2 = iw.getReader();
+ AtomicReader merged = getOnlySegmentReader(ir2);
+ iw.shutdown();
+
+ SortedNumericDocValues multi = MultiDocValues.getSortedNumericValues(ir, "nums");
+ SortedNumericDocValues single = merged.getSortedNumericDocValues("nums");
+ if (multi == null) {
+ assertNull(single);
+ } else {
+ // check values
+ for (int i = 0; i < numDocs; i++) {
+ single.setDocument(i);
+ ArrayList<Long> expectedList = new ArrayList<>();
+ for (int j = 0; j < single.count(); j++) {
+ expectedList.add(single.valueAt(j));
+ }
+
+ multi.setDocument(i);
+ assertEquals(expectedList.size(), multi.count());
+ for (int j = 0; j < single.count(); j++) {
+ assertEquals(expectedList.get(j).longValue(), multi.valueAt(j));
+ }
+ }
+ }
+
+ ir.close();
+ ir2.close();
+ dir.close();
+ }
+
public void testDocsWithField() throws Exception {
assumeTrue("codec does not support docsWithField", defaultCodecSupportsDocsWithField());
Directory dir = newDirectory();
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericSortField.java b/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericSortField.java
new file mode 100644
index 00000000000..dac420010e0
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericSortField.java
@@ -0,0 +1,289 @@
+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.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.SortedNumericDocValuesField;
+import org.apache.lucene.document.SortedSetDocValuesField;
+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.BytesRef;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
+import org.apache.lucene.util.NumericUtils;
+
+/** Simple tests for SortedNumericSortField */
+@SuppressCodecs({"Lucene40", "Lucene41", "Lucene42", "Lucene45", "Lucene46"})
+// avoid codecs that don't support sortednumeric
+public class TestSortedNumericSortField extends LuceneTestCase {
+
+ 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 SortedNumericSortField("sortednumeric", SortField.Type.LONG));
+ TopDocs td = empty.search(query, null, 10, sort, true, true);
+ assertEquals(0, td.totalHits);
+
+ // for an empty index, any selector should work
+ for (SortedNumericSelector.Type v : SortedNumericSelector.Type.values()) {
+ sort.setSort(new SortedNumericSortField("sortednumeric", SortField.Type.LONG, false, v));
+ td = empty.search(query, null, 10, sort, true, true);
+ assertEquals(0, td.totalHits);
+ }
+ }
+
+ public void testEquals() throws Exception {
+ SortField sf = new SortedNumericSortField("a", SortField.Type.LONG);
+ assertFalse(sf.equals(null));
+
+ assertEquals(sf, sf);
+
+ SortField sf2 = new SortedNumericSortField("a", SortField.Type.LONG);
+ assertEquals(sf, sf2);
+ assertEquals(sf.hashCode(), sf2.hashCode());
+
+ assertFalse(sf.equals(new SortedNumericSortField("a", SortField.Type.LONG, true)));
+ assertFalse(sf.equals(new SortedNumericSortField("a", SortField.Type.FLOAT)));
+ assertFalse(sf.equals(new SortedNumericSortField("b", SortField.Type.LONG)));
+ assertFalse(sf.equals(new SortedNumericSortField("a", SortField.Type.LONG, false, SortedNumericSelector.Type.MAX)));
+ assertFalse(sf.equals("foo"));
+ }
+
+ public void testForward() throws Exception {
+ Directory dir = newDirectory();
+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
+ Document doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", 5));
+ doc.add(newStringField("id", "2", Field.Store.YES));
+ writer.addDocument(doc);
+ doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", 3));
+ doc.add(new SortedNumericDocValuesField("value", 7));
+ doc.add(newStringField("id", "1", Field.Store.YES));
+ writer.addDocument(doc);
+ IndexReader ir = writer.getReader();
+ writer.shutdown();
+
+ IndexSearcher searcher = newSearcher(ir);
+ Sort sort = new Sort(new SortedNumericSortField("value", SortField.Type.INT));
+
+ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
+ assertEquals(2, td.totalHits);
+ // 3 comes before 5
+ 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(new SortedNumericDocValuesField("value", 3));
+ doc.add(new SortedNumericDocValuesField("value", 7));
+ doc.add(newStringField("id", "1", Field.Store.YES));
+ writer.addDocument(doc);
+ doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", 5));
+ doc.add(newStringField("id", "2", Field.Store.YES));
+ writer.addDocument(doc);
+
+ IndexReader ir = writer.getReader();
+ writer.shutdown();
+
+ IndexSearcher searcher = newSearcher(ir);
+ Sort sort = new Sort(new SortedNumericSortField("value", SortField.Type.INT, 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(new SortedNumericDocValuesField("value", 5));
+ doc.add(newStringField("id", "2", Field.Store.YES));
+ writer.addDocument(doc);
+ doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", 3));
+ doc.add(new SortedNumericDocValuesField("value", 7));
+ 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.shutdown();
+
+ IndexSearcher searcher = newSearcher(ir);
+ SortField sortField = new SortedNumericSortField("value", SortField.Type.INT);
+ sortField.setMissingValue(Integer.MIN_VALUE);
+ Sort sort = new Sort(sortField);
+
+ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
+ assertEquals(3, td.totalHits);
+ // 3 comes before 5
+ // 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(new SortedNumericDocValuesField("value", 5));
+ doc.add(newStringField("id", "2", Field.Store.YES));
+ writer.addDocument(doc);
+ doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", 3));
+ doc.add(new SortedNumericDocValuesField("value", 7));
+ 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.shutdown();
+
+ IndexSearcher searcher = newSearcher(ir);
+ SortField sortField = new SortedNumericSortField("value", SortField.Type.INT);
+ sortField.setMissingValue(Integer.MAX_VALUE);
+ Sort sort = new Sort(sortField);
+
+ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
+ assertEquals(3, td.totalHits);
+ // 3 comes before 5
+ 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(new SortedNumericDocValuesField("value", 5));
+ doc.add(newStringField("id", "2", Field.Store.YES));
+ writer.addDocument(doc);
+ doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", 3));
+ doc.add(newStringField("id", "1", Field.Store.YES));
+ writer.addDocument(doc);
+ IndexReader ir = writer.getReader();
+ writer.shutdown();
+
+ IndexSearcher searcher = newSearcher(ir);
+ Sort sort = new Sort(new SortedNumericSortField("value", SortField.Type.INT));
+
+ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
+ assertEquals(2, td.totalHits);
+ // 3 comes before 5
+ 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 testFloat() throws Exception {
+ Directory dir = newDirectory();
+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
+ Document doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", NumericUtils.floatToSortableInt(-3f)));
+ doc.add(newStringField("id", "2", Field.Store.YES));
+ writer.addDocument(doc);
+ doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", NumericUtils.floatToSortableInt(-5f)));
+ doc.add(new SortedNumericDocValuesField("value", NumericUtils.floatToSortableInt(7f)));
+ doc.add(newStringField("id", "1", Field.Store.YES));
+ writer.addDocument(doc);
+ IndexReader ir = writer.getReader();
+ writer.shutdown();
+
+ IndexSearcher searcher = newSearcher(ir);
+ Sort sort = new Sort(new SortedNumericSortField("value", SortField.Type.FLOAT));
+
+ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
+ assertEquals(2, td.totalHits);
+ // -5 comes before -3
+ 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 testDouble() throws Exception {
+ Directory dir = newDirectory();
+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
+ Document doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", NumericUtils.doubleToSortableLong(-3d)));
+ doc.add(newStringField("id", "2", Field.Store.YES));
+ writer.addDocument(doc);
+ doc = new Document();
+ doc.add(new SortedNumericDocValuesField("value", NumericUtils.doubleToSortableLong(-5d)));
+ doc.add(new SortedNumericDocValuesField("value", NumericUtils.doubleToSortableLong(7d)));
+ doc.add(newStringField("id", "1", Field.Store.YES));
+ writer.addDocument(doc);
+ IndexReader ir = writer.getReader();
+ writer.shutdown();
+
+ IndexSearcher searcher = newSearcher(ir);
+ Sort sort = new Sort(new SortedNumericSortField("value", SortField.Type.DOUBLE));
+
+ TopDocs td = searcher.search(new MatchAllDocsQuery(), 10, sort);
+ assertEquals(2, td.totalHits);
+ // -5 comes before -3
+ assertEquals("1", searcher.doc(td.scoreDocs[0].doc).get("id"));
+ assertEquals("2", searcher.doc(td.scoreDocs[1].doc).get("id"));
+
+ ir.close();
+ dir.close();
+ }
+}
diff --git a/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java b/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java
index b628517bbcd..09ab9bfa60a 100644
--- a/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java
+++ b/lucene/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java
@@ -45,6 +45,7 @@ import org.apache.lucene.index.Fields;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.OrdTermState;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.StoredFieldVisitor;
import org.apache.lucene.index.TermState;
@@ -793,6 +794,11 @@ public class MemoryIndex {
return null;
}
+ @Override
+ public SortedNumericDocValues getSortedNumericDocValues(String field) {
+ return null;
+ }
+
@Override
public SortedSetDocValues getSortedSetDocValues(String field) {
return null;
diff --git a/lucene/misc/src/test/org/apache/lucene/uninverting/TestUninvertingReader.java b/lucene/misc/src/test/org/apache/lucene/uninverting/TestUninvertingReader.java
index 37389e7895a..714ebadb16c 100644
--- a/lucene/misc/src/test/org/apache/lucene/uninverting/TestUninvertingReader.java
+++ b/lucene/misc/src/test/org/apache/lucene/uninverting/TestUninvertingReader.java
@@ -235,6 +235,10 @@ public class TestUninvertingReader extends LuceneTestCase {
break;
case SORTED_SET:
reader.getSortedSetDocValues(field);
+ break;
+ case SORTED_NUMERIC:
+ // not supported
+ return;
default:
throw new AssertionError();
}
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/function/TestDocValuesFieldSources.java b/lucene/queries/src/test/org/apache/lucene/queries/function/TestDocValuesFieldSources.java
index 78fc197fe42..2411da28646 100644
--- a/lucene/queries/src/test/org/apache/lucene/queries/function/TestDocValuesFieldSources.java
+++ b/lucene/queries/src/test/org/apache/lucene/queries/function/TestDocValuesFieldSources.java
@@ -146,7 +146,7 @@ public class TestDocValuesFieldSources extends LuceneTestCase {
public void test() throws IOException {
for (DocValuesType type : DocValuesType.values()) {
- if (type != DocValuesType.SORTED_SET) {
+ if (type != DocValuesType.SORTED_SET && type != DocValuesType.SORTED_NUMERIC) {
test(type);
}
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/asserting/AssertingDocValuesFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/asserting/AssertingDocValuesFormat.java
index 57a3c50ce14..c109e1ab899 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/asserting/AssertingDocValuesFormat.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/asserting/AssertingDocValuesFormat.java
@@ -32,6 +32,7 @@ import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
@@ -130,6 +131,30 @@ public class AssertingDocValuesFormat extends DocValuesFormat {
in.addSortedField(field, values, docToOrd);
}
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ long valueCount = 0;
+ Iterator<Number> valueIterator = values.iterator();
+ for (Number count : docToValueCount) {
+ assert count != null;
+ assert count.intValue() >= 0;
+ valueCount += count.intValue();
+ long previous = Long.MIN_VALUE;
+ for (int i = 0; i < count.intValue(); i++) {
+ assert valueIterator.hasNext();
+ Number next = valueIterator.next();
+ assert next != null;
+ long nextValue = next.longValue();
+ assert nextValue >= previous;
+ previous = nextValue;
+ }
+ }
+ assert valueIterator.hasNext() == false;
+ checkIterator(docToValueCount.iterator(), maxDoc, false);
+ checkIterator(values.iterator(), valueCount, false);
+ in.addSortedNumericField(field, docToValueCount, values);
+ }
+
@Override
public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrdCount, Iterable<Number> ords) throws IOException {
long valueCount = 0;
@@ -217,6 +242,11 @@ public class AssertingDocValuesFormat extends DocValuesFormat {
public void addSortedField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrd) throws IOException {
throw new IllegalStateException();
}
+
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ throw new IllegalStateException();
+ }
@Override
public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrdCount, Iterable<Number> ords) throws IOException {
@@ -280,6 +310,14 @@ public class AssertingDocValuesFormat extends DocValuesFormat {
return new AssertingAtomicReader.AssertingSortedDocValues(values, maxDoc);
}
+ @Override
+ public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException {
+ assert field.getDocValuesType() == FieldInfo.DocValuesType.SORTED_NUMERIC;
+ SortedNumericDocValues values = in.getSortedNumeric(field);
+ assert values != null;
+ return new AssertingAtomicReader.AssertingSortedNumericDocValues(values, maxDoc);
+ }
+
@Override
public SortedSetDocValues getSortedSet(FieldInfo field) throws IOException {
assert field.getDocValuesType() == FieldInfo.DocValuesType.SORTED_SET;
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/cranky/CrankyDocValuesFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/cranky/CrankyDocValuesFormat.java
index a05dd8e8cdd..0ee8281c639 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/cranky/CrankyDocValuesFormat.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/cranky/CrankyDocValuesFormat.java
@@ -93,6 +93,14 @@ class CrankyDocValuesFormat extends DocValuesFormat {
}
delegate.addSortedField(field, values, docToOrd);
}
+
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ if (random.nextInt(100) == 0) {
+ throw new IOException("Fake IOException from DocValuesConsumer.addSortedNumericField()");
+ }
+ delegate.addSortedNumericField(field, docToValueCount, values);
+ }
@Override
public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrdCount, Iterable<Number> ords) throws IOException {
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Lucene40DocValuesWriter.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Lucene40DocValuesWriter.java
index 2a300397df5..2f636857898 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Lucene40DocValuesWriter.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene40/Lucene40DocValuesWriter.java
@@ -530,6 +530,11 @@ class Lucene40DocValuesWriter extends DocValuesConsumer {
ords.finish();
}
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ throw new UnsupportedOperationException("Lucene 4.0 does not support SortedNumeric docvalues");
+ }
+
@Override
public void addSortedSetField(FieldInfo field, Iterable<BytesRef> values, Iterable<Number> docToOrdCount, Iterable<Number> ords) throws IOException {
throw new UnsupportedOperationException("Lucene 4.0 does not support SortedSet docvalues");
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesConsumer.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesConsumer.java
index 999014a56c7..464bd4f920c 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesConsumer.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesConsumer.java
@@ -378,4 +378,9 @@ class Lucene42DocValuesConsumer extends DocValuesConsumer {
throw new UnsupportedOperationException();
}
}
+
+ @Override
+ public void addSortedNumericField(FieldInfo field, Iterable<Number> docToValueCount, Iterable<Number> values) throws IOException {
+ throw new UnsupportedOperationException("Lucene 4.2 does not support SORTED_NUMERIC");
+ }
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/AssertingAtomicReader.java b/lucene/test-framework/src/java/org/apache/lucene/index/AssertingAtomicReader.java
index b7f3c0c1cb0..cd9b163ae51 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/index/AssertingAtomicReader.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/index/AssertingAtomicReader.java
@@ -511,6 +511,41 @@ public class AssertingAtomicReader extends FilterAtomicReader {
}
}
+ /** Wraps a SortedSetDocValues but with additional asserts */
+ public static class AssertingSortedNumericDocValues extends SortedNumericDocValues {
+ private final SortedNumericDocValues in;
+ private final int maxDoc;
+
+ public AssertingSortedNumericDocValues(SortedNumericDocValues in, int maxDoc) {
+ this.in = in;
+ this.maxDoc = maxDoc;
+ }
+
+ @Override
+ public void setDocument(int doc) {
+ assert doc >= 0 && doc < maxDoc;
+ in.setDocument(doc);
+ // check the values are actually sorted
+ long previous = Long.MIN_VALUE;
+ for (int i = 0; i < in.count(); i++) {
+ long v = in.valueAt(i);
+ assert v >= previous;
+ previous = v;
+ }
+ }
+
+ @Override
+ public long valueAt(int index) {
+ assert index < in.count();
+ return in.valueAt(index);
+ }
+
+ @Override
+ public int count() {
+ return in.count();
+ }
+ }
+
/** Wraps a SortedSetDocValues but with additional asserts */
public static class AssertingSortedSetDocValues extends SortedSetDocValues {
private final SortedSetDocValues in;
@@ -608,6 +643,20 @@ public class AssertingAtomicReader extends FilterAtomicReader {
return null;
}
}
+
+ @Override
+ public SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException {
+ SortedNumericDocValues dv = super.getSortedNumericDocValues(field);
+ FieldInfo fi = getFieldInfos().fieldInfo(field);
+ if (dv != null) {
+ assert fi != null;
+ assert fi.getDocValuesType() == FieldInfo.DocValuesType.SORTED_NUMERIC;
+ return new AssertingSortedNumericDocValues(dv, maxDoc());
+ } else {
+ assert fi == null || fi.getDocValuesType() != FieldInfo.DocValuesType.SORTED_NUMERIC;
+ return null;
+ }
+ }
@Override
public SortedSetDocValues getSortedSetDocValues(String field) throws IOException {
diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/BaseDocValuesFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/index/BaseDocValuesFormatTestCase.java
index 4535bef809f..79c18a2f36e 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/index/BaseDocValuesFormatTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/index/BaseDocValuesFormatTestCase.java
@@ -21,6 +21,7 @@ import static org.apache.lucene.index.SortedSetDocValues.NO_MORE_ORDS;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@@ -38,6 +39,7 @@ import org.apache.lucene.document.Field;
import org.apache.lucene.document.FloatDocValuesField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
+import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
@@ -79,6 +81,12 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
doc.add(new SortedSetDocValuesField("ssdv", new BytesRef(TestUtil.randomSimpleString(random(), 2))));
}
}
+ if (defaultCodecSupportsSortedNumeric()) {
+ final int numValues = random().nextInt(5);
+ for (int i = 0; i < numValues; ++i) {
+ doc.add(new SortedNumericDocValuesField("sndv", TestUtil.nextLong(random(), Long.MIN_VALUE, Long.MAX_VALUE)));
+ }
+ }
}
public void testOneNumber() throws IOException {
@@ -1193,6 +1201,69 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
dir.close();
}
+ private void doTestSortedNumericsVsStoredFields(LongProducer counts, LongProducer values) throws Exception {
+ Directory dir = newDirectory();
+ IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
+ RandomIndexWriter writer = new RandomIndexWriter(random(), dir, conf);
+
+ // index some docs
+ int numDocs = atLeast(300);
+ // numDocs should be always > 256 so that in case of a codec that optimizes
+ // for numbers of values <= 256, all storage layouts are tested
+ assert numDocs > 256;
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ doc.add(new StringField("id", Integer.toString(i), Field.Store.NO));
+
+ int valueCount = (int) counts.next();
+ long valueArray[] = new long[valueCount];
+ for (int j = 0; j < valueCount; j++) {
+ long value = values.next();
+ valueArray[j] = value;
+ doc.add(new SortedNumericDocValuesField("dv", value));
+ }
+ Arrays.sort(valueArray);
+ for (int j = 0; j < valueCount; j++) {
+ doc.add(new StoredField("stored", Long.toString(valueArray[j])));
+ }
+ writer.addDocument(doc);
+ if (random().nextInt(31) == 0) {
+ writer.commit();
+ }
+ }
+
+ // delete some docs
+ int numDeletions = random().nextInt(numDocs/10);
+ for (int i = 0; i < numDeletions; i++) {
+ int id = random().nextInt(numDocs);
+ writer.deleteDocuments(new Term("id", Integer.toString(id)));
+ }
+
+ // merge some segments and ensure that at least one of them has more than
+ // 256 values
+ writer.forceMerge(numDocs / 256);
+
+ writer.shutdown();
+
+ // compare
+ DirectoryReader ir = DirectoryReader.open(dir);
+ for (AtomicReaderContext context : ir.leaves()) {
+ AtomicReader r = context.reader();
+ SortedNumericDocValues docValues = DocValues.getSortedNumeric(r, "dv");
+ for (int i = 0; i < r.maxDoc(); i++) {
+ String expected[] = r.document(i).getValues("stored");
+ docValues.setDocument(i);
+ String actual[] = new String[docValues.count()];
+ for (int j = 0; j < actual.length; j++) {
+ actual[j] = Long.toString(docValues.valueAt(j));
+ }
+ assertArrayEquals(expected, actual);
+ }
+ }
+ ir.close();
+ dir.close();
+ }
+
public void testBooleanNumericsVsStoredFields() throws Exception {
int numIterations = atLeast(1);
for (int i = 0; i < numIterations; i++) {
@@ -1889,6 +1960,69 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
}
}
+ public void testSortedNumericsSingleValuedVsStoredFields() throws Exception {
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ int numIterations = atLeast(1);
+ for (int i = 0; i < numIterations; i++) {
+ doTestSortedNumericsVsStoredFields(
+ new LongProducer() {
+ @Override
+ long next() {
+ return 1;
+ }
+ },
+ new LongProducer() {
+ @Override
+ long next() {
+ return TestUtil.nextLong(random(), Long.MIN_VALUE, Long.MAX_VALUE);
+ }
+ }
+ );
+ }
+ }
+
+ public void testSortedNumericsSingleValuedMissingVsStoredFields() throws Exception {
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ int numIterations = atLeast(1);
+ for (int i = 0; i < numIterations; i++) {
+ doTestSortedNumericsVsStoredFields(
+ new LongProducer() {
+ @Override
+ long next() {
+ return random().nextBoolean() ? 0 : 1;
+ }
+ },
+ new LongProducer() {
+ @Override
+ long next() {
+ return TestUtil.nextLong(random(), Long.MIN_VALUE, Long.MAX_VALUE);
+ }
+ }
+ );
+ }
+ }
+
+ public void testSortedNumericsMultipleValuesVsStoredFields() throws Exception {
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ int numIterations = atLeast(1);
+ for (int i = 0; i < numIterations; i++) {
+ doTestSortedNumericsVsStoredFields(
+ new LongProducer() {
+ @Override
+ long next() {
+ return TestUtil.nextLong(random(), 0, 50);
+ }
+ },
+ new LongProducer() {
+ @Override
+ long next() {
+ return TestUtil.nextLong(random(), Long.MIN_VALUE, Long.MAX_VALUE);
+ }
+ }
+ );
+ }
+ }
+
public void testSortedSetVariableLengthVsStoredFields() throws Exception {
assumeTrue("Codec does not support SORTED_SET", defaultCodecSupportsSortedSet());
int numIterations = atLeast(1);
@@ -2238,6 +2372,7 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
public void testThreads2() throws Exception {
assumeTrue("Codec does not support getDocsWithField", defaultCodecSupportsDocsWithField());
assumeTrue("Codec does not support SORTED_SET", defaultCodecSupportsSortedSet());
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
Directory dir = newDirectory();
IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
RandomIndexWriter writer = new RandomIndexWriter(random(), dir, conf);
@@ -2281,6 +2416,15 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
doc.add(new SortedSetDocValuesField("dvSortedSet", new BytesRef(v)));
doc.add(new StoredField("storedSortedSet", v));
}
+ int numSortedNumericFields = random().nextInt(3);
+ Set<Long> numValues = new TreeSet<>();
+ for (int j = 0; j < numSortedNumericFields; j++) {
+ numValues.add(TestUtil.nextLong(random(), Long.MIN_VALUE, Long.MAX_VALUE));
+ }
+ for (Long l : numValues) {
+ doc.add(new SortedNumericDocValuesField("dvSortedNumeric", l));
+ doc.add(new StoredField("storedSortedNumeric", Long.toString(l)));
+ }
writer.addDocument(doc);
if (random().nextInt(31) == 0) {
writer.commit();
@@ -2317,6 +2461,8 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
Bits numericBits = r.getDocsWithField("dvNum");
SortedSetDocValues sortedSet = r.getSortedSetDocValues("dvSortedSet");
Bits sortedSetBits = r.getDocsWithField("dvSortedSet");
+ SortedNumericDocValues sortedNumeric = r.getSortedNumericDocValues("dvSortedNumeric");
+ Bits sortedNumericBits = r.getDocsWithField("dvSortedNumeric");
for (int j = 0; j < r.maxDoc(); j++) {
BytesRef binaryValue = r.document(j).getBinaryValue("storedBin");
if (binaryValue != null) {
@@ -2361,6 +2507,22 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
assertEquals(SortedSetDocValues.NO_MORE_ORDS, sortedSet.nextOrd());
assertFalse(sortedSetBits.get(j));
}
+
+ String numValues[] = r.document(j).getValues("storedSortedNumeric");
+ if (numValues.length > 0) {
+ assertNotNull(sortedNumeric);
+ sortedNumeric.setDocument(j);
+ assertEquals(numValues.length, sortedNumeric.count());
+ for (int k = 0; k < numValues.length; k++) {
+ long v = sortedNumeric.valueAt(k);
+ assertEquals(numValues[k], Long.toString(v));
+ }
+ assertTrue(sortedNumericBits.get(j));
+ } else if (sortedNumeric != null) {
+ sortedNumeric.setDocument(j);
+ assertEquals(0, sortedNumeric.count());
+ assertFalse(sortedNumericBits.get(j));
+ }
}
}
TestUtil.checkReader(ir);
@@ -2414,6 +2576,171 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
dir.close();
}
}
+
+ public void testOneSortedNumber() throws IOException {
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ Directory directory = newDirectory();
+ RandomIndexWriter writer = new RandomIndexWriter(random(), directory);
+ Document doc = new Document();
+ doc.add(new SortedNumericDocValuesField("dv", 5));
+ writer.addDocument(doc);
+ writer.shutdown();
+
+ // Now search the index:
+ IndexReader reader = DirectoryReader.open(directory);
+ assert reader.leaves().size() == 1;
+ SortedNumericDocValues dv = reader.leaves().get(0).reader().getSortedNumericDocValues("dv");
+ dv.setDocument(0);
+ assertEquals(1, dv.count());
+ assertEquals(5, dv.valueAt(0));
+
+ reader.close();
+ directory.close();
+ }
+
+ public void testOneSortedNumberOneMissing() throws IOException {
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ Directory directory = newDirectory();
+ IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(TEST_VERSION_CURRENT, null));
+ Document doc = new Document();
+ doc.add(new SortedNumericDocValuesField("dv", 5));
+ writer.addDocument(doc);
+ writer.addDocument(new Document());
+ writer.shutdown();
+
+ // Now search the index:
+ IndexReader reader = DirectoryReader.open(directory);
+ assert reader.leaves().size() == 1;
+ SortedNumericDocValues dv = reader.leaves().get(0).reader().getSortedNumericDocValues("dv");
+ dv.setDocument(0);
+ assertEquals(1, dv.count());
+ assertEquals(5, dv.valueAt(0));
+ dv.setDocument(1);
+ assertEquals(0, dv.count());
+
+ Bits docsWithField = reader.leaves().get(0).reader().getDocsWithField("dv");
+ assertEquals(2, docsWithField.length());
+ assertTrue(docsWithField.get(0));
+ assertFalse(docsWithField.get(1));
+
+ reader.close();
+ directory.close();
+ }
+
+ public void testTwoSortedNumber() throws IOException {
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ Directory directory = newDirectory();
+ RandomIndexWriter writer = new RandomIndexWriter(random(), directory);
+ Document doc = new Document();
+ doc.add(new SortedNumericDocValuesField("dv", 11));
+ doc.add(new SortedNumericDocValuesField("dv", -5));
+ writer.addDocument(doc);
+ writer.shutdown();
+
+ // Now search the index:
+ IndexReader reader = DirectoryReader.open(directory);
+ assert reader.leaves().size() == 1;
+ SortedNumericDocValues dv = reader.leaves().get(0).reader().getSortedNumericDocValues("dv");
+ dv.setDocument(0);
+ assertEquals(2, dv.count());
+ assertEquals(-5, dv.valueAt(0));
+ assertEquals(11, dv.valueAt(1));
+
+ reader.close();
+ directory.close();
+ }
+
+ public void testTwoSortedNumberOneMissing() throws IOException {
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ Directory directory = newDirectory();
+ IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(TEST_VERSION_CURRENT, null));
+ Document doc = new Document();
+ doc.add(new SortedNumericDocValuesField("dv", 11));
+ doc.add(new SortedNumericDocValuesField("dv", -5));
+ writer.addDocument(doc);
+ writer.addDocument(new Document());
+ writer.shutdown();
+
+ // Now search the index:
+ IndexReader reader = DirectoryReader.open(directory);
+ assert reader.leaves().size() == 1;
+ SortedNumericDocValues dv = reader.leaves().get(0).reader().getSortedNumericDocValues("dv");
+ dv.setDocument(0);
+ assertEquals(2, dv.count());
+ assertEquals(-5, dv.valueAt(0));
+ assertEquals(11, dv.valueAt(1));
+ dv.setDocument(1);
+ assertEquals(0, dv.count());
+
+ Bits docsWithField = reader.leaves().get(0).reader().getDocsWithField("dv");
+ assertEquals(2, docsWithField.length());
+ assertTrue(docsWithField.get(0));
+ assertFalse(docsWithField.get(1));
+
+ reader.close();
+ directory.close();
+ }
+
+ public void testSortedNumberMerge() throws IOException {
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ Directory directory = newDirectory();
+ IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, null);
+ iwc.setMergePolicy(newLogMergePolicy());
+ IndexWriter writer = new IndexWriter(directory, iwc);
+ Document doc = new Document();
+ doc.add(new SortedNumericDocValuesField("dv", 11));
+ writer.addDocument(doc);
+ writer.commit();
+ doc = new Document();
+ doc.add(new SortedNumericDocValuesField("dv", -5));
+ writer.addDocument(doc);
+ writer.forceMerge(1);
+ writer.shutdown();
+
+ // Now search the index:
+ IndexReader reader = DirectoryReader.open(directory);
+ assert reader.leaves().size() == 1;
+ SortedNumericDocValues dv = reader.leaves().get(0).reader().getSortedNumericDocValues("dv");
+ dv.setDocument(0);
+ assertEquals(1, dv.count());
+ assertEquals(11, dv.valueAt(0));
+ dv.setDocument(1);
+ assertEquals(1, dv.count());
+ assertEquals(-5, dv.valueAt(0));
+
+ reader.close();
+ directory.close();
+ }
+
+ public void testSortedNumberMergeAwayAllValues() throws IOException {
+ assumeTrue("Codec does not support SORTED_NUMERIC", defaultCodecSupportsSortedNumeric());
+ Directory directory = newDirectory();
+ Analyzer analyzer = new MockAnalyzer(random());
+ IndexWriterConfig iwconfig = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
+ iwconfig.setMergePolicy(newLogMergePolicy());
+ RandomIndexWriter iwriter = new RandomIndexWriter(random(), directory, iwconfig);
+
+ Document doc = new Document();
+ doc.add(new StringField("id", "0", Field.Store.NO));
+ iwriter.addDocument(doc);
+ doc = new Document();
+ doc.add(new StringField("id", "1", Field.Store.NO));
+ doc.add(new SortedNumericDocValuesField("field", 5));
+ iwriter.addDocument(doc);
+ iwriter.commit();
+ iwriter.deleteDocuments(new Term("id", "1"));
+ iwriter.forceMerge(1);
+
+ DirectoryReader ireader = iwriter.getReader();
+ iwriter.shutdown();
+
+ SortedNumericDocValues dv = getOnlySegmentReader(ireader).getSortedNumericDocValues("field");
+ dv.setDocument(0);
+ assertEquals(0, dv.count());
+
+ ireader.close();
+ directory.close();
+ }
protected boolean codecAcceptsHugeBinaryValues(String field) {
return true;
diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/FieldFilterAtomicReader.java b/lucene/test-framework/src/java/org/apache/lucene/index/FieldFilterAtomicReader.java
index 33b61ab65b6..9ca11013ae9 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/index/FieldFilterAtomicReader.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/index/FieldFilterAtomicReader.java
@@ -132,6 +132,11 @@ public final class FieldFilterAtomicReader extends FilterAtomicReader {
return hasField(field) ? super.getSortedDocValues(field) : null;
}
+ @Override
+ public SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException {
+ return hasField(field) ? super.getSortedNumericDocValues(field) : null;
+ }
+
@Override
public SortedSetDocValues getSortedSetDocValues(String field) throws IOException {
return hasField(field) ? super.getSortedSetDocValues(field) : null;
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
index 08325b870ed..4256337480f 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
@@ -95,6 +95,7 @@ import org.apache.lucene.index.SerialMergeScheduler;
import org.apache.lucene.index.SimpleMergedSegmentWarmer;
import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.StorableField;
import org.apache.lucene.index.StoredDocument;
@@ -1680,6 +1681,15 @@ public abstract class LuceneTestCase extends Assert {
return true;
}
+ /** Returns true if the default codec supports SORTED_NUMERIC docvalues */
+ public static boolean defaultCodecSupportsSortedNumeric() {
+ String name = Codec.getDefault().getName();
+ if (name.equals("Lucene40") || name.equals("Lucene41") || name.equals("Lucene42") || name.equals("Lucene45") || name.equals("Lucene46")) {
+ return false;
+ }
+ return true;
+ }
+
/** Returns true if the codec "supports" docsWithField
* (other codecs return MatchAllBits, because you couldnt write missing values before) */
public static boolean defaultCodecSupportsDocsWithField() {
@@ -2288,6 +2298,28 @@ public abstract class LuceneTestCase extends Assert {
}
}
+ {
+ SortedNumericDocValues leftValues = MultiDocValues.getSortedNumericValues(leftReader, field);
+ SortedNumericDocValues rightValues = MultiDocValues.getSortedNumericValues(rightReader, field);
+ if (leftValues != null && rightValues != null) {
+ for (int i = 0; i < leftReader.maxDoc(); i++) {
+ leftValues.setDocument(i);
+ long expected[] = new long[leftValues.count()];
+ for (int j = 0; j < expected.length; j++) {
+ expected[j] = leftValues.valueAt(j);
+ }
+ rightValues.setDocument(i);
+ for (int j = 0; j < expected.length; j++) {
+ assertEquals(info, expected[j], rightValues.valueAt(j));
+ }
+ assertEquals(info, expected.length, rightValues.count());
+ }
+ } else {
+ assertNull(info, leftValues);
+ assertNull(info, rightValues);
+ }
+ }
+
{
Bits leftBits = MultiDocValues.getDocsWithField(leftReader, field);
Bits rightBits = MultiDocValues.getDocsWithField(rightReader, field);
diff --git a/solr/core/src/test/org/apache/solr/search/TestDocSet.java b/solr/core/src/test/org/apache/solr/search/TestDocSet.java
index ec6d7d860bf..e74f55c20c1 100644
--- a/solr/core/src/test/org/apache/solr/search/TestDocSet.java
+++ b/solr/core/src/test/org/apache/solr/search/TestDocSet.java
@@ -33,6 +33,7 @@ import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SortedDocValues;
+import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.StoredFieldVisitor;
import org.apache.lucene.search.DocIdSet;
@@ -406,6 +407,11 @@ public class TestDocSet extends LuceneTestCase {
return null;
}
+ @Override
+ public SortedNumericDocValues getSortedNumericDocValues(String field) {
+ return null;
+ }
+
@Override
public SortedSetDocValues getSortedSetDocValues(String field) {
return null;