Apache Lucene open-source search software
- Fixed IndexOutOfBoundException due to PagedBytes Boundary - Added Source based ValuesEnums for all types - Cut over to PagedBytes - Share binary search impl with all sorted implementations - DocValuesCodec is now directly compute the file names belonging to it due to per codec metadata - splitted up testcases in more and smaller tests - removed several nocommit
Simon Willnauer8dbe034b5928
diff --git a/lucene/src/java/org/apache/lucene/document/ValuesField.java b/lucene/src/java/org/apache/lucene/document/ValuesField.javaindex 43fc6bd6623..d71a273a3d9 100644--- a/lucene/src/java/org/apache/lucene/document/ValuesField.java+++ b/lucene/src/java/org/apache/lucene/document/ValuesField.java@@ -16,7 +16,6 @@ package org.apache.lucene.document;* See the License for the specific language governing permissions and* limitations under the License.*/-import java.io.IOException;import java.io.Reader;import java.util.Comparator;@@ -118,7 +117,6 @@ public class ValuesField extends AbstractField {valField.setBytes(ref, type);break;case PACKED_INTS:- case PACKED_INTS_FIXED:valField.setInt(Long.parseLong(field.stringValue()));break;case SIMPLE_FLOAT_4BYTE:diff --git a/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java b/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.javaindex dee260a976d..1eeeacb1176 100644--- a/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java+++ b/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java@@ -43,6 +43,8 @@ final class DocFieldProcessor extends DocConsumer {final StoredFieldsWriter fieldsWriter;final private Map<String, DocValuesConsumer> docValues = new HashMap<String, DocValuesConsumer>();private FieldsConsumer fieldsConsumer; // TODO this should be encapsulated in DocumentsWriter+ private SegmentWriteState docValuesConsumerState; // TODO this should be encapsulated in DocumentsWriter+synchronized DocValuesConsumer docValuesConsumer(Directory dir,String segment, String name, ValuesAttribute attr, FieldInfo fieldInfo)@@ -57,8 +59,8 @@ final class DocFieldProcessor extends DocConsumer {* the SegmentsWriteState passed in right at the moment when the segment is flushed (doccount etc) but we need the consumer earlier* to support docvalues and later on stored fields too.*/- SegmentWriteState state = docWriter.segWriteState();- fieldsConsumer = state.segmentCodecs.codec().fieldsConsumer(state);+ docValuesConsumerState = docWriter.segWriteState();+ fieldsConsumer = docValuesConsumerState.segmentCodecs.codec().fieldsConsumer(docValuesConsumerState);}valuesConsumer = fieldsConsumer.addValuesField(fieldInfo);docValues.put(name, valuesConsumer);@@ -102,7 +104,9 @@ final class DocFieldProcessor extends DocConsumer {}docValues.clear();if(fieldsConsumer != null) {- fieldsConsumer.close(); // nocommit this should go away+ fieldsConsumer.close(); // TODO remove this once docvalues are fully supported by codecs+ state.flushedFiles.addAll(docValuesConsumerState.flushedFiles);+ docValuesConsumerState = null;fieldsConsumer = null;}diff --git a/lucene/src/java/org/apache/lucene/index/FieldInfos.java b/lucene/src/java/org/apache/lucene/index/FieldInfos.javaindex 0c8aef3b11e..a6baae51324 100644--- a/lucene/src/java/org/apache/lucene/index/FieldInfos.java+++ b/lucene/src/java/org/apache/lucene/index/FieldInfos.java@@ -344,9 +344,6 @@ public final class FieldInfos {case BYTES_VAR_SORTED:b = 9;break;- case PACKED_INTS_FIXED:- b = 10;- break;default:throw new IllegalStateException("unhandled indexValues type " + fi.docValues);}@@ -413,9 +410,6 @@ public final class FieldInfos {case 9:fi.docValues = Values.BYTES_VAR_SORTED;break;- case 10:- fi.docValues = Values.PACKED_INTS_FIXED;- break;default:throw new IllegalStateException("unhandled indexValues type " + b);}diff --git a/lucene/src/java/org/apache/lucene/index/IndexFileNames.java b/lucene/src/java/org/apache/lucene/index/IndexFileNames.javaindex 1917b1e7dd8..ef9c4b419c6 100644--- a/lucene/src/java/org/apache/lucene/index/IndexFileNames.java+++ b/lucene/src/java/org/apache/lucene/index/IndexFileNames.java@@ -79,12 +79,6 @@ public final class IndexFileNames {/** Extension of separate norms */public static final String SEPARATE_NORMS_EXTENSION = "s";- /** Extension of Column-Stride Filed data files */- public static final String CSF_DATA_EXTENSION = "dat";-- /** Extension of Column-Stride Filed index files */- public static final String CSF_INDEX_EXTENSION = "idx";-/*** This array contains all filename extensions used by* Lucene's index files, with one exception, namely the@@ -104,8 +98,6 @@ public final class IndexFileNames {GEN_EXTENSION,NORMS_EXTENSION,COMPOUND_FILE_STORE_EXTENSION,- CSF_DATA_EXTENSION,- CSF_INDEX_EXTENSION};public static final String[] STORE_INDEX_EXTENSIONS = new String[] {diff --git a/lucene/src/java/org/apache/lucene/index/SegmentCodecs.java b/lucene/src/java/org/apache/lucene/index/SegmentCodecs.javaindex 3c707e0d281..0f31e7854e2 100644--- a/lucene/src/java/org/apache/lucene/index/SegmentCodecs.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentCodecs.java@@ -92,7 +92,6 @@ final class SegmentCodecs implements Cloneable {}}return new SegmentCodecs(provider, codecs.toArray(Codec.EMPTY));-}Codec codec() {diff --git a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.java b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.javaindex 75b330daa65..2a4a880b790 100644--- a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.java@@ -17,12 +17,9 @@ package org.apache.lucene.index.codecs.docvalues;* limitations under the License.*/import java.io.IOException;-import java.util.ArrayList;-import java.util.HashMap;+import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;-import java.util.List;-import java.util.Map;import java.util.Set;import java.util.Map.Entry;@@ -41,28 +38,32 @@ import org.apache.lucene.index.values.DocValues;import org.apache.lucene.index.values.Writer;import org.apache.lucene.store.Directory;import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;/*** A codec that adds DocValues support to a given codec transparently.*/public class DocValuesCodec extends Codec {- private final Map<String, WrappingFieldsConsumer> consumers = new HashMap<String, WrappingFieldsConsumer>();private final Codec other;+ private final Comparator<BytesRef> comparator;- public DocValuesCodec(Codec other) {+ public DocValuesCodec(Codec other, Comparator<BytesRef> comparator) {this.name = "docvalues_" + other.name;this.other = other;+ this.comparator = comparator;+ }++ public DocValuesCodec(Codec other) {+ this(other, null);}@Overridepublic FieldsConsumer fieldsConsumer(SegmentWriteState state)throws IOException {- WrappingFieldsConsumer consumer;- if ((consumer = consumers.get(state.segmentName)) == null) {- consumer = new WrappingFieldsConsumer(other);- }- consumer.state = state; // nocommit this is a hack and only necessary since- // we want to initialized the wrapped+ final WrappingFieldsConsumer consumer;+ consumer = new WrappingFieldsConsumer(other, comparator, state);+ // nocommit this is a hack and only necessary since+ // we want to initialized the wrapped// fieldsConsumer lazily with a SegmentWriteState created after the docvalue// ones is. We should fix this in DocumentWriter I guess. See// DocFieldProcessor too!@@ -70,31 +71,44 @@ public class DocValuesCodec extends Codec {}private static class WrappingFieldsConsumer extends FieldsConsumer {- SegmentWriteState state;- private final List<DocValuesConsumer> docValuesConsumers = new ArrayList<DocValuesConsumer>();+ private final SegmentWriteState state;private FieldsConsumer wrappedConsumer;private final Codec other;+ private final Comparator<BytesRef> comparator;+ private DocValuesCodecInfo info;- public WrappingFieldsConsumer(Codec other) {+ public WrappingFieldsConsumer(Codec other, Comparator<BytesRef> comparator, SegmentWriteState state) {this.other = other;+ this.comparator = comparator;+ this.state = state;}@Overridepublic void close() throws IOException {synchronized (this) {- if (wrappedConsumer != null)+ if (info != null) {+ info.write(state);+ info = null;+ }+ if (wrappedConsumer != null) {wrappedConsumer.close();+ }}+}@Overridepublic synchronized DocValuesConsumer addValuesField(FieldInfo field)throws IOException {- DocValuesConsumer consumer = DocValuesConsumer.create(state.segmentName,- // TODO: set comparator here- //TODO can we have a compound file per segment and codec for docvalues?- state.directory, field, state.codecId +"-"+ field.number, null);- docValuesConsumers.add(consumer);+ if(info == null) {+ info = new DocValuesCodecInfo();+ }+ final DocValuesConsumer consumer = DocValuesConsumer.create(info.docValuesId(state.segmentName, state.codecId, ""+ + field.number),+ // TODO can we have a compound file per segment and codec for+ // docvalues?+ state.directory, field, comparator);+ info.add(field.number);return consumer;}@@ -115,35 +129,23 @@ public class DocValuesCodec extends Codec {Set<String> files = new HashSet<String>();other.files(dir, state.segmentInfo, state.codecId, files);- for (String string : files) {+ for (String string : files) { // for now we just check if one of the files+ // exists and open the producerif (dir.fileExists(string))return new WrappingFielsdProducer(state, other.fieldsProducer(state));}return new WrappingFielsdProducer(state, FieldsProducer.EMPTY);-}@Overridepublic void files(Directory dir, SegmentInfo segmentInfo, String codecId,Set<String> files) throws IOException {- Set<String> otherFiles = new HashSet<String>();- other.files(dir, segmentInfo, codecId, otherFiles);- for (String string : otherFiles) { // under some circumstances we only write- // DocValues- // so other files will be added even if- // they don't exist- if (dir.fileExists(string))- files.add(string);- }- //TODO can we have a compound file per segment and codec for docvalues?- for (String file : dir.listAll()) {- if (file.startsWith(segmentInfo.name+"_" + codecId)- && (file.endsWith(Writer.DATA_EXTENSION) || file- .endsWith(Writer.INDEX_EXTENSION))) {- files.add(file);- }- }-+ other.files(dir, segmentInfo, codecId, files);+ // TODO can we have a compound file per segment and codec for docvalues?+ DocValuesCodecInfo info = new DocValuesCodecInfo(); // TODO can we do that+ // only once?+ info.read(dir, segmentInfo, codecId);+ info.files(dir, segmentInfo, codecId, files);}@Override@@ -151,6 +153,7 @@ public class DocValuesCodec extends Codec {other.getExtensions(extensions);extensions.add(Writer.DATA_EXTENSION);extensions.add(Writer.INDEX_EXTENSION);+ extensions.add(DocValuesCodecInfo.INFO_FILE_EXT);}static class WrappingFielsdProducer extends DocValuesProducerBase {@@ -219,7 +222,6 @@ public class DocValuesCodec extends Codec {name = value.next();return this;}-}static class DocValueNameValue extends NameValue<DocValues> {@@ -236,7 +238,6 @@ public class DocValuesCodec extends Codec {}return this;}-}static class WrappingFieldsEnum extends FieldsEnum {@@ -254,7 +255,6 @@ public class DocValuesCodec extends Codec {this.docValues.iter = docValues;this.fieldsEnum.value = wrapped;coordinator = null;-}@Override@@ -268,7 +268,6 @@ public class DocValuesCodec extends Codec {public String next() throws IOException {if (coordinator == null) {coordinator = fieldsEnum.next().smaller(docValues.next());- // old = coordinator.name;} else {String current = coordinator.name;if (current == docValues.name) {@@ -281,16 +280,15 @@ public class DocValuesCodec extends Codec {}return coordinator == null ? null : coordinator.name;-}@Overridepublic TermsEnum terms() throws IOException {- if (fieldsEnum.name == coordinator.name)+ if (fieldsEnum.name == coordinator.name) {return fieldsEnum.value.terms();+ }return null;}-}}diff --git a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodecInfo.java b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodecInfo.javanew file mode 100644index 00000000000..cbe9ca6c0fd--- /dev/null+++ b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodecInfo.java@@ -0,0 +1,119 @@+package org.apache.lucene.index.codecs.docvalues;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import java.io.IOException;+import java.util.Set;++import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.index.SegmentInfo;+import org.apache.lucene.index.SegmentWriteState;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.IntsRef;+import org.apache.lucene.util.packed.PackedInts;+import org.apache.lucene.util.packed.PackedInts.Reader;+import org.apache.lucene.util.packed.PackedInts.Writer;++/**+ * @lucene.internal+ */+class DocValuesCodecInfo {+ public static final int FORMAT_CURRENT = 0;+ static final String INFO_FILE_EXT = "inf";+ private int[] docValuesFields = new int[1];+ private int max;+ private int pos;++ public DocValuesCodecInfo() {+ }++ void add(int fieldId) {+ if (pos >= docValuesFields.length) {+ docValuesFields = ArrayUtil.grow(docValuesFields, pos + 1);+ }+ docValuesFields[pos++] = fieldId;+ if (fieldId > max) {+ max = fieldId;+ }+ }++ String docValuesId(String segmentsName, String codecID, String fieldId) {+ return segmentsName + "_" + codecID + "-" + fieldId;+ }++ void files(Directory dir, SegmentInfo segmentInfo, String codecId,+ Set<String> files) throws IOException {+ final String file = IndexFileNames.segmentFileName(segmentInfo.name, codecId,+ INFO_FILE_EXT);+ files.add(file);+ for (int i = 0; i < pos; i++) {+ int field = docValuesFields[i];+ String docValuesID = docValuesId(segmentInfo.name, codecId, "" + field);+ files.add(IndexFileNames.segmentFileName(docValuesID, "",+ org.apache.lucene.index.values.Writer.DATA_EXTENSION));+ String idxFile = IndexFileNames.segmentFileName(docValuesID, "",+ org.apache.lucene.index.values.Writer.INDEX_EXTENSION);+ if (dir.fileExists(idxFile)) {+ files.add(idxFile);+ }+ }+ }++ void write(SegmentWriteState state) throws IOException {+ final String fileName = IndexFileNames.segmentFileName(state.segmentName,+ state.codecId, INFO_FILE_EXT);+ final IndexOutput out = state.directory.createOutput(fileName);+ state.flushedFiles.add(fileName);+ try {+ out.writeInt(FORMAT_CURRENT);+ Writer writer = PackedInts.getWriter(out, pos, PackedInts+ .bitsRequired(max));+ for (int i = 0; i < pos; i++) {+ writer.add(docValuesFields[i]);+ }+ writer.finish();+ } finally {+ out.close();+ }++ }++ void read(Directory directory, SegmentInfo info, String codecId)+ throws IOException {+ final String fileName = IndexFileNames.segmentFileName(info.name, codecId,+ INFO_FILE_EXT);+ final IndexInput in = directory.openInput(fileName);+ try {+ in.readInt();+ final Reader reader = PackedInts.getReader(in);+ docValuesFields = new int[reader.size()];+ for (int i = 0; i < docValuesFields.length; i++) {+ docValuesFields[i] = (int) reader.get(i);+ }+ pos = docValuesFields.length;+ } finally {+ in.close();+ }+ }++ IntsRef fieldIDs() {+ return new IntsRef(docValuesFields, 0, pos);+ }+}diff --git a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesConsumer.java b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesConsumer.javaindex 3d39701779d..5f9cd9702b9 100644--- a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesConsumer.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesConsumer.java@@ -88,10 +88,9 @@ public abstract class DocValuesConsumer {}}- public static DocValuesConsumer create(String segmentName,- Directory directory, FieldInfo field, String codecId, Comparator<BytesRef> comp)+ public static DocValuesConsumer create(String id,+ Directory directory, FieldInfo field, Comparator<BytesRef> comp)throws IOException {- final String id = segmentName + "_" + codecId;return Writer.create(field.getDocValues(), id, directory, comp);}}diff --git a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.java b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.javaindex 426f9277894..adf9349e766 100644--- a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.java@@ -31,12 +31,15 @@ import org.apache.lucene.index.values.Ints;import org.apache.lucene.index.values.Values;import org.apache.lucene.index.values.Writer;import org.apache.lucene.store.Directory;+import org.apache.lucene.util.IntsRef;public abstract class DocValuesProducerBase extends FieldsProducer{protected final TreeMap<String, DocValues> docValues = new TreeMap<String, DocValues>();+ private final DocValuesCodecInfo info = new DocValuesCodecInfo();protected DocValuesProducerBase(SegmentInfo si, Directory dir, FieldInfos fieldInfo, String codecId) throws IOException {+ info.read(dir, si, codecId);load(fieldInfo, si.name, si.docCount, dir, codecId);}@@ -48,16 +51,15 @@ public abstract class DocValuesProducerBase extends FieldsProducer{// Only opens files... doesn't actually load any valuesprotected void load(FieldInfos fieldInfos, String segment, int docCount,Directory dir, String codecId) throws IOException {- final int numFields = fieldInfos.size();- for (int i = 0; i < numFields; i++) {- final FieldInfo fieldInfo = fieldInfos.fieldInfo(i);- final Values v = fieldInfo.getDocValues();+ final IntsRef valueFields = info.fieldIDs();+ for (int i = valueFields.offset; i < valueFields.length; i++) {+ final int fieldNumber = valueFields.ints[i];+ final FieldInfo fieldInfo = fieldInfos.fieldInfo(fieldNumber);+ assert fieldInfo.hasDocValues();final String field = fieldInfo.name;//TODO can we have a compound file per segment and codec for docvalues?- final String id = IndexFileNames.segmentFileName(segment, codecId+"-"+fieldInfo.number, "");- if (v != null && dir.fileExists(id + "." + Writer.DATA_EXTENSION)) {- docValues.put(field, loadDocValues(docCount, dir, id, v));- }+ final String id = info.docValuesId( segment, codecId, fieldNumber+"");+ docValues.put(field, loadDocValues(docCount, dir, id, fieldInfo.getDocValues()));}}@@ -66,8 +68,6 @@ public abstract class DocValuesProducerBase extends FieldsProducer{switch (v) {case PACKED_INTS:return Ints.getValues(dir, id, false);- case PACKED_INTS_FIXED:- return Ints.getValues(dir, id, true);case SIMPLE_FLOAT_4BYTE:return Floats.getValues(dir, id, docCount);case SIMPLE_FLOAT_8BYTE:diff --git a/lucene/src/java/org/apache/lucene/index/values/Bytes.java b/lucene/src/java/org/apache/lucene/index/values/Bytes.javaindex 70343ca1eca..f9eeff57093 100644--- a/lucene/src/java/org/apache/lucene/index/values/Bytes.java+++ b/lucene/src/java/org/apache/lucene/index/values/Bytes.java@@ -24,11 +24,14 @@ import java.util.Comparator;import java.util.concurrent.atomic.AtomicLong;import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.index.values.DocValues.MissingValues;import org.apache.lucene.index.values.DocValues.SortedSource;import org.apache.lucene.index.values.DocValues.Source;+import org.apache.lucene.index.values.DocValues.SourceEnum;import org.apache.lucene.store.Directory;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.ByteBlockPool;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.CodecUtil;@@ -88,7 +91,7 @@ public final class Bytes {throw new IllegalArgumentException("");}- // nocommit -- I can peek @ header to determing fixed/mode?+ // TODO -- I can peek @ header to determing fixed/mode?public static DocValues getValues(Directory dir, String id, Mode mode,boolean fixedSize, int maxDoc) throws IOException {if (fixedSize) {@@ -123,15 +126,15 @@ public final class Bytes {static abstract class BytesBaseSource extends Source {protected final IndexInput datIn;protected final IndexInput idxIn;- protected final BytesRef defaultValue = new BytesRef();protected final static int PAGED_BYTES_BITS = 15;private final PagedBytes pagedBytes;protected final PagedBytes.Reader data;protected final long totalLengthInBytes;- protected BytesBaseSource(IndexInput datIn, IndexInput idxIn, PagedBytes pagedBytes, long bytesToRead)- throws IOException {- assert bytesToRead <= datIn.length() : " file size is less than the expected size diff: " + (bytesToRead - datIn.length()) + " pos: " + datIn.getFilePointer();+ protected BytesBaseSource(IndexInput datIn, IndexInput idxIn,+ PagedBytes pagedBytes, long bytesToRead) throws IOException {+ assert bytesToRead <= datIn.length() : " file size is less than the expected size diff: "+ + (bytesToRead - datIn.length()) + " pos: " + datIn.getFilePointer();this.datIn = datIn;this.totalLengthInBytes = bytesToRead;this.pagedBytes = pagedBytes;@@ -146,12 +149,36 @@ public final class Bytes {if (datIn != null)datIn.close();} finally {- if (idxIn != null) // if straight+ if (idxIn != null) // if straight - no index neededidxIn.close();}}++ protected abstract int maxDoc();+public long ramBytesUsed() {- return 0; //TOODO+ return 0; // TODO+ }++ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValues missing = getMissing();+ return new SourceEnum(attrSource, type(), this, maxDoc()) {+ final BytesRef bytesRef = attr.bytes();++ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ while (source.getBytes(target, bytesRef) == missing.bytesValue) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }+ return pos = target;+ }+ };}}@@ -163,13 +190,14 @@ public final class Bytes {protected final static int PAGED_BYTES_BITS = 15;private final PagedBytes pagedBytes;protected final PagedBytes.Reader data;- protected final BytesRef bytesRef = new BytesRef();protected final LookupResult lookupResult = new LookupResult();private final Comparator<BytesRef> comp;-- protected BytesBaseSortedSource(IndexInput datIn, IndexInput idxIn, Comparator<BytesRef> comp, PagedBytes pagedBytes, long bytesToRead) throws IOException {- assert bytesToRead <= datIn.length() : " file size is less than the expected size diff: " + (bytesToRead - datIn.length()) + " pos: " + datIn.getFilePointer();+ protected BytesBaseSortedSource(IndexInput datIn, IndexInput idxIn,+ Comparator<BytesRef> comp, PagedBytes pagedBytes, long bytesToRead)+ throws IOException {+ assert bytesToRead <= datIn.length() : " file size is less than the expected size diff: "+ + (bytesToRead - datIn.length()) + " pos: " + datIn.getFilePointer();this.datIn = datIn;this.pagedBytes = pagedBytes;this.pagedBytes.copy(datIn, bytesToRead);@@ -177,12 +205,12 @@ public final class Bytes {this.idxIn = idxIn;this.comp = comp == null ? BytesRef.getUTF8SortedAsUnicodeComparator(): comp;-+}-+@Override- public BytesRef getByOrd(int ord) {- return ord == 0 ? defaultValue : deref(--ord);+ public BytesRef getByOrd(int ord, BytesRef bytesRef) {+ return ord == 0 ? null : deref(--ord, bytesRef);}public void close() throws IOException {@@ -191,14 +219,16 @@ public final class Bytes {if (idxIn != null) // if straightidxIn.close();}-- protected abstract BytesRef deref(int ord);-- protected LookupResult binarySearch(BytesRef b, int low, int high) {+ protected abstract int maxDoc();++ protected abstract BytesRef deref(int ord, BytesRef bytesRef);++ protected LookupResult binarySearch(BytesRef b, BytesRef bytesRef, int low,+ int high) {while (low <= high) {int mid = (low + high) >>> 1;- deref(mid);+ deref(mid, bytesRef);final int cmp = comp.compare(bytesRef, b);if (cmp < 0) {low = mid + 1;@@ -215,6 +245,27 @@ public final class Bytes {lookupResult.found = false;return lookupResult;}++ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValues missing = getMissing();+ return new SourceEnum(attrSource, type(), this, maxDoc()) {+ final BytesRef bytesRef = attr.bytes();++ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ while (source.getBytes(target, bytesRef) == missing.bytesValue) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }+ return pos = target;+ }+ };+ }}static abstract class BytesWriterBase extends Writer {@@ -243,16 +294,16 @@ public final class Bytes {if (initIndex)initIndexOut();}-+protected void initDataOut() throws IOException {datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_DATA_EXTENSION));+ DATA_EXTENSION));CodecUtil.writeHeader(datOut, codecName, version);}protected void initIndexOut() throws IOException {idxOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_INDEX_EXTENSION));+ INDEX_EXTENSION));CodecUtil.writeHeader(idxOut, codecName, version);}@@ -299,12 +350,11 @@ public final class Bytes {@Overridepublic void files(Collection<String> files) throws IOException {assert datOut != null;- files.add(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_DATA_EXTENSION));+ files.add(IndexFileNames.segmentFileName(id, "", DATA_EXTENSION));if (idxOut != null) { // called after flush - so this must be initialized- // if needed or present+ // if needed or presentfinal String idxFile = IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_INDEX_EXTENSION);+ INDEX_EXTENSION);files.add(idxFile);}}@@ -324,12 +374,12 @@ public final class Bytes {int maxVersion, boolean doIndex) throws IOException {this.id = id;datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_DATA_EXTENSION));+ Writer.DATA_EXTENSION));version = CodecUtil.checkHeader(datIn, codecName, maxVersion, maxVersion);if (doIndex) {idxIn = dir.openInput(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_INDEX_EXTENSION));+ Writer.INDEX_EXTENSION));final int version2 = CodecUtil.checkHeader(idxIn, codecName,maxVersion, maxVersion);assert version == version2;@@ -345,7 +395,7 @@ public final class Bytes {}protected final IndexInput cloneIndex() { // TODO assert here for null- // rather than return null+ // rather than return nullreturn idxIn == null ? null : (IndexInput) idxIn.clone();}diff --git a/lucene/src/java/org/apache/lucene/index/values/DocValues.java b/lucene/src/java/org/apache/lucene/index/values/DocValues.javaindex 2ed2192f831..a0d84ff1d79 100644--- a/lucene/src/java/org/apache/lucene/index/values/DocValues.java+++ b/lucene/src/java/org/apache/lucene/index/values/DocValues.java@@ -40,8 +40,9 @@ public abstract class DocValues implements Closeable {public Source getSource() throws IOException {return cache.load(this);}-- public SortedSource getSortedSorted(Comparator<BytesRef> comparator) throws IOException {++ public SortedSource getSortedSorted(Comparator<BytesRef> comparator)+ throws IOException {return cache.laodSorted(this, comparator);}@@ -51,7 +52,7 @@ public abstract class DocValues implements Closeable {}public abstract Values type();-+public void close() throws IOException {this.cache.close(this);}@@ -69,6 +70,7 @@ public abstract class DocValues implements Closeable {* used since it can handle all precisions.*/public static abstract class Source {+ protected final MissingValues missingValues = new MissingValues();public long getInt(int docID) {throw new UnsupportedOperationException("ints are not supported");@@ -78,7 +80,7 @@ public abstract class DocValues implements Closeable {throw new UnsupportedOperationException("floats are not supported");}- public BytesRef getBytes(int docID) {+ public BytesRef getBytes(int docID, BytesRef ref) {throw new UnsupportedOperationException("bytes are not supported");}@@ -91,24 +93,56 @@ public abstract class DocValues implements Closeable {}public ValuesEnum getEnum() throws IOException {- return getEnum(null);+ return getEnum(new AttributeSource());}-- // nocommit - enable obtaining enum from source since this is already in- // memory- public/* abstract */ValuesEnum getEnum(AttributeSource attrSource)- throws IOException {- throw new UnsupportedOperationException();++ public MissingValues getMissing() {+ return missingValues;}++ public abstract Values type();++ public abstract ValuesEnum getEnum(AttributeSource attrSource)+ throws IOException;public abstract long ramBytesUsed();++ }++ abstract static class SourceEnum extends ValuesEnum {+ protected final Source source;+ protected final int numDocs;+ protected int pos = -1;++ SourceEnum(AttributeSource attrs, Values type, Source source, int numDocs) {+ super(attrs, type);++ this.source = source;+ this.numDocs = numDocs;+ }++ @Override+ public void close() throws IOException {+ }++ @Override+ public int docID() {+ return pos;+ }++ @Override+ public int nextDoc() throws IOException {+ if(pos == NO_MORE_DOCS)+ return NO_MORE_DOCS;+ return advance(pos + 1);+ }}public static abstract class SortedSource extends Source {@Override- public BytesRef getBytes(int docID) {- return getByOrd(ord(docID));+ public BytesRef getBytes(int docID, BytesRef bytesRef) {+ return getByOrd(ord(docID), bytesRef);}/**@@ -119,7 +153,7 @@ public abstract class DocValues implements Closeable {public abstract int ord(int docID);/** Returns value for specified ord. */- public abstract BytesRef getByOrd(int ord);+ public abstract BytesRef getByOrd(int ord, BytesRef bytesRef);public static class LookupResult {public boolean found;@@ -131,7 +165,22 @@ public abstract class DocValues implements Closeable {* {@link LookupResult#found} is true, then ord is an exact match. The* returned {@link LookupResult} may be reused across calls.*/- public abstract LookupResult getByValue(BytesRef value);+ public final LookupResult getByValue(BytesRef value) {+ return getByValue(value, new BytesRef());+ }+ public abstract LookupResult getByValue(BytesRef value, BytesRef tmpRef);}+ public final static class MissingValues {+ public long longValue;+ public double doubleValue;+ public BytesRef bytesValue;++ public final void copy(MissingValues values) {+ longValue = values.longValue;+ doubleValue = values.doubleValue;+ bytesValue = values.bytesValue;+ }+ }+}diff --git a/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java b/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.javaindex 3be9918d55d..06a322b9972 100644--- a/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java@@ -49,7 +49,7 @@ class FixedDerefBytesImpl {private int size = -1;private int[] docToID;private final BytesRefHash hash = new BytesRefHash(pool);-+public Writer(Directory dir, String id) throws IOException {this(dir, id, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE),new AtomicLong());@@ -65,7 +65,7 @@ class FixedDerefBytesImpl {@Overridesynchronized public void add(int docID, BytesRef bytes) throws IOException {- if(bytes.length == 0) // default value - skip it+ if (bytes.length == 0) // default value - skip itreturn;if (size == -1) {size = bytes.length;@@ -81,18 +81,18 @@ class FixedDerefBytesImpl {// new added entrydatOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);} else {- ord = (-ord)-1;+ ord = (-ord) - 1;}if (docID >= docToID.length) {int size = docToID.length;docToID = ArrayUtil.grow(docToID, 1 + docID);- bytesUsed.addAndGet((docToID.length - size) * RamUsageEstimator.NUM_BYTES_INT);+ bytesUsed.addAndGet((docToID.length - size)+ * RamUsageEstimator.NUM_BYTES_INT);}- docToID[docID] = 1+ord;+ docToID[docID] = 1 + ord;}-// Important that we get docCount, in case there were// some last docs that we didn't see@Override@@ -100,7 +100,7 @@ class FixedDerefBytesImpl {if (datOut == null) // no added datareturn;initIndexOut();- final int count = 1+hash.size();+ final int count = 1 + hash.size();idxOut.writeInt(count - 1);// write indexfinal PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,@@ -135,17 +135,16 @@ class FixedDerefBytesImpl {@Overridepublic Source load() throws IOException {final IndexInput index = cloneIndex();- return new Source(cloneData(), index , size, index.readInt());+ return new Source(cloneData(), index, size, index.readInt());}private static class Source extends BytesBaseSource {- private final BytesRef bytesRef = new BytesRef();private final PackedInts.Reader index;private final int size;private final int numValues;- protected Source(IndexInput datIn, IndexInput idxIn, int size, int numValues)- throws IOException {+ protected Source(IndexInput datIn, IndexInput idxIn, int size,+ int numValues) throws IOException {super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), size * numValues);this.size = size;this.numValues = numValues;@@ -153,24 +152,33 @@ class FixedDerefBytesImpl {}@Override- public BytesRef getBytes(int docID) {+ public BytesRef getBytes(int docID, BytesRef bytesRef) {final int id = (int) index.get(docID);if (id == 0) {- return defaultValue;+ return null;}return data.fill(bytesRef, ((id - 1) * size), size);}-@Overridepublic int getValueCount() {return numValues;}++ @Override+ public Values type() {+ return Values.BYTES_FIXED_DEREF;+ }++ @Override+ protected int maxDoc() {+ return index.size();+ }}@Overridepublic ValuesEnum getEnum(AttributeSource source) throws IOException {- return new DerefBytesEnum(source, cloneData(), cloneIndex(), CODEC_NAME,+ return new DerefBytesEnum(source, cloneData(), cloneIndex(),size);}@@ -184,12 +192,12 @@ class FixedDerefBytesImpl {private int pos = -1;public DerefBytesEnum(AttributeSource source, IndexInput datIn,- IndexInput idxIn, String codecName, int size) throws IOException {- this(source, datIn, idxIn, codecName, size, Values.BYTES_FIXED_DEREF);+ IndexInput idxIn, int size) throws IOException {+ this(source, datIn, idxIn, size, Values.BYTES_FIXED_DEREF);}protected DerefBytesEnum(AttributeSource source, IndexInput datIn,- IndexInput idxIn, String codecName, int size, Values enumType)+ IndexInput idxIn, int size, Values enumType)throws IOException {super(source, enumType);ref = attr.bytes();@@ -207,14 +215,13 @@ class FixedDerefBytesImpl {@Overridepublic int advance(int target) throws IOException {if (target < valueCount) {- final long address = idx.advance(target);- pos = idx.ord();- if(address == 0) {- // default is empty- ref.length = 0;- ref.offset = 0;- return pos;+ long address;+ while ((address = idx.advance(target)) == 0) {+ if (++target >= valueCount) {+ return pos = NO_MORE_DOCS;+ }}+ pos = idx.ord();fill(address, ref);return pos;}@@ -223,6 +230,9 @@ class FixedDerefBytesImpl {@Overridepublic int nextDoc() throws IOException {+ if (pos < valueCount) {+ return pos = NO_MORE_DOCS;+ }return advance(pos + 1);}diff --git a/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java b/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.javaindex e445cfb29bd..e826a709ee9 100644--- a/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java@@ -187,8 +187,6 @@ class FixedSortedBytesImpl {this.size = size;this.numValue = numValues;index = PackedInts.getReader(idxIn);-- bytesRef.length = size;}@Override@@ -197,8 +195,8 @@ class FixedSortedBytesImpl {}@Override- public LookupResult getByValue(BytesRef bytes) {- return binarySearch(bytes, 0, numValue - 1);+ public LookupResult getByValue(BytesRef bytes, BytesRef tmpRef) {+ return binarySearch(bytes, tmpRef, 0, numValue - 1);}public long ramBytesUsed() {@@ -216,15 +214,25 @@ class FixedSortedBytesImpl {return numValue;}@Override- protected BytesRef deref(int ord) {+ protected BytesRef deref(int ord, BytesRef bytesRef) {return data.fill(bytesRef, (ord* size), size);}++ @Override+ public Values type() {+ return Values.BYTES_FIXED_SORTED;+ }++ @Override+ protected int maxDoc() {+ return index.size();+ }}@Overridepublic ValuesEnum getEnum(AttributeSource source) throws IOException {// do unsorted- return new DerefBytesEnum(source, cloneData(), cloneIndex(), CODEC_NAME,+ return new DerefBytesEnum(source, cloneData(), cloneIndex(),size);}diff --git a/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java b/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.javaindex 202947c5eef..1ee7b6e996a 100644--- a/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java@@ -47,7 +47,7 @@ class FixedStraightBytesImpl {super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false, null, null);}- // nocommit - impl bulk copy here!+ // TODO - impl bulk copy here!@Overridesynchronized public void add(int docID, BytesRef bytes) throws IOException {@@ -133,16 +133,18 @@ class FixedStraightBytesImpl {}private static class Source extends BytesBaseSource {- private final BytesRef bytesRef = new BytesRef();private final int size;+ private final int maxDoc;public Source(IndexInput datIn, IndexInput idxIn, int size, int maxDoc) throws IOException {super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), size*maxDoc);this.size = size;+ this.missingValues.bytesValue = new BytesRef(size);+ this.maxDoc = maxDoc;}@Override- public BytesRef getBytes(int docID) {+ public BytesRef getBytes(int docID, BytesRef bytesRef) {return data.fill(bytesRef, docID * size, size);}@@ -150,6 +152,16 @@ class FixedStraightBytesImpl {public int getValueCount() {throw new UnsupportedOperationException();}++ @Override+ public Values type() {+ return Values.BYTES_FIXED_STRAIGHT;+ }++ @Override+ protected int maxDoc() {+ return maxDoc;+ }}@Override@@ -184,8 +196,6 @@ class FixedStraightBytesImpl {@Overridepublic int advance(int target) throws IOException {if(target >= maxDoc){- ref.length = 0;- ref.offset = 0;return pos = NO_MORE_DOCS;}if((target-1) != pos) // pos inc == 1@@ -201,6 +211,9 @@ class FixedStraightBytesImpl {@Overridepublic int nextDoc() throws IOException {+ if(pos >= maxDoc){+ return pos = NO_MORE_DOCS;+ }return advance(pos+1);}}diff --git a/lucene/src/java/org/apache/lucene/index/values/Floats.java b/lucene/src/java/org/apache/lucene/index/values/Floats.javaindex f844bba40e4..dcf984b0774 100644--- a/lucene/src/java/org/apache/lucene/index/values/Floats.java+++ b/lucene/src/java/org/apache/lucene/index/values/Floats.java@@ -19,13 +19,15 @@ import org.apache.lucene.util.RamUsageEstimator;* Exposes writer/reader for floating point values. You can specify 4 (java* float) or 8 (java double) byte precision.*/-//TODO - add bulk copy where possible+// TODO - add bulk copy where possiblepublic class Floats {private static final String CODEC_NAME = "SimpleFloats";static final int VERSION_START = 0;static final int VERSION_CURRENT = VERSION_START;- private static final int INT_ZERO = Float.floatToRawIntBits(0.0f);- private static final long LONG_ZERO = Double.doubleToRawLongBits(0.0);+ private static final int INT_DEFAULT = Float+ .floatToRawIntBits(Float.NEGATIVE_INFINITY);+ private static final long LONG_DEFAULT = Double+ .doubleToRawLongBits(Double.NEGATIVE_INFINITY);public static Writer getWriter(Directory dir, String id, int precisionBytes)throws IOException {@@ -47,7 +49,6 @@ public class Floats {abstract static class FloatsWriter extends Writer {-private final Directory dir;private final String id;private FloatsRef floatsRef;@@ -64,7 +65,7 @@ public class Floats {protected void initDatOut() throws IOException {datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_DATA_EXTENSION));+ Writer.DATA_EXTENSION));CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);assert datOut.getFilePointer() == CodecUtil.headerLength(CODEC_NAME);datOut.writeByte(precision);@@ -78,12 +79,12 @@ public class Floats {protected void add(int docID) throws IOException {add(docID, floatsRef.get());}-+@Overridepublic void add(int docID, ValuesAttribute attr) throws IOException {final FloatsRef ref;- if((ref = attr.floats()) != null)- add(docID, ref.get());+ if ((ref = attr.floats()) != null)+ add(docID, ref.get());}@Override@@ -113,14 +114,12 @@ public class Floats {} elsesuper.merge(state);}-+@Overridepublic void files(Collection<String> files) throws IOException {- files.add(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_DATA_EXTENSION));+ files.add(IndexFileNames.segmentFileName(id, "", Writer.DATA_EXTENSION));}-}// Writes 4 bytes (float) per value@@ -153,7 +152,7 @@ public class Floats {return; // no data added - don't create file!if (docCount > lastDocId + 1)for (int i = lastDocId; i < docCount; i++) {- datOut.writeInt(INT_ZERO); // default value+ datOut.writeInt(INT_DEFAULT); // default value}datOut.close();}@@ -161,7 +160,7 @@ public class Floats {@Overrideprotected int fillDefault(int numValues) throws IOException {for (int i = 0; i < numValues; i++) {- datOut.writeInt(INT_ZERO);+ datOut.writeInt(INT_DEFAULT);}return numValues;}@@ -196,7 +195,7 @@ public class Floats {return; // no data added - don't create file!if (docCount > lastDocId + 1)for (int i = lastDocId; i < docCount; i++) {- datOut.writeLong(LONG_ZERO); // default value+ datOut.writeLong(LONG_DEFAULT); // default value}datOut.close();}@@ -204,7 +203,7 @@ public class Floats {@Overrideprotected int fillDefault(int numValues) throws IOException {for (int i = 0; i < numValues; i++) {- datOut.writeLong(LONG_ZERO);+ datOut.writeLong(LONG_DEFAULT);}return numValues;}@@ -224,7 +223,7 @@ public class Floats {protected FloatsReader(Directory dir, String id, int maxDoc)throws IOException {datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_DATA_EXTENSION));+ Writer.DATA_EXTENSION));CodecUtil.checkHeader(datIn, CODEC_NAME, VERSION_START, VERSION_START);precisionBytes = datIn.readByte();assert precisionBytes == 4 || precisionBytes == 8;@@ -266,19 +265,43 @@ public class Floats {Source4(ByteBuffer buffer) {values = buffer.asFloatBuffer();+ missingValues.doubleValue = Float.NEGATIVE_INFINITY;}@Overridepublic double getFloat(int docID) {- final float f = values.get(docID);- // nocommit should we return NaN as default instead of 0.0?- return Float.isNaN(f) ? 0.0f : f;+ return values.get(docID);}public long ramBytesUsed() {return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.limit()* RamUsageEstimator.NUM_BYTES_FLOAT;}++ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValues missing = getMissing();+ return new SourceEnum(attrSource, Values.SIMPLE_FLOAT_4BYTE, this, maxDoc) {+ private final FloatsRef ref = attr.floats();+ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs)+ return pos = NO_MORE_DOCS;+ while (missing.doubleValue == source.getFloat(target)) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }+ ref.floats[ref.offset] = source.getFloat(target);+ return pos = target;+ }+ };+ }++ @Override+ public Values type() {+ return Values.SIMPLE_FLOAT_4BYTE;+ }}private class Source8 extends Source {@@ -286,19 +309,44 @@ public class Floats {Source8(ByteBuffer buffer) {values = buffer.asDoubleBuffer();+ missingValues.doubleValue = Double.NEGATIVE_INFINITY;+}@Overridepublic double getFloat(int docID) {- final double d = values.get(docID);- // TODO should we return NaN as default instead of 0.0?- return Double.isNaN(d) ? 0.0d : d;+ return values.get(docID);}public long ramBytesUsed() {return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.limit()* RamUsageEstimator.NUM_BYTES_DOUBLE;}++ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValues missing = getMissing();+ return new SourceEnum(attrSource, type(), this, maxDoc) {+ private final FloatsRef ref = attr.floats();+ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs)+ return pos = NO_MORE_DOCS;+ while (missing.doubleValue == source.getFloat(target)) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }+ ref.floats[ref.offset] = source.getFloat(target);+ return pos = target;+ }+ };+ }++ @Override+ public Values type() {+ return Values.SIMPLE_FLOAT_8BYTE;+ }}@Override@@ -316,7 +364,7 @@ public class Floats {return precisionBytes == 4 ? new Floats4Enum(source, indexInput, maxDoc): new Floats8EnumImpl(source, indexInput, maxDoc);}-+@Overridepublic Values type() {return precisionBytes == 4 ? Values.SIMPLE_FLOAT_4BYTE@@ -336,8 +384,13 @@ public class Floats {if (target >= maxDoc)return pos = NO_MORE_DOCS;dataIn.seek(fp + (target * precision));- ref.floats[0] = Float.intBitsToFloat(dataIn.readInt());- ref.offset = 0; // nocommit -- can we igore this?+ int intBits;+ while ((intBits = dataIn.readInt()) == INT_DEFAULT) {+ if (++target >= maxDoc)+ return pos = NO_MORE_DOCS;+ }+ ref.floats[0] = Float.intBitsToFloat(intBits);+ ref.offset = 0;return pos = target;}@@ -348,6 +401,9 @@ public class Floats {@Overridepublic int nextDoc() throws IOException {+ if (pos >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }return advance(pos + 1);}}@@ -361,11 +417,17 @@ public class Floats {@Overridepublic int advance(int target) throws IOException {- if (target >= maxDoc)+ if (target >= maxDoc) {return pos = NO_MORE_DOCS;+ }dataIn.seek(fp + (target * precision));- ref.floats[0] = Double.longBitsToDouble(dataIn.readLong());- ref.offset = 0; // nocommit -- can we igore this?+ long value;+ while ((value = dataIn.readLong()) == LONG_DEFAULT) {+ if (++target >= maxDoc)+ return pos = NO_MORE_DOCS;+ }+ ref.floats[0] = Double.longBitsToDouble(value);+ ref.offset = 0;return pos = target;}@@ -376,6 +438,9 @@ public class Floats {@Overridepublic int nextDoc() throws IOException {+ if (pos >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }return advance(pos + 1);}}diff --git a/lucene/src/java/org/apache/lucene/index/values/MultiDocValues.java b/lucene/src/java/org/apache/lucene/index/values/MultiDocValues.javaindex 0c458cf205e..d1780936f5c 100644--- a/lucene/src/java/org/apache/lucene/index/values/MultiDocValues.java+++ b/lucene/src/java/org/apache/lucene/index/values/MultiDocValues.java@@ -21,8 +21,6 @@ import java.util.Arrays;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.BytesRef;-import org.apache.lucene.util.FloatsRef;-import org.apache.lucene.util.LongsRef;import org.apache.lucene.util.ReaderUtil;public class MultiDocValues extends DocValues {@@ -78,27 +76,26 @@ public class MultiDocValues extends DocValues {public static class DummyDocValues extends DocValues {final int maxDoc;- final Values type;- static final Source DUMMY = new DummySource();+ final Source emptySoruce;public DummyDocValues(int maxDoc, Values type) {- this.type = type;this.maxDoc = maxDoc;+ this.emptySoruce = new EmptySource(type);}@Overridepublic ValuesEnum getEnum(AttributeSource attrSource) throws IOException {- return new DummyEnum(attrSource, maxDoc, type);+ return emptySoruce.getEnum(attrSource);}@Overridepublic Source load() throws IOException {- return DUMMY;+ return emptySoruce;}-+@Overridepublic Values type() {- return type;+ return emptySoruce.type();}public void close() throws IOException {@@ -177,6 +174,7 @@ public class MultiDocValues extends DocValues {public MultiSource(DocValuesIndex[] docValuesIdx, int[] starts) {this.docValuesIdx = docValuesIdx;this.starts = starts;+ assert docValuesIdx.length != 0;}@@ -193,7 +191,8 @@ public class MultiDocValues extends DocValues {+ " for doc id: " + docID + " slices : " + Arrays.toString(starts);assert docValuesIdx[idx] != null;try {- current = docValuesIdx[idx].docValues.load();+ current = docValuesIdx[idx].docValues.getSource();+ missingValues.copy(current.getMissing());} catch (IOException e) {throw new RuntimeException("load failed", e); // TODO how should we// handle this@@ -211,92 +210,62 @@ public class MultiDocValues extends DocValues {return current.getFloat(doc);}- public BytesRef getBytes(int docID) {+ public BytesRef getBytes(int docID, BytesRef bytesRef) {final int doc = ensureSource(docID);- return current.getBytes(doc);+ return current.getBytes(doc, bytesRef);}public long ramBytesUsed() {return current.ramBytesUsed();}- }-- private static class DummySource extends Source {- private final BytesRef ref = new BytesRef();-@Override- public BytesRef getBytes(int docID) {- return ref;+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ throw new UnsupportedOperationException(); // TODO}@Override- public double getFloat(int docID) {- return 0.0d;+ public Values type() {+ return docValuesIdx[0].docValues.type();}- @Override- public long getInt(int docID) {- return 0;- }+ }- public long ramBytesUsed() {- return 0;+ private static class EmptySource extends Source {+ private final Values type;++ public EmptySource(Values type) {+ this.type = type;}- }- private static class DummyEnum extends ValuesEnum {- private int pos = -1;- private final int maxDoc;+ @Override+ public BytesRef getBytes(int docID, BytesRef ref) {+ return this.missingValues.bytesValue;- public DummyEnum(AttributeSource source, int maxDoc, Values type) {- super(source, type);- this.maxDoc = maxDoc;- switch (type) {- case BYTES_VAR_STRAIGHT:- case BYTES_FIXED_STRAIGHT:- case BYTES_FIXED_DEREF:- case BYTES_FIXED_SORTED:- case BYTES_VAR_DEREF:- case BYTES_VAR_SORTED:- // nocommit - this is not correct for Fixed_straight- BytesRef bytes = attr.bytes();- bytes.length = 0;- bytes.offset = 0;- break;- case PACKED_INTS:- case PACKED_INTS_FIXED:- LongsRef ints = attr.ints();- ints.set(0);- break;-- case SIMPLE_FLOAT_4BYTE:- case SIMPLE_FLOAT_8BYTE:- FloatsRef floats = attr.floats();- floats.set(0d);- break;- default:- throw new IllegalArgumentException("unknown Values type: " + type);- }}@Override- public void close() throws IOException {+ public double getFloat(int docID) {+ return missingValues.doubleValue;}@Override- public int advance(int target) throws IOException {- return pos = (pos < maxDoc ? target : NO_MORE_DOCS);+ public long getInt(int docID) {+ return missingValues.longValue;+ }++ public long ramBytesUsed() {+ return 0;}@Override- public int docID() {- return pos;+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ return ValuesEnum.emptyEnum(type);}@Override- public int nextDoc() throws IOException {- return advance(pos + 1);+ public Values type() {+ return type;}}diff --git a/lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.java b/lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.javaindex f37f7bbbdff..91f56bdd660 100644--- a/lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.java@@ -20,6 +20,7 @@ import java.io.IOException;import java.util.Collection;import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.index.values.DocValues.MissingValues;import org.apache.lucene.store.Directory;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;@@ -27,6 +28,7 @@ import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.CodecUtil;import org.apache.lucene.util.LongsRef;+import org.apache.lucene.util.OpenBitSet;import org.apache.lucene.util.RamUsageEstimator;import org.apache.lucene.util.packed.PackedInts;@@ -39,7 +41,6 @@ class PackedIntsImpl {static final int VERSION_CURRENT = VERSION_START;static class IntsWriter extends Writer {-// TODO: can we bulkcopy this on a merge?private LongsRef intsRef;@@ -49,8 +50,8 @@ class PackedIntsImpl {private boolean started;private final Directory dir;private final String id;- private int maxDocID;- private int minDocID;+ private OpenBitSet defaultValues = new OpenBitSet(1);+ private int lastDocId = -1;protected IntsWriter(Directory dir, String id) throws IOException {this.dir = dir;@@ -59,54 +60,58 @@ class PackedIntsImpl {}@Override- synchronized public void add(int docID, long v) throws IOException {-+ public synchronized void add(int docID, long v) throws IOException {+ assert lastDocId < docID;if (!started) {- minValue = maxValue = v;- minDocID = maxDocID = docID;started = true;-+ minValue = maxValue = v;} else {if (v < minValue) {minValue = v;} else if (v > maxValue) {maxValue = v;}- if (docID < minDocID) {- minDocID = docID;- } else if (docID > maxDocID) {- maxDocID = docID;- }}+ defaultValues.set(docID);+ lastDocId = docID;+if (docID >= docToValue.length) {docToValue = ArrayUtil.grow(docToValue, 1 + docID);+ defaultValues.ensureCapacity(docToValue.length);+}docToValue[docID] = v;}@Override- synchronized public void finish(int docCount) throws IOException {- if(!started)+ public synchronized void finish(int docCount) throws IOException {+ if (!started)return;final IndexOutput datOut = dir.createOutput(IndexFileNames- .segmentFileName(id, "", IndexFileNames.CSF_DATA_EXTENSION));+ .segmentFileName(id, "", DATA_EXTENSION));CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);- // nocommit -- long can't work right since it's signed+ // TODO -- long can't work right since it's signeddatOut.writeLong(minValue);// write a default value to recognize docs without a value for that fieldfinal long defaultValue = ++maxValue - minValue;datOut.writeLong(defaultValue);- PackedInts.Writer w = PackedInts.getWriter(datOut, docCount, PackedInts.bitsRequired(maxValue-minValue));-- final int limit = maxDocID + 1;- for (int i = 0; i < minDocID; i++) {- w.add(defaultValue);+ PackedInts.Writer w = PackedInts.getWriter(datOut, docCount, PackedInts+ .bitsRequired(maxValue - minValue));+ final int firstDoc = defaultValues.nextSetBit(0);+ assert firstDoc >= 0; // we have at lest one value!+ for (int i = 0; i < firstDoc; i++) {+ w.add(defaultValue); // fill with defaults until first bit set}- for (int i = minDocID; i < limit; i++) {+ lastDocId++;+ for (int i = firstDoc; i < lastDocId;) {w.add(docToValue[i] - minValue);+ final int nextValue = defaultValues.nextSetBit(i);+ for (i++; i < nextValue; i++) {+ w.add(defaultValue); // fill all gaps+ }}- for (int i = limit; i < docCount; i++) {+ for (int i = lastDocId; i < docCount; i++) {w.add(defaultValue);}w.finish();@@ -128,19 +133,18 @@ class PackedIntsImpl {protected void setNextAttribute(ValuesAttribute attr) {intsRef = attr.ints();}-+@Overridepublic void add(int docID, ValuesAttribute attr) throws IOException {final LongsRef ref;- if((ref = attr.ints()) != null) {+ if ((ref = attr.ints()) != null) {add(docID, ref.get());}}@Overridepublic void files(Collection<String> files) throws IOException {- files.add(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_DATA_EXTENSION));+ files.add(IndexFileNames.segmentFileName(id, "", DATA_EXTENSION));}}@@ -153,7 +157,7 @@ class PackedIntsImpl {protected IntsReader(Directory dir, String id) throws IOException {datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",- IndexFileNames.CSF_DATA_EXTENSION));+ Writer.DATA_EXTENSION));CodecUtil.checkHeader(datIn, CODEC_NAME, VERSION_START, VERSION_START);}@@ -176,6 +180,7 @@ class PackedIntsImpl {minValue = dataIn.readLong();defaultValue = dataIn.readLong();values = PackedInts.getReader(dataIn);+ missingValues.longValue = minValue + defaultValue;}@Override@@ -183,9 +188,7 @@ class PackedIntsImpl {// TODO -- can we somehow avoid 2X method calls// on each get? must push minValue down, and make// PackedInts implement Ints.Source- final long val = values.get(docID);- // docs not having a value for that field must return a default value- return val == defaultValue ? 0 : minValue + val;+ return minValue + values.get(docID);}public long ramBytesUsed() {@@ -193,6 +196,31 @@ class PackedIntsImpl {return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER+ values.getBitsPerValue() * values.size();}++ @Override+ public ValuesEnum getEnum(AttributeSource attrSource) throws IOException {+ final MissingValues missing = getMissing();+ return new SourceEnum(attrSource, type(), this, values.size()) {+ private final LongsRef ref = attr.ints();+ @Override+ public int advance(int target) throws IOException {+ if (target >= numDocs)+ return pos = NO_MORE_DOCS;+ while (source.getInt(target) == missing.longValue) {+ if (++target >= numDocs) {+ return pos = NO_MORE_DOCS;+ }+ }+ ref.ints[ref.offset] = source.getInt(target);+ return pos = target;+ }+ };+ }++ @Override+ public Values type() {+ return Values.PACKED_INTS;+ }}@Override@@ -205,7 +233,7 @@ class PackedIntsImpl {public ValuesEnum getEnum(AttributeSource source) throws IOException {return new IntsEnumImpl(source, (IndexInput) datIn.clone());}-+@Overridepublic Values type() {return Values.PACKED_INTS;@@ -243,10 +271,17 @@ class PackedIntsImpl {@Overridepublic int advance(int target) throws IOException {- if (target >= maxDoc)+ if (target >= maxDoc) {return pos = NO_MORE_DOCS;- final long val = ints.advance(target);- ref.ints[0] = val == defaultValue? 0:minValue + val;+ }+ long val = ints.advance(target);+ while (val == defaultValue) {+ if (++target >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }+ val = ints.advance(target);+ }+ ref.ints[0] = minValue + val;ref.offset = 0; // can we skip this?return pos = target;}@@ -258,7 +293,10 @@ class PackedIntsImpl {@Overridepublic int nextDoc() throws IOException {- return advance(pos+1);+ if (pos >= maxDoc) {+ return pos = NO_MORE_DOCS;+ }+ return advance(pos + 1);}}}\ No newline at end of filediff --git a/lucene/src/java/org/apache/lucene/index/values/Values.java b/lucene/src/java/org/apache/lucene/index/values/Values.javaindex d7d613c0510..e33c0cb9b1b 100644--- a/lucene/src/java/org/apache/lucene/index/values/Values.java+++ b/lucene/src/java/org/apache/lucene/index/values/Values.java@@ -30,7 +30,6 @@ public enum Values {* precision is fixed across the segment, and* determined by the min/max values in the field. */PACKED_INTS,- PACKED_INTS_FIXED,SIMPLE_FLOAT_4BYTE,SIMPLE_FLOAT_8BYTE,diff --git a/lucene/src/java/org/apache/lucene/index/values/ValuesAttributeImpl.java b/lucene/src/java/org/apache/lucene/index/values/ValuesAttributeImpl.javaindex 6cd1e0294c7..b69217bcbbe 100644--- a/lucene/src/java/org/apache/lucene/index/values/ValuesAttributeImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/ValuesAttributeImpl.java@@ -6,7 +6,6 @@ import org.apache.lucene.util.AttributeImpl;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.FloatsRef;import org.apache.lucene.util.LongsRef;-import org.apache.lucene.util.SetOnce;public class ValuesAttributeImpl extends AttributeImpl implements ValuesAttribute {private Values type;@@ -45,7 +44,6 @@ public class ValuesAttributeImpl extends AttributeImpl implements ValuesAttributfloats = null;break;case PACKED_INTS:- case PACKED_INTS_FIXED:ints = new LongsRef(new long[1], 0, 1);bytes = null;floats = null;@@ -84,7 +82,6 @@ public class ValuesAttributeImpl extends AttributeImpl implements ValuesAttributother.bytes.copy(bytes);break;case PACKED_INTS:- case PACKED_INTS_FIXED:other.ints.copy(ints);break;case SIMPLE_FLOAT_4BYTE:diff --git a/lucene/src/java/org/apache/lucene/index/values/ValuesEnum.java b/lucene/src/java/org/apache/lucene/index/values/ValuesEnum.javaindex eed33457380..54bc8bf2c7e 100644--- a/lucene/src/java/org/apache/lucene/index/values/ValuesEnum.java+++ b/lucene/src/java/org/apache/lucene/index/values/ValuesEnum.java@@ -21,14 +21,16 @@ import java.io.IOException;import org.apache.lucene.search.DocIdSetIterator;import org.apache.lucene.util.Attribute;import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.FloatsRef;+import org.apache.lucene.util.LongsRef;-public abstract class ValuesEnum extends DocIdSetIterator{+public abstract class ValuesEnum extends DocIdSetIterator {private AttributeSource source;protected final ValuesAttribute attr;-protected ValuesEnum(Values enumType) {- this(null, enumType);+ this(null, enumType);}protected ValuesEnum(AttributeSource source, Values enumType) {@@ -39,6 +41,22 @@ public abstract class ValuesEnum extends DocIdSetIterator{attr.setType(enumType);}+ public Values type() {+ return attr.type();+ }++ public BytesRef bytes() {+ return attr.bytes();+ }++ public FloatsRef getFloat() {+ return attr.floats();+ }++ public LongsRef getInt() {+ return attr.ints();+ }+public AttributeSource attributes() {if (source == null)source = new AttributeSource();@@ -59,4 +77,28 @@ public abstract class ValuesEnum extends DocIdSetIterator{public abstract void close() throws IOException;+ public static ValuesEnum emptyEnum(Values type) {+ return new ValuesEnum(type) {+ @Override+ public int nextDoc() throws IOException {+ return NO_MORE_DOCS;+ }++ @Override+ public int docID() {+ return NO_MORE_DOCS;+ }++ @Override+ public int advance(int target) throws IOException {+ return NO_MORE_DOCS;+ }++ @Override+ public void close() throws IOException {++ }+ };+ }+}diff --git a/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java b/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.javaindex beb0c14704c..2dfa5bdc8a1 100644--- a/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java@@ -50,16 +50,16 @@ class VarDerefBytesImpl {static final String CODEC_NAME = "VarDerefBytes";static final int VERSION_START = 0;static final int VERSION_CURRENT = VERSION_START;--- private static class AddressParallelArray extends ParallelArrayBase<AddressParallelArray> {+ private static class AddressParallelArray extends+ ParallelArrayBase<AddressParallelArray> {final int[] address;-+AddressParallelArray(int size, AtomicLong bytesUsed) {super(size, bytesUsed);- address = new int[size];+ address = new int[size];}+@Overrideprotected int bytesPerEntry() {return RamUsageEstimator.NUM_BYTES_INT + super.bytesPerEntry();@@ -69,46 +69,50 @@ class VarDerefBytesImpl {protected void copyTo(AddressParallelArray toArray, int numToCopy) {super.copyTo(toArray, numToCopy);System.arraycopy(address, 0, toArray.address, 0, size);-+}@Overridepublic AddressParallelArray newInstance(int size) {return new AddressParallelArray(size, bytesUsed);}-- }+ }static class Writer extends BytesWriterBase {private int[] docToAddress;private int address = 1;-- private final ParallelBytesStartArray<AddressParallelArray> array = new ParallelBytesStartArray<AddressParallelArray>(new AddressParallelArray(0, bytesUsed));- private final BytesRefHash hash = new BytesRefHash(pool, 16, array) ;- public Writer(Directory dir, String id) throws IOException {+ private final ParallelBytesStartArray<AddressParallelArray> array = new ParallelBytesStartArray<AddressParallelArray>(+ new AddressParallelArray(0, bytesUsed));+ private final BytesRefHash hash = new BytesRefHash(pool, 16, array);++ public Writer(Directory dir, String id) throws IOException {this(dir, id, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE),new AtomicLong());}- public Writer(Directory dir, String id, Allocator allocator, AtomicLong bytesUsed) throws IOException {- super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false, new ByteBlockPool(allocator), bytesUsed);++ public Writer(Directory dir, String id, Allocator allocator,+ AtomicLong bytesUsed) throws IOException {+ super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false,+ new ByteBlockPool(allocator), bytesUsed);docToAddress = new int[1];bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);}@Overridesynchronized public void add(int docID, BytesRef bytes) throws IOException {- if(bytes.length == 0)+ if (bytes.length == 0)return; // default- if(datOut == null)+ if (datOut == null)initDataOut();final int e = hash.add(bytes);if (docID >= docToAddress.length) {final int oldSize = docToAddress.length;- docToAddress = ArrayUtil.grow(docToAddress, 1+docID);- bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT * (docToAddress.length - oldSize));+ docToAddress = ArrayUtil.grow(docToAddress, 1 + docID);+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT+ * (docToAddress.length - oldSize));}final int docAddress;if (e >= 0) {@@ -117,12 +121,13 @@ class VarDerefBytesImpl {datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);address += bytes.length;} else {- docAddress = array.array.address[(-e)-1];+ docAddress = array.array.address[(-e) - 1];}docToAddress[docID] = docAddress;}-- private static int writePrefixLength(DataOutput datOut, BytesRef bytes) throws IOException{++ private static int writePrefixLength(DataOutput datOut, BytesRef bytes)+ throws IOException {if (bytes.length < 128) {datOut.writeByte((byte) bytes.length);return 1;@@ -132,7 +137,7 @@ class VarDerefBytesImpl {return 2;}}-+public long ramBytesUsed() {return bytesUsed.get();}@@ -141,25 +146,26 @@ class VarDerefBytesImpl {// some last docs that we didn't see@Overridesynchronized public void finish(int docCount) throws IOException {- if(datOut == null)+ if (datOut == null)return;initIndexOut();- idxOut.writeInt(address-1);+ idxOut.writeInt(address - 1);// write index// TODO(simonw): -- allow forcing fixed array (not -1)// TODO(simonw): check the address calculation / make it more intuitive- final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount, PackedInts.bitsRequired(address-1));+ final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,+ PackedInts.bitsRequired(address - 1));final int limit;if (docCount > docToAddress.length) {limit = docToAddress.length;} else {limit = docCount;}- for(int i=0;i<limit;i++) {+ for (int i = 0; i < limit; i++) {w.add(docToAddress[i]);}- for(int i=limit;i<docCount;i++) {+ for (int i = limit; i < docCount; i++) {w.add(0);}w.finish();@@ -170,8 +176,7 @@ class VarDerefBytesImpl {public static class Reader extends BytesReaderBase {- Reader(Directory dir, String id, int maxDoc)- throws IOException {+ Reader(Directory dir, String id, int maxDoc) throws IOException {super(dir, id, CODEC_NAME, VERSION_START, true);}@@ -182,49 +187,53 @@ class VarDerefBytesImpl {data.seek(CodecUtil.headerLength(CODEC_NAME));index.seek(CodecUtil.headerLength(CODEC_NAME));final long totalBytes = index.readInt(); // should be long- return new Source(data,index, totalBytes);+ return new Source(data, index, totalBytes);}private static class Source extends BytesBaseSource {- private final BytesRef bytesRef = new BytesRef();private final PackedInts.Reader index;- public Source(IndexInput datIn, IndexInput idxIn, long totalBytes) throws IOException {+ public Source(IndexInput datIn, IndexInput idxIn, long totalBytes)+ throws IOException {super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), totalBytes);index = PackedInts.getReader(idxIn);}@Override- public BytesRef getBytes(int docID) {- long address = index.get(docID);- if (address == 0) {- assert defaultValue.length == 0: " default value manipulated";- return defaultValue;- } else {- data.fillUsingLengthPrefix2(bytesRef, --address);- return bytesRef;- }+ public BytesRef getBytes(int docID, BytesRef bytesRef) {+ long address = index.get(docID);+ return address == 0 ? null : data.fillUsingLengthPrefix4(bytesRef,+ --address);}-+@Overridepublic int getValueCount() {+ throw new UnsupportedOperationException();+ }++ @Override+ public Values type() {+ return Values.BYTES_VAR_DEREF;+ }++ @Override+ protected int maxDoc() {return index.size();}}@Overridepublic ValuesEnum getEnum(AttributeSource source) throws IOException {- return new VarDerefBytesEnum(source, cloneData(), cloneIndex(), CODEC_NAME);+ return new VarDerefBytesEnum(source, cloneData(), cloneIndex());}-+static class VarDerefBytesEnum extends DerefBytesEnum {- public VarDerefBytesEnum(AttributeSource source, IndexInput datIn, IndexInput idxIn,- String codecName) throws IOException {- super(source, datIn, idxIn, codecName, -1, Values.BYTES_VAR_DEREF);+ public VarDerefBytesEnum(AttributeSource source, IndexInput datIn,+ IndexInput idxIn) throws IOException {+ super(source, datIn, idxIn, -1, Values.BYTES_VAR_DEREF);}-@Overrideprotected void fill(long address, BytesRef ref) throws IOException {datIn.seek(fp + --address);@@ -234,16 +243,16 @@ class VarDerefBytesImpl {// length is 1 bytesize = sizeByte;} else {- size = ((sizeByte & 0x7f)<<8) | ((datIn.readByte() & 0xff));+ size = ((sizeByte & 0x7f) << 8) | ((datIn.readByte() & 0xff));}- if(ref.bytes.length < size)+ if (ref.bytes.length < size)ref.grow(size);ref.length = size;ref.offset = 0;datIn.readBytes(ref.bytes, 0, size);}}-+@Overridepublic Values type() {return Values.BYTES_VAR_DEREF;diff --git a/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java b/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.javaindex a6eb7d0deb0..4504ee4f431 100644--- a/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java@@ -171,7 +171,6 @@ class VarSortedBytesImpl {}private static class Source extends BytesBaseSortedSource {- // TODO: paged dataprivate final PackedInts.Reader docToOrdIndex;private final PackedInts.Reader ordToOffsetIndex; // 0-basedprivate final long totBytes;@@ -184,8 +183,6 @@ class VarSortedBytesImpl {docToOrdIndex = PackedInts.getReader(idxIn);ordToOffsetIndex = PackedInts.getReader(idxIn);valueCount = ordToOffsetIndex.size();- // default byte sort order-}@Override@@ -194,8 +191,8 @@ class VarSortedBytesImpl {}@Override- public LookupResult getByValue(BytesRef bytes) {- return binarySearch(bytes, 0, valueCount - 1);+ public LookupResult getByValue(BytesRef bytes, BytesRef tmpRef) {+ return binarySearch(bytes, tmpRef, 0, valueCount - 1);}public long ramBytesUsed() {@@ -217,8 +214,7 @@ class VarSortedBytesImpl {// ord is 0-based@Override- protected BytesRef deref(int ord) {-+ protected BytesRef deref(int ord, BytesRef bytesRef) {final long nextOffset;if (ord == valueCount - 1) {nextOffset = totBytes;@@ -230,7 +226,15 @@ class VarSortedBytesImpl {return bytesRef;}-+ @Override+ public Values type() {+ return Values.BYTES_VAR_SORTED;+ }++ @Override+ protected int maxDoc() {+ return docToOrdIndex.size();+ }}@Override@@ -274,15 +278,16 @@ class VarSortedBytesImpl {@Overridepublic int advance(int target) throws IOException {- if (target >= docCount)+ if (target >= docCount) {return pos = NO_MORE_DOCS;- final int ord = (int) docToOrdIndex.get(target) - 1;- if (ord == -1) {- bytesRef.length = 0;- bytesRef.offset = 0;- return pos = target;}- final long offset = ordToOffsetIndex.get(ord);+ int ord;+ while((ord =(int) docToOrdIndex.get(target)) == 0) {+ if(++target >= docCount) {+ return pos = NO_MORE_DOCS;+ }+ }+ final long offset = ordToOffsetIndex.get(--ord);final long nextOffset;if (ord == valueCount - 1) {nextOffset = totBytes;@@ -306,6 +311,9 @@ class VarSortedBytesImpl {@Overridepublic int nextDoc() throws IOException {+ if (pos >= docCount) {+ return pos = NO_MORE_DOCS;+ }return advance(pos + 1);}}diff --git a/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java b/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.javaindex 04fd5939d34..0f3f6dff28f 100644--- a/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java+++ b/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java@@ -41,15 +41,15 @@ class VarStraightBytesImpl {static final int VERSION_CURRENT = VERSION_START;static class Writer extends BytesWriterBase {- private int address;+ private long address;// start at -1 if the first added value is > 0private int lastDocID = -1;- private int[] docToAddress;+ private long[] docToAddress;public Writer(Directory dir, String id, AtomicLong bytesUsed)throws IOException {super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false, null, bytesUsed);- docToAddress = new int[1];+ docToAddress = new long[1];bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);}@@ -89,11 +89,8 @@ class VarStraightBytesImpl {return;}initIndexOut();- // write all lengths to index- // write indexfill(docCount);- idxOut.writeVInt(address);- // TODO(simonw): allow not -1+ idxOut.writeVLong(address);final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,PackedInts.bitsRequired(address));for (int i = 0; i < docCount; i++) {@@ -125,20 +122,17 @@ class VarStraightBytesImpl {}private class Source extends BytesBaseSource {- private final BytesRef bytesRef = new BytesRef();private final PackedInts.Reader addresses;public Source(IndexInput datIn, IndexInput idxIn) throws IOException {- super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), idxIn.readVInt()); // TODO- // should- // be- // long+ super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), idxIn.readVLong());addresses = PackedInts.getReader(idxIn);+ missingValues.bytesValue = new BytesRef(0); // empty}@Override- public BytesRef getBytes(int docID) {- final int address = (int) addresses.get(docID);+ public BytesRef getBytes(int docID, BytesRef bytesRef) {+ final long address = addresses.get(docID);final int length = docID == maxDoc - 1 ? (int) (totalLengthInBytes - address): (int) (addresses.get(1 + docID) - address);return data.fill(bytesRef, address, length);@@ -148,14 +142,24 @@ class VarStraightBytesImpl {public int getValueCount() {throw new UnsupportedOperationException();}++ @Override+ public Values type() {+ return Values.BYTES_VAR_STRAIGHT;+ }++ @Override+ protected int maxDoc() {+ return addresses.size();+ }}@Overridepublic ValuesEnum getEnum(AttributeSource source) throws IOException {- return new VarStrainghtBytesEnum(source, cloneData(), cloneIndex());+ return new VarStraightBytesEnum(source, cloneData(), cloneIndex());}- private class VarStrainghtBytesEnum extends ValuesEnum {+ private class VarStraightBytesEnum extends ValuesEnum {private final PackedInts.Reader addresses;private final IndexInput datIn;private final IndexInput idxIn;@@ -164,7 +168,7 @@ class VarStraightBytesImpl {private final BytesRef ref;private int pos = -1;- protected VarStrainghtBytesEnum(AttributeSource source, IndexInput datIn,+ protected VarStraightBytesEnum(AttributeSource source, IndexInput datIn,IndexInput idxIn) throws IOException {super(source, Values.BYTES_VAR_STRAIGHT);totBytes = idxIn.readVInt();@@ -185,13 +189,10 @@ class VarStraightBytesImpl {@Overridepublic int advance(final int target) throws IOException {if (target >= maxDoc) {- ref.length = 0;- ref.offset = 0;return pos = NO_MORE_DOCS;}final long addr = addresses.get(target);- if (addr == totBytes) {- // nocommit is that a valid default value+ if (addr == totBytes) { // empty values at the endref.length = 0;ref.offset = 0;return pos = target;diff --git a/lucene/src/java/org/apache/lucene/index/values/Writer.java b/lucene/src/java/org/apache/lucene/index/values/Writer.javaindex b73b8ab4113..04471b25427 100644--- a/lucene/src/java/org/apache/lucene/index/values/Writer.java+++ b/lucene/src/java/org/apache/lucene/index/values/Writer.java@@ -25,7 +25,7 @@ import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;public abstract class Writer extends DocValuesConsumer {-+public static final String INDEX_EXTENSION = "idx";public static final String DATA_EXTENSION = "dat";@@ -63,23 +63,31 @@ public abstract class Writer extends DocValuesConsumer {int docID = state.docBase;final Bits bits = state.bits;final int docCount = state.docCount;- for (int i = 0; i < docCount; i++) {- if (bits == null || !bits.get(i)) {- if (valEnum.advance(i) == ValuesEnum.NO_MORE_DOCS)- break;- add(docID++);+ int currentDocId;+ if ((currentDocId = valEnum.advance(0)) != ValuesEnum.NO_MORE_DOCS) {+ for (int i = 0; i < docCount; i++) {+ if (bits == null || !bits.get(i)) {+ if (currentDocId < i) {+ if ((currentDocId = valEnum.advance(i)) == ValuesEnum.NO_MORE_DOCS) {+ break; // advance can jump over default values+ }+ }+ if (currentDocId == i) { // we are on the doc to merge+ add(docID);+ }+ ++docID;+ }}}} finally {valEnum.close();}}-- public static Writer create(Values v, String id,- Directory directory, Comparator<BytesRef> comp) throws IOException {++ public static Writer create(Values v, String id, Directory directory,+ Comparator<BytesRef> comp) throws IOException {switch (v) {case PACKED_INTS:- case PACKED_INTS_FIXED:return Ints.getWriter(directory, id, true);case SIMPLE_FLOAT_4BYTE:return Floats.getWriter(directory, id, 4);diff --git a/lucene/src/java/org/apache/lucene/util/PagedBytes.java b/lucene/src/java/org/apache/lucene/util/PagedBytes.javaindex 9d42cdd94f7..d09ef809ab7 100644--- a/lucene/src/java/org/apache/lucene/util/PagedBytes.java+++ b/lucene/src/java/org/apache/lucene/util/PagedBytes.java@@ -90,7 +90,7 @@ public final class PagedBytes {}return b;}-+/** Reads length as 1 or 2 byte vInt prefix, starting @ start */public BytesRef fillUsingLengthPrefix(BytesRef b, long start) {final int index = (int) (start >> blockBits);@@ -145,6 +145,49 @@ public final class PagedBytes {}return start;}++ /**+ * Reads length as 1 or 2 byte vInt prefix, starting @ start and fill the+ * given {@link BytesRef} with the byte slice starting after the length+ * prefix.+ * @lucene.internal+ **/+ public BytesRef fillUsingLengthPrefix4(BytesRef b, long start) {+ final int index = (int) (start >> blockBits);+ int offset = (int) (start & blockMask);+ final byte[] block = blocks[index];+ final int length;+ if ((block[offset] & 128) == 0) {+ length = block[offset];+ offset = offset+1;+ } else {+ length = ((block[offset] & 0x7f) << 8) | (block[1+offset] & 0xff);+ offset = offset+2;+ assert length > 0;+ }+ assert length >= 0: "length=" + length;+ b.length = length;+ if (blockSize - offset >= length) {+ // Within block+ b.offset = offset;+ b.bytes = blocks[index];+ } else {+ // Split+ byte[] buffer = threadBuffers.get();+ if (buffer == null) {+ buffer = new byte[length];+ threadBuffers.set(buffer);+ } else if (buffer.length < length) {+ buffer = ArrayUtil.grow(buffer, length);+ threadBuffers.set(buffer);+ }+ b.bytes = buffer;+ b.offset = 0;+ System.arraycopy(blocks[index], offset, buffer, 0, blockSize-offset);+ System.arraycopy(blocks[1+index], 0, buffer, blockSize-offset, length-(blockSize-offset));+ }+ return b;+ }/** @lucene.internal */public byte[][] getBlocks() {diff --git a/lucene/src/test/org/apache/lucene/index/values/TestDocValues.java b/lucene/src/test/org/apache/lucene/index/values/TestDocValues.javaindex 8086871678c..2b2015cf5f1 100644--- a/lucene/src/test/org/apache/lucene/index/values/TestDocValues.java+++ b/lucene/src/test/org/apache/lucene/index/values/TestDocValues.java@@ -117,14 +117,15 @@ public class TestDocValues extends LuceneTestCase {s = getSource(r);ss = null;}-for (int i = 0; i < 100; i++) {final int idx = 2 * i;- assertNotNull("doc " + idx + "; value=" + values[idx], s.getBytes(idx));- assertEquals("doc " + idx, values[idx], s.getBytes(idx).utf8ToString());+ assertNotNull("doc " + idx + "; value=" + values[idx], s.getBytes(idx,+ bytesRef));+ assertEquals("doc " + idx, values[idx], s.getBytes(idx, bytesRef)+ .utf8ToString());if (ss != null) {- assertEquals("doc " + idx, values[idx], ss.getByOrd(ss.ord(idx))- .utf8ToString());+ assertEquals("doc " + idx, values[idx], ss.getByOrd(ss.ord(idx),+ bytesRef).utf8ToString());DocValues.SortedSource.LookupResult result = ss.getByValue(new BytesRef(values[idx]));assertTrue(result.found);@@ -141,7 +142,8 @@ public class TestDocValues extends LuceneTestCase {SortedSource.LookupResult result = ss.getByValue(bytesValue);if (result.found) {assert result.ord > 0;- assertTrue(bytesValue.bytesEquals(ss.getByOrd(result.ord)));+ assertTrue(bytesValue+ .bytesEquals(ss.getByOrd(result.ord, bytesRef)));int count = 0;for (int k = 0; k < 100; k++) {if (bytesValue.utf8ToString().equals(values[2 * k])) {@@ -153,18 +155,18 @@ public class TestDocValues extends LuceneTestCase {} else {assert result.ord >= 0;if (result.ord == 0) {- final BytesRef firstRef = ss.getByOrd(1);+ final BytesRef firstRef = ss.getByOrd(1, bytesRef);// random string was before our firstassertTrue(firstRef.compareTo(bytesValue) > 0);} else if (result.ord == numValues) {- final BytesRef lastRef = ss.getByOrd(numValues);+ final BytesRef lastRef = ss.getByOrd(numValues, bytesRef);// random string was after our lastassertTrue(lastRef.compareTo(bytesValue) < 0);} else {// random string fell between two of our values- final BytesRef before = (BytesRef) ss.getByOrd(result.ord)- .clone();- final BytesRef after = ss.getByOrd(result.ord + 1);+ final BytesRef before = (BytesRef) ss.getByOrd(result.ord,+ bytesRef).clone();+ final BytesRef after = ss.getByOrd(result.ord + 1, bytesRef);assertTrue(before.compareTo(bytesValue) < 0);assertTrue(bytesValue.compareTo(after) < 0);@@ -180,64 +182,65 @@ public class TestDocValues extends LuceneTestCase {public void testInts() throws IOException {long maxV = 1;- final int NUM_VALUES = 1000;+ final int NUM_VALUES = 777 + random.nextInt(777);final long[] values = new long[NUM_VALUES];for (int rx = 1; rx < 63; rx++, maxV *= 2) {- for (int b = 0; b < 2; b++) {- Directory dir = newDirectory();- boolean useFixedArrays = b == 0;- Writer w = Ints.getWriter(dir, "test", useFixedArrays);+ Directory dir = newDirectory();+ Writer w = Ints.getWriter(dir, "test", false);+ for (int i = 0; i < NUM_VALUES; i++) {+ final long v = random.nextLong() % (1 + maxV);+ values[i] = v;+ w.add(i, v);+ }+ final int additionalDocs = 1 + random.nextInt(9);+ w.finish(NUM_VALUES + additionalDocs);++ DocValues r = Ints.getValues(dir, "test", false);+ for (int iter = 0; iter < 2; iter++) {+ Source s = getSource(r);for (int i = 0; i < NUM_VALUES; i++) {- final long v = random.nextLong() % (1 + maxV);- values[i] = v;- w.add(i, v);- }- final int additionalDocs = 1 + random.nextInt(9);- w.finish(NUM_VALUES + additionalDocs);-- DocValues r = Ints.getValues(dir, "test", useFixedArrays);- for (int iter = 0; iter < 2; iter++) {- Source s = getSource(r);- for (int i = 0; i < NUM_VALUES; i++) {- final long v = s.getInt(i);- assertEquals("index " + i + " b: " + b, values[i], v);- }+ final long v = s.getInt(i);+ assertEquals("index " + i, values[i], v);}+ }- for (int iter = 0; iter < 2; iter++) {- ValuesEnum iEnum = r.getEnum();- ValuesAttribute attr = iEnum.addAttribute(ValuesAttribute.class);- LongsRef ints = attr.ints();- for (int i = 0; i < NUM_VALUES; i++) {- assertEquals(i, iEnum.nextDoc());- assertEquals(values[i], ints.get());- }- for (int i = NUM_VALUES; i < NUM_VALUES + additionalDocs; i++) {- assertEquals(i, iEnum.nextDoc());- assertEquals("" + i, 0, ints.get());- }-- iEnum.close();+ for (int iter = 0; iter < 2; iter++) {+ ValuesEnum iEnum = r.getEnum();+ ValuesAttribute attr = iEnum.addAttribute(ValuesAttribute.class);+ LongsRef ints = attr.ints();+ for (int i = 0; i < NUM_VALUES; i++) {+ assertEquals(i, iEnum.nextDoc());+ assertEquals(values[i], ints.get());+ }+ if (iEnum.docID() < NUM_VALUES - 1) {+ assertEquals(NUM_VALUES - 1, iEnum.advance(NUM_VALUES - 1));+ }+ for (int i = NUM_VALUES; i < NUM_VALUES + additionalDocs; i++) {+ assertEquals(ValuesEnum.NO_MORE_DOCS, iEnum.nextDoc());}- for (int iter = 0; iter < 2; iter++) {- ValuesEnum iEnum = r.getEnum();- ValuesAttribute attr = iEnum.addAttribute(ValuesAttribute.class);- LongsRef ints = attr.ints();- for (int i = 0; i < NUM_VALUES; i += 1 + random.nextInt(25)) {- assertEquals(i, iEnum.advance(i));- assertEquals(values[i], ints.get());- }- for (int i = NUM_VALUES; i < NUM_VALUES + additionalDocs; i++) {- assertEquals(i, iEnum.advance(i));- assertEquals("" + i, 0, ints.get());- }+ iEnum.close();+ }- iEnum.close();+ for (int iter = 0; iter < 2; iter++) {+ ValuesEnum iEnum = r.getEnum();+ ValuesAttribute attr = iEnum.addAttribute(ValuesAttribute.class);+ LongsRef ints = attr.ints();+ for (int i = 0; i < NUM_VALUES; i += 1 + random.nextInt(25)) {+ assertEquals(i, iEnum.advance(i));+ assertEquals(values[i], ints.get());}- r.close();- dir.close();+ if (iEnum.docID() < NUM_VALUES - 1) {+ assertEquals(NUM_VALUES - 1, iEnum.advance(NUM_VALUES - 1));+ }+ for (int i = NUM_VALUES; i < NUM_VALUES + additionalDocs; i++) {+ assertEquals(ValuesEnum.NO_MORE_DOCS, iEnum.nextDoc());+ }++ iEnum.close();}+ r.close();+ dir.close();}}@@ -248,7 +251,7 @@ public class TestDocValues extends LuceneTestCase {private void runTestFloats(int precision, double delta) throws IOException {Directory dir = newDirectory();Writer w = Floats.getWriter(dir, "test", precision);- final int NUM_VALUES = 1000;+ final int NUM_VALUES = 777 + random.nextInt(777);;final double[] values = new double[NUM_VALUES];for (int i = 0; i < NUM_VALUES; i++) {final double v = precision == 4 ? random.nextFloat() : random@@ -269,29 +272,25 @@ public class TestDocValues extends LuceneTestCase {for (int iter = 0; iter < 2; iter++) {ValuesEnum fEnum = r.getEnum();- ValuesAttribute attr = fEnum.addAttribute(ValuesAttribute.class);- FloatsRef floats = attr.floats();+ FloatsRef floats = fEnum.getFloat();for (int i = 0; i < NUM_VALUES; i++) {assertEquals(i, fEnum.nextDoc());assertEquals(values[i], floats.get(), delta);}for (int i = NUM_VALUES; i < NUM_VALUES + additionalValues; i++) {- assertEquals(i, fEnum.nextDoc());- assertEquals(0.0, floats.get(), delta);+ assertEquals(ValuesEnum.NO_MORE_DOCS, fEnum.nextDoc());}fEnum.close();}for (int iter = 0; iter < 2; iter++) {ValuesEnum fEnum = r.getEnum();- ValuesAttribute attr = fEnum.addAttribute(ValuesAttribute.class);- FloatsRef floats = attr.floats();+ FloatsRef floats = fEnum.getFloat();for (int i = 0; i < NUM_VALUES; i += 1 + random.nextInt(25)) {assertEquals(i, fEnum.advance(i));assertEquals(values[i], floats.get(), delta);}for (int i = NUM_VALUES; i < NUM_VALUES + additionalValues; i++) {- assertEquals(i, fEnum.advance(i));- assertEquals(0.0, floats.get(), delta);+ assertEquals(ValuesEnum.NO_MORE_DOCS, fEnum.advance(i));}fEnum.close();}diff --git a/lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.java b/lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.javaindex fcac9640ef7..5ab0c649adf 100644--- a/lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.java+++ b/lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.java@@ -43,6 +43,7 @@ import org.apache.lucene.index.MultiFields;import org.apache.lucene.index.Term;import org.apache.lucene.index.codecs.CodecProvider;import org.apache.lucene.index.codecs.docvalues.DocValuesCodec;+import org.apache.lucene.index.values.DocValues.MissingValues;import org.apache.lucene.index.values.DocValues.Source;import org.apache.lucene.store.Directory;import org.apache.lucene.store.LockObtainFailedException;@@ -86,49 +87,40 @@ public class TestDocValuesIndexing extends LuceneTestCase {* Tests complete indexing of {@link Values} including deletions, merging and* sparse value fields on Compound-File*/- public void testCFSIndex() throws IOException {- // without deletions- IndexWriterConfig cfg = writerConfig(true);- // primitives - no deletes- runTestNumerics(cfg, false);-- cfg = writerConfig(true);- // bytes - no deletes- runTestIndexBytes(cfg, false);-- // with deletions- cfg = writerConfig(true);- // primitives- runTestNumerics(cfg, true);-- cfg = writerConfig(true);- // bytes- runTestIndexBytes(cfg, true);+ public void testIndexBytesNoDeletesCFS() throws IOException {+ runTestIndexBytes(writerConfig(true), false);+ }++ public void testIndexBytesDeletesCFS() throws IOException {+ runTestIndexBytes(writerConfig(true), true);+ }++ public void testIndexNumericsNoDeletesCFS() throws IOException {+ runTestNumerics(writerConfig(true), false);+ }++ public void testIndexNumericsDeletesCFS() throws IOException {+ runTestNumerics(writerConfig(true), true);}/*** Tests complete indexing of {@link Values} including deletions, merging and* sparse value fields on None-Compound-File*/- public void testIndex() throws IOException {- //- // without deletions- IndexWriterConfig cfg = writerConfig(false);- // primitives - no deletes- runTestNumerics(cfg, false);-- cfg = writerConfig(false);- // bytes - no deletes- runTestIndexBytes(cfg, false);-- // with deletions- cfg = writerConfig(false);- // primitives- runTestNumerics(cfg, true);-- cfg = writerConfig(false);- // bytes- runTestIndexBytes(cfg, true);+ public void testIndexBytesNoDeletes() throws IOException {+ runTestIndexBytes(writerConfig(false), false);+ }++ public void testIndexBytesDeletes() throws IOException {+ runTestIndexBytes(writerConfig(false), true);+ }++ public void testIndexNumericsNoDeletes() throws IOException {+ runTestNumerics(writerConfig(false), false);+ }++ public void testIndexNumericsDeletes() throws IOException {+ runTestNumerics(writerConfig(false), true);}private IndexWriterConfig writerConfig(boolean useCompoundFile) {@@ -150,7 +142,7 @@ public class TestDocValuesIndexing extends LuceneTestCase {throws IOException {Directory d = newDirectory();IndexWriter w = new IndexWriter(d, cfg);- final int numValues = 350;+ final int numValues = 179 + random.nextInt(151);final List<Values> numVariantList = new ArrayList<Values>(NUMERICS);// run in random order to test if fill works correctly during merges@@ -163,22 +155,24 @@ public class TestDocValuesIndexing extends LuceneTestCase {final int numRemainingValues = (int) (numValues - deleted.cardinality());final int base = r.numDocs() - numRemainingValues;switch (val) {- case PACKED_INTS:- case PACKED_INTS_FIXED: {+ case PACKED_INTS: {DocValues intsReader = getDocValues(r, val.name());assertNotNull(intsReader);Source ints = getSource(intsReader);+ MissingValues missing = ints.getMissing();- ValuesEnum intsEnum = intsReader.getEnum();- assertNotNull(intsEnum);- LongsRef enumRef = intsEnum.addAttribute(ValuesAttribute.class).ints();for (int i = 0; i < base; i++) {- assertEquals("index " + i, 0, ints.getInt(i));- assertEquals(val.name() + " base: " + base + " index: " + i, i,- random.nextBoolean() ? intsEnum.advance(i) : intsEnum.nextDoc());- assertEquals(0, enumRef.get());+ long value = ints.getInt(i);+ assertEquals("index " + i, missing.longValue, value);}++ ValuesEnum intsEnum = getValuesEnum(intsReader);+ assertTrue(intsEnum.advance(0) >= base);++ intsEnum = getValuesEnum(intsReader);+ LongsRef enumRef = intsEnum.getInt();+int expected = 0;for (int i = base; i < r.numDocs(); i++, expected++) {while (deleted.get(expected)) {@@ -197,18 +191,18 @@ public class TestDocValuesIndexing extends LuceneTestCase {DocValues floatReader = getDocValues(r, val.name());assertNotNull(floatReader);Source floats = getSource(floatReader);- ValuesEnum floatEnum = floatReader.getEnum();- assertNotNull(floatEnum);- FloatsRef enumRef = floatEnum.addAttribute(ValuesAttribute.class)- .floats();+ MissingValues missing = floats.getMissing();for (int i = 0; i < base; i++) {- assertEquals(" floats failed for doc: " + i + " base: " + base, 0.0d,- floats.getFloat(i), 0.0d);- assertEquals(i, random.nextBoolean() ? floatEnum.advance(i)- : floatEnum.nextDoc());- assertEquals("index " + i, 0.0, enumRef.get(), 0.0);+ double value = floats.getFloat(i);+ assertEquals(" floats failed for doc: " + i + " base: " + base,+ missing.doubleValue, value, 0.0d);}+ ValuesEnum floatEnum = getValuesEnum(floatReader);+ assertTrue(floatEnum.advance(0) >= base);++ floatEnum = getValuesEnum(floatReader);+ FloatsRef enumRef = floatEnum.getFloat();int expected = 0;for (int i = base; i < r.numDocs(); i++, expected++) {while (deleted.get(expected)) {@@ -235,92 +229,6 @@ public class TestDocValuesIndexing extends LuceneTestCase {d.close();}- private static EnumSet<Values> BYTES = EnumSet.of(Values.BYTES_FIXED_DEREF,- Values.BYTES_FIXED_SORTED, Values.BYTES_FIXED_STRAIGHT,- Values.BYTES_VAR_DEREF, Values.BYTES_VAR_SORTED,- Values.BYTES_VAR_STRAIGHT);-- private static EnumSet<Values> NUMERICS = EnumSet.of(Values.PACKED_INTS,- Values.PACKED_INTS_FIXED, Values.SIMPLE_FLOAT_4BYTE,- Values.SIMPLE_FLOAT_8BYTE);-- private static Index[] IDX_VALUES = new Index[] { Index.ANALYZED,- Index.ANALYZED_NO_NORMS, Index.NOT_ANALYZED, Index.NOT_ANALYZED_NO_NORMS,- Index.NO };-- private OpenBitSet indexValues(IndexWriter w, int numValues, Values value,- List<Values> valueVarList, boolean withDeletions, int multOfSeven)- throws CorruptIndexException, IOException {- final boolean isNumeric = NUMERICS.contains(value);- OpenBitSet deleted = new OpenBitSet(numValues);- Document doc = new Document();- Index idx = IDX_VALUES[random.nextInt(IDX_VALUES.length)];- Fieldable field = random.nextBoolean() ? new ValuesField(value.name())- : newField(value.name(), _TestUtil.randomRealisticUnicodeString(random,- 10), idx == Index.NO ? Store.YES : Store.NO, idx);- doc.add(field);-- ValuesAttribute valuesAttribute = ValuesField.values(field);- valuesAttribute.setType(value);- final LongsRef intsRef = valuesAttribute.ints();- final FloatsRef floatsRef = valuesAttribute.floats();- final BytesRef bytesRef = valuesAttribute.bytes();-- final String idBase = value.name() + "_";- final byte[] b = new byte[multOfSeven];- if (bytesRef != null) {- bytesRef.bytes = b;- bytesRef.length = b.length;- bytesRef.offset = 0;- }- byte upto = 0;- for (int i = 0; i < numValues; i++) {- if (isNumeric) {- switch (value) {- case PACKED_INTS:- case PACKED_INTS_FIXED:- intsRef.set(i);- break;- case SIMPLE_FLOAT_4BYTE:- case SIMPLE_FLOAT_8BYTE:- floatsRef.set(2.0f * i);- break;- default:- fail("unexpected value " + value);- }- } else {- for (int j = 0; j < b.length; j++) {- b[j] = upto++;- }- }- doc.removeFields("id");- doc.add(new Field("id", idBase + i, Store.YES,- Index.NOT_ANALYZED_NO_NORMS));- w.addDocument(doc);-- if (i % 7 == 0) {- if (withDeletions && random.nextBoolean()) {- Values val = valueVarList.get(random.nextInt(1 + valueVarList- .indexOf(value)));- final int randInt = val == value ? random.nextInt(1 + i) : random- .nextInt(numValues);- w.deleteDocuments(new Term("id", val.name() + "_" + randInt));- if (val == value) {- deleted.set(randInt);- }- }- w.commit();-- }- }- w.commit();-- // TODO test unoptimized with deletions- if (withDeletions || random.nextBoolean())- w.optimize();- return deleted;- }-public void runTestIndexBytes(IndexWriterConfig cfg, boolean withDeletions)throws CorruptIndexException, LockObtainFailedException, IOException {final Directory d = newDirectory();@@ -343,30 +251,32 @@ public class TestDocValuesIndexing extends LuceneTestCase {assertNotNull("field " + byteIndexValue.name()+ " returned null reader - maybe merged failed", bytesReader);Source bytes = getSource(bytesReader);- ValuesEnum bytesEnum = bytesReader.getEnum();- assertNotNull(bytesEnum);- final ValuesAttribute attr = bytesEnum- .addAttribute(ValuesAttribute.class);byte upto = 0;+// test the filled up slots for correctness+ MissingValues missing = bytes.getMissing();for (int i = 0; i < base; i++) {- final BytesRef br = bytes.getBytes(i);++ BytesRef br = bytes.getBytes(i, new BytesRef());String msg = " field: " + byteIndexValue.name() + " at index: " + i+ " base: " + base + " numDocs:" + r.numDocs();switch (byteIndexValue) {case BYTES_VAR_STRAIGHT:case BYTES_FIXED_STRAIGHT:- assertEquals(i, bytesEnum.advance(i));// fixed straight returns bytesref with zero bytes all of fixed// length- assertNotNull("expected none null - " + msg, br);- if (br.length != 0) {- assertEquals("expected zero bytes of length " + bytesSize + " - "- + msg, bytesSize, br.length);- for (int j = 0; j < br.length; j++) {- assertEquals("Byte at index " + j + " doesn't match - " + msg, 0,- br.bytes[br.offset + j]);+ if (missing.bytesValue != null) {+ assertNotNull("expected none null - " + msg, br);+ if (br.length != 0) {+ assertEquals("expected zero bytes of length " + bytesSize + " - "+ + msg, bytesSize, br.length);+ for (int j = 0; j < br.length; j++) {+ assertEquals("Byte at index " + j + " doesn't match - " + msg,+ 0, br.bytes[br.offset + j]);+ }}+ } else {+ assertNull("expected null - " + msg + " " + br, br);}break;case BYTES_VAR_SORTED:@@ -374,16 +284,18 @@ public class TestDocValuesIndexing extends LuceneTestCase {case BYTES_VAR_DEREF:case BYTES_FIXED_DEREF:default:- assertNotNull("expected none null - " + msg, br);- if (br.length != 0) {- bytes.getBytes(i);- }- assertEquals("expected empty bytes - " + br.utf8ToString() + msg, 0,- br.length);+ assertNull("expected null - " + msg + " " + br, br);+ // make sure we advance at least until base+ ValuesEnum bytesEnum = getValuesEnum(bytesReader);+ final int advancedTo = bytesEnum.advance(0);+ assertTrue(byteIndexValue.name() + " advanced failed base:" + base+ + " advancedTo: " + advancedTo, base <= advancedTo);+}}- final BytesRef enumRef = attr.bytes();+ ValuesEnum bytesEnum = getValuesEnum(bytesReader);+ final BytesRef enumRef = bytesEnum.bytes();// test the actual doc values added in this iterationassertEquals(base + numRemainingValues, r.numDocs());int v = 0;@@ -395,14 +307,20 @@ public class TestDocValuesIndexing extends LuceneTestCase {upto += bytesSize;}- BytesRef br = bytes.getBytes(i);- if (bytesEnum.docID() != i)+ BytesRef br = bytes.getBytes(i, new BytesRef());+ if (bytesEnum.docID() != i) {assertEquals("seek failed for index " + i + " " + msg, i, bytesEnum.advance(i));+ }for (int j = 0; j < br.length; j++, upto++) {assertEquals("EnumRef Byte at index " + j + " doesn't match - " + msg, upto,enumRef.bytes[enumRef.offset + j]);+ if (!(br.bytes.length > br.offset + j))+ br = bytes.getBytes(i, new BytesRef());+ assertTrue("BytesRef index exceeded [" + msg + "] offset: "+ + br.offset + " length: " + br.length + " index: "+ + (br.offset + j), br.bytes.length > br.offset + j);assertEquals("SourceRef Byte at index " + j + " doesn't match - "+ msg, upto, br.bytes[br.offset + j]);}@@ -442,8 +360,113 @@ public class TestDocValuesIndexing extends LuceneTestCase {}private Source getSource(DocValues values) throws IOException {- // getSource uses cache internally- return random.nextBoolean() ? values.load() : values.getSource();+ Source source;+ if (random.nextInt(10) == 0) {+ source = values.load();+ } else {+ // getSource uses cache internally+ source = values.getSource();+ }+ assertNotNull(source);+ return source;+ }++ private ValuesEnum getValuesEnum(DocValues values) throws IOException {+ ValuesEnum valuesEnum;+ if (!(values instanceof MultiDocValues) && random.nextInt(10) == 0) {+ // TODO not supported by MultiDocValues yet!+ valuesEnum = getSource(values).getEnum();+ } else {+ valuesEnum = values.getEnum();++ }+ assertNotNull(valuesEnum);+ return valuesEnum;+ }++ private static EnumSet<Values> BYTES = EnumSet.of(Values.BYTES_FIXED_DEREF,+ Values.BYTES_FIXED_SORTED, Values.BYTES_FIXED_STRAIGHT,+ Values.BYTES_VAR_DEREF, Values.BYTES_VAR_SORTED,+ Values.BYTES_VAR_STRAIGHT);++ private static EnumSet<Values> NUMERICS = EnumSet.of(Values.PACKED_INTS,+ Values.SIMPLE_FLOAT_4BYTE, Values.SIMPLE_FLOAT_8BYTE);++ private static Index[] IDX_VALUES = new Index[] { Index.ANALYZED,+ Index.ANALYZED_NO_NORMS, Index.NOT_ANALYZED, Index.NOT_ANALYZED_NO_NORMS,+ Index.NO };++ private OpenBitSet indexValues(IndexWriter w, int numValues, Values value,+ List<Values> valueVarList, boolean withDeletions, int multOfSeven)+ throws CorruptIndexException, IOException {+ final boolean isNumeric = NUMERICS.contains(value);+ OpenBitSet deleted = new OpenBitSet(numValues);+ Document doc = new Document();+ Index idx = IDX_VALUES[random.nextInt(IDX_VALUES.length)];+ Fieldable field = random.nextBoolean() ? new ValuesField(value.name())+ : newField(value.name(), _TestUtil.randomRealisticUnicodeString(random,+ 10), idx == Index.NO ? Store.YES : Store.NO, idx);+ doc.add(field);++ ValuesAttribute valuesAttribute = ValuesField.values(field);+ valuesAttribute.setType(value);+ final LongsRef intsRef = valuesAttribute.ints();+ final FloatsRef floatsRef = valuesAttribute.floats();+ final BytesRef bytesRef = valuesAttribute.bytes();++ final String idBase = value.name() + "_";+ final byte[] b = new byte[multOfSeven];+ if (bytesRef != null) {+ bytesRef.bytes = b;+ bytesRef.length = b.length;+ bytesRef.offset = 0;+ }+ byte upto = 0;+ for (int i = 0; i < numValues; i++) {+ if (isNumeric) {+ switch (value) {+ case PACKED_INTS:+ intsRef.set(i);+ break;+ case SIMPLE_FLOAT_4BYTE:+ case SIMPLE_FLOAT_8BYTE:+ floatsRef.set(2.0f * i);+ break;+ default:+ fail("unexpected value " + value);+ }+ } else {+ for (int j = 0; j < b.length; j++) {+ b[j] = upto++;+ }+ }+ doc.removeFields("id");+ doc.add(new Field("id", idBase + i, Store.YES,+ Index.NOT_ANALYZED_NO_NORMS));+ w.addDocument(doc);++ if (i % 7 == 0) {+ if (withDeletions && random.nextBoolean()) {+ Values val = valueVarList.get(random.nextInt(1 + valueVarList+ .indexOf(value)));+ final int randInt = val == value ? random.nextInt(1 + i) : random+ .nextInt(numValues);+ w.deleteDocuments(new Term("id", val.name() + "_" + randInt));+ if (val == value) {+ deleted.set(randInt);+ }+ }+ if (random.nextInt(10) == 0) {+ w.commit();+ }+ }+ }+ w.commit();++ // TODO test unoptimized with deletions+ if (withDeletions || random.nextBoolean())+ w.optimize();+ return deleted;}}