Skip to content

Apache Lucene open-source search software

catch up with trunk

Simon Willnauerfc50a5d3a606
diff --cc lucene/src/java/org/apache/lucene/document/AbstractField.java
index a45fc075076,8f025aca33c..2fd4397d12f
--- a/lucene/src/java/org/apache/lucene/document/AbstractField.java
+++ b/lucene/src/java/org/apache/lucene/document/AbstractField.java
@@@ -19,7 -19,6 +19,8 @@@ import org.apache.lucene.search.PhraseQ
import org.apache.lucene.search.spans.SpanQuery; // for javadocs
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.index.FieldInvertState;
+import org.apache.lucene.index.values.PerDocFieldValues;
++import org.apache.lucene.index.values.Type;
import org.apache.lucene.util.StringHelper; // for javadocs
@@@ -293,13 -292,4 +294,21 @@@ public abstract class AbstractField imp
result.append('>');
return result.toString();
}
+ protected PerDocFieldValues docValues;
+
+ public PerDocFieldValues getDocValues() {
+ return docValues;
+ }
+
+ public void setDocValues(PerDocFieldValues docValues) {
+ this.docValues = docValues;
+ }
++
++ public boolean hasDocValues() {
++ return docValues != null;
++ }
++
++ public Type docValuesType() {
++ return docValues == null? null : docValues.type();
++ }
}
diff --cc lucene/src/java/org/apache/lucene/document/Fieldable.java
index 3b48ad53350,3b48ad53350..6a552fc0345
--- a/lucene/src/java/org/apache/lucene/document/Fieldable.java
+++ b/lucene/src/java/org/apache/lucene/document/Fieldable.java
@@@ -18,6 -18,6 +18,8 @@@ package org.apache.lucene.document
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.index.FieldInvertState; // for javadocs
++import org.apache.lucene.index.values.PerDocFieldValues;
++import org.apache.lucene.index.values.Type;
import org.apache.lucene.search.PhraseQuery; // for javadocs
import org.apache.lucene.search.spans.SpanQuery; // for javadocs
@@@ -209,4 -209,4 +211,12 @@@ public interface Fieldable extends Seri
* silently fail to find results.
*/
void setOmitTermFreqAndPositions(boolean omitTermFreqAndPositions);
++
++ public PerDocFieldValues getDocValues() ;
++
++ public void setDocValues(PerDocFieldValues docValues);
++
++ public boolean hasDocValues();
++
++ public Type docValuesType();
}
diff --cc lucene/src/java/org/apache/lucene/index/CompoundFileReader.java
index 70ac9b7a0e3,87c3c7b1ac5..f7e3489fe40
--- a/lucene/src/java/org/apache/lucene/index/CompoundFileReader.java
+++ b/lucene/src/java/org/apache/lucene/index/CompoundFileReader.java
@@@ -158,9 -158,9 +158,9 @@@ public class CompoundFileReader extend
throw new IOException("Stream closed");
id = IndexFileNames.stripSegmentName(id);
- FileEntry entry = entries.get(id);
+ final FileEntry entry = entries.get(id);
if (entry == null)
- throw new IOException("No sub-file with id " + id + " found");
+ throw new IOException("No sub-file with id " + id + " found (files: " + entries.keySet() + ")");
return new CSIndexInput(stream, entry.offset, entry.length, readBufferSize);
}
diff --cc lucene/src/java/org/apache/lucene/index/DocFieldProcessorPerThread.java
index 5eaddfcae25,298b3bd2b75..90b96ca061a
--- a/lucene/src/java/org/apache/lucene/index/DocFieldProcessorPerThread.java
+++ b/lucene/src/java/org/apache/lucene/index/DocFieldProcessorPerThread.java
@@@ -199,7 -195,7 +199,7 @@@ final class DocFieldProcessorPerThread
// easily add it
FieldInfo fi = fieldInfos.add(fieldName, field.isIndexed(), field.isTermVectorStored(),
field.isStorePositionWithTermVector(), field.isStoreOffsetWithTermVector(),
-- field.getOmitNorms(), false, field.getOmitTermFreqAndPositions());
++ field.getOmitNorms(), false, field.getOmitTermFreqAndPositions(), field.docValuesType());
fp = new DocFieldProcessorPerField(this, fi);
fp.next = fieldHash[hashPos];
fieldHash[hashPos] = fp;
diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
index 960bc2d9b6e,c6214e65f09..8988b49ed7f
--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
@@@ -600,134 -505,148 +505,152 @@@ final class DocumentsWriter
}
synchronized boolean anyChanges() {
- return numDocsInRAM != 0 ||
- deletesInRAM.numTerms != 0 ||
- deletesInRAM.docIDs.size() != 0 ||
- deletesInRAM.queries.size() != 0;
+ return numDocs != 0 || pendingDeletes.any();
}
- synchronized private void initFlushState(boolean onlyDocStore) {
- initSegmentName(onlyDocStore);
- final SegmentCodecs info = SegmentCodecs.build(fieldInfos, writer.codecs);
- flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,
- docStoreSegment, numDocsInRAM, numDocsInStore, writer.getConfig().getTermIndexInterval(), info, bytesUsed);
+ // for testing
+ public SegmentDeletes getPendingDeletes() {
+ return pendingDeletes;
}
-
- SegmentWriteState segWriteState() {
- final SegmentCodecs info = SegmentCodecs.build(docFieldProcessor.fieldInfos, writer.codecs);
- return new SegmentWriteState(infoStream, directory, segment, docFieldProcessor.fieldInfos,
- docStoreSegment, numDocsInRAM, numDocsInStore, writer.getConfig().getTermIndexInterval(),
- info, bytesUsed);
+
+ private void pushDeletes(SegmentInfo newSegment, SegmentInfos segmentInfos) {
+ // Lock order: DW -> BD
+ if (pendingDeletes.any()) {
+ if (newSegment != null) {
+ if (infoStream != null) {
+ message("flush: push buffered deletes to newSegment");
+ }
+ bufferedDeletes.pushDeletes(pendingDeletes, newSegment);
+ } else if (segmentInfos.size() > 0) {
+ if (infoStream != null) {
+ message("flush: push buffered deletes to previously flushed segment " + segmentInfos.lastElement());
+ }
+ bufferedDeletes.pushDeletes(pendingDeletes, segmentInfos.lastElement(), true);
+ } else {
+ if (infoStream != null) {
+ message("flush: drop buffered deletes: no segments");
+ }
+ // We can safely discard these deletes: since
+ // there are no segments, the deletions cannot
+ // affect anything.
+ }
+ pendingDeletes = new SegmentDeletes();
+ }
}
- /** Returns the SegmentCodecs used to flush the last segment */
- SegmentCodecs getSegmentCodecs() {
- return flushState.segmentCodecs;
+ public boolean anyDeletions() {
+ return pendingDeletes.any();
}
-
- /** Flush all pending docs to a new segment */
- synchronized int flush(boolean closeDocStore) throws IOException {
- assert allThreadsIdle();
+ /** Flush all pending docs to a new segment */
+ // Lock order: IW -> DW
+ synchronized SegmentInfo flush(IndexWriter writer, IndexFileDeleter deleter, MergePolicy mergePolicy, SegmentInfos segmentInfos) throws IOException {
- assert numDocsInRAM > 0;
+ // We change writer's segmentInfos:
+ assert Thread.holdsLock(writer);
- assert nextDocID == numDocsInRAM;
- assert waitQueue.numWaiting == 0;
- assert waitQueue.waitingBytes == 0;
+ waitIdle();
- initFlushState(false);
+ if (numDocs == 0) {
+ // nothing to do!
+ if (infoStream != null) {
+ message("flush: no docs; skipping");
+ }
+ // Lock order: IW -> DW -> BD
+ pushDeletes(null, segmentInfos);
+ return null;
+ }
- docStoreOffset = numDocsInStore;
+ if (aborting) {
+ if (infoStream != null) {
+ message("flush: skip because aborting is set");
+ }
+ return null;
+ }
- if (infoStream != null)
- message("flush postings as segment " + flushState.segmentName + " numDocs=" + numDocsInRAM);
-
boolean success = false;
+ SegmentInfo newSegment;
+
try {
+ assert nextDocID == numDocs;
+ assert waitQueue.numWaiting == 0;
+ assert waitQueue.waitingBytes == 0;
- if (closeDocStore) {
- assert flushState.docStoreSegmentName != null;
- assert flushState.docStoreSegmentName.equals(flushState.segmentName);
- closeDocStore();
- flushState.numDocsInStore = 0;
+ if (infoStream != null) {
+ message("flush postings as segment " + segment + " numDocs=" + numDocs);
}
- final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,
- numDocs, writer.getConfig().getTermIndexInterval(),
- SegmentCodecs.build(fieldInfos, writer.codecs));
++ final SegmentWriteState flushState = segWriteState();
+
+ newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false);
+
Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>();
- for(int i=0;i<threadStates.length;i++)
- threads.add(threadStates[i].consumer);
+ for (DocumentsWriterThreadState threadState : threadStates) {
+ threads.add(threadState.consumer);
+ }
+
+ long startNumBytesUsed = bytesUsed();
- final long startNumBytesUsed = bytesUsed();
consumer.flush(threads, flushState);
+ newSegment.setHasVectors(flushState.hasVectors);
if (infoStream != null) {
- SegmentInfo si = new SegmentInfo(flushState.segmentName,
- flushState.numDocs, directory, false, -1, flushState.segmentName,
- false, hasProx(), flushState.segmentCodecs);
- final long newSegmentSize = si.sizeInBytes();
- String message = " ramUsed=" + nf.format(startNumBytesUsed/1024./1024.) + " MB" +
- " newFlushedSize=" + newSegmentSize +
- " docs/MB=" + nf.format(numDocsInRAM/(newSegmentSize/1024./1024.)) +
- " new/old=" + nf.format(100.0*newSegmentSize/startNumBytesUsed) + "%";
- message(message);
+ message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors"));
+ message("flushedFiles=" + flushState.flushedFiles);
+ message("flushed codecs=" + newSegment.getSegmentCodecs());
}
- flushedDocCount += flushState.numDocs;
+ if (mergePolicy.useCompoundFile(segmentInfos, newSegment)) {
+ final String cfsFileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION);
- doAfterFlush();
+ if (infoStream != null) {
+ message("flush: create compound file \"" + cfsFileName + "\"");
+ }
- success = true;
+ CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, cfsFileName);
+ for(String fileName : flushState.flushedFiles) {
+ cfsWriter.addFile(fileName);
+ }
+ cfsWriter.close();
+ deleter.deleteNewFiles(flushState.flushedFiles);
+
+ newSegment.setUseCompoundFile(true);
+ }
+
+ if (infoStream != null) {
+ message("flush: segment=" + newSegment);
+ final long newSegmentSize = newSegment.sizeInBytes();
+ message(" ramUsed=" + nf.format(startNumBytesUsed / 1024. / 1024.) + " MB" +
+ " newFlushedSize=" + nf.format(newSegmentSize / 1024 / 1024) + " MB" +
+ " docs/MB=" + nf.format(numDocs / (newSegmentSize / 1024. / 1024.)) +
+ " new/old=" + nf.format(100.0 * newSegmentSize / startNumBytesUsed) + "%");
+ }
+ success = true;
} finally {
+ notifyAll();
if (!success) {
+ if (segment != null) {
+ deleter.refresh(segment);
+ }
abort();
}
}
- assert waitQueue.waitingBytes == 0;
+ doAfterFlush();
- return flushState.numDocs;
- }
+ // Lock order: IW -> DW -> BD
+ pushDeletes(newSegment, segmentInfos);
- Collection<String> getFlushedFiles() {
- return flushState.flushedFiles;
- }
-
- /** Build compound file for the segment we just flushed */
- void createCompoundFile(String segment) throws IOException {
-
- CompoundFileWriter cfsWriter = new CompoundFileWriter(directory,
- IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION));
- for(String fileName : flushState.flushedFiles) {
- cfsWriter.addFile(fileName);
- }
-
- // Perform the merge
- cfsWriter.close();
+ return newSegment;
}
-
- /** Set flushPending if it is not already set and returns
- * whether it was set. This is used by IndexWriter to
- * trigger a single flush even when multiple threads are
- * trying to do so. */
- synchronized boolean setFlushPending() {
- if (flushPending)
- return false;
- else {
- flushPending = true;
- return true;
- }
- }
-
- synchronized void clearFlushPending() {
- bufferIsFull = false;
- flushPending = false;
- }
-
- synchronized void pushDeletes() {
- deletesFlushed.update(deletesInRAM);
++
++ SegmentWriteState segWriteState() {
++ return new SegmentWriteState(infoStream, directory, segment, fieldInfos,
++ numDocs, writer.getConfig().getTermIndexInterval(),
++ SegmentCodecs.build(fieldInfos, writer.codecs), bytesUsed);
+ }
synchronized void close() {
closed = true;
diff --cc lucene/src/java/org/apache/lucene/index/FieldInfos.java
index ea5d528ca78,0fb4878b4be..70efdc407ba
--- a/lucene/src/java/org/apache/lucene/index/FieldInfos.java
+++ b/lucene/src/java/org/apache/lucene/index/FieldInfos.java
@@@ -100,7 -96,7 +100,7 @@@ public final class FieldInfos
List<Fieldable> fields = doc.getFields();
for (Fieldable field : fields) {
add(field.name(), field.isIndexed(), field.isTermVectorStored(), field.isStorePositionWithTermVector(),
-- field.isStoreOffsetWithTermVector(), field.getOmitNorms(), false, field.getOmitTermFreqAndPositions());
++ field.isStoreOffsetWithTermVector(), field.getOmitNorms(), false, field.getOmitTermFreqAndPositions(), field.docValuesType());
}
}
@@@ -199,7 -195,7 +199,7 @@@
synchronized public void add(String name, boolean isIndexed, boolean storeTermVector,
boolean storePositionWithTermVector, boolean storeOffsetWithTermVector, boolean omitNorms) {
add(name, isIndexed, storeTermVector, storePositionWithTermVector,
-- storeOffsetWithTermVector, omitNorms, false, false);
++ storeOffsetWithTermVector, omitNorms, false, false, null);
}
/** If the field is not yet known, adds it. If it is known, checks to make
@@@ -218,22 -214,29 +218,31 @@@
*/
synchronized public FieldInfo add(String name, boolean isIndexed, boolean storeTermVector,
boolean storePositionWithTermVector, boolean storeOffsetWithTermVector,
-- boolean omitNorms, boolean storePayloads, boolean omitTermFreqAndPositions) {
++ boolean omitNorms, boolean storePayloads, boolean omitTermFreqAndPositions, Type docValues) {
FieldInfo fi = fieldInfo(name);
if (fi == null) {
-- return addInternal(name, isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions);
++ return addInternal(name, isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions, docValues);
} else {
fi.update(isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions);
++ fi.setDocValues(docValues);
}
return fi;
}
+ synchronized public FieldInfo add(FieldInfo fi) {
+ return add(fi.name, fi.isIndexed, fi.storeTermVector,
+ fi.storePositionWithTermVector, fi.storeOffsetWithTermVector,
+ fi.omitNorms, fi.storePayloads,
- fi.omitTermFreqAndPositions);
++ fi.omitTermFreqAndPositions, fi.docValues);
+ }
+
private FieldInfo addInternal(String name, boolean isIndexed,
boolean storeTermVector, boolean storePositionWithTermVector,
-- boolean storeOffsetWithTermVector, boolean omitNorms, boolean storePayloads, boolean omitTermFreqAndPositions) {
++ boolean storeOffsetWithTermVector, boolean omitNorms, boolean storePayloads, boolean omitTermFreqAndPositions, Type docValuesType) {
name = StringHelper.intern(name);
FieldInfo fi = new FieldInfo(name, isIndexed, byNumber.size(), storeTermVector, storePositionWithTermVector,
storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions);
++ fi.setDocValues(docValuesType);
byNumber.add(fi);
byName.put(name, fi);
return fi;
@@@ -376,45 -340,8 +385,47 @@@
boolean omitNorms = (bits & OMIT_NORMS) != 0;
boolean storePayloads = (bits & STORE_PAYLOADS) != 0;
boolean omitTermFreqAndPositions = (bits & OMIT_TERM_FREQ_AND_POSITIONS) != 0;
- final FieldInfo fi = addInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions);
- final FieldInfo addInternal = addInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions);
- addInternal.codecId = codecId;
++ Type docValuesType = null;
+ if (format <= FORMAT_INDEX_VALUES) {
+ final byte b = input.readByte();
+ switch(b) {
+ case 0:
- fi.docValues = null;
++ docValuesType = null;
+ break;
+ case 1:
- fi.docValues = Type.PACKED_INTS;
++ docValuesType = Type.PACKED_INTS;
+ break;
+ case 2:
- fi.docValues = Type.SIMPLE_FLOAT_4BYTE;
++ docValuesType = Type.SIMPLE_FLOAT_4BYTE;
+ break;
+ case 3:
- fi.docValues = Type.SIMPLE_FLOAT_8BYTE;
++ docValuesType = Type.SIMPLE_FLOAT_8BYTE;
+ break;
+ case 4:
- fi.docValues = Type.BYTES_FIXED_STRAIGHT;
++ docValuesType = Type.BYTES_FIXED_STRAIGHT;
+ break;
+ case 5:
- fi.docValues = Type.BYTES_FIXED_DEREF;
++ docValuesType = Type.BYTES_FIXED_DEREF;
+ break;
+ case 6:
- fi.docValues = Type.BYTES_FIXED_SORTED;
++ docValuesType = Type.BYTES_FIXED_SORTED;
+ break;
+ case 7:
- fi.docValues = Type.BYTES_VAR_STRAIGHT;
++ docValuesType = Type.BYTES_VAR_STRAIGHT;
+ break;
+ case 8:
- fi.docValues = Type.BYTES_VAR_DEREF;
++ docValuesType = Type.BYTES_VAR_DEREF;
+ break;
+ case 9:
- fi.docValues = Type.BYTES_VAR_SORTED;
++ docValuesType = Type.BYTES_VAR_SORTED;
+ break;
+ default:
+ throw new IllegalStateException("unhandled indexValues type " + b);
+ }
+ }
++ final FieldInfo fi = addInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions, docValuesType);
++
+ fi.codecId = codecId;
}
if (input.getFilePointer() != input.length()) {
diff --cc lucene/src/java/org/apache/lucene/index/IndexReader.java
index 2130c221959,2e3a93ebaac..7f2aa6f8945
--- a/lucene/src/java/org/apache/lucene/index/IndexReader.java
+++ b/lucene/src/java/org/apache/lucene/index/IndexReader.java
@@@ -1416,16 -1418,9 +1422,16 @@@ public abstract class IndexReader imple
public int getTermInfosIndexDivisor() {
throw new UnsupportedOperationException("This reader does not support this method.");
}
-
+
+ public DocValues docValues(String field) throws IOException {
+ final Fields fields = fields();
+ if (fields == null) {
+ return null;
+ }
+ return fields.docValues(field);
+ }
- private Fields fields;
+ private volatile Fields fields;
/** @lucene.internal */
void storeFields(Fields fields) {
diff --cc lucene/src/java/org/apache/lucene/index/MultiFields.java
index a871ce87f7a,6abf54346bc..0943aacbdaa
--- a/lucene/src/java/org/apache/lucene/index/MultiFields.java
+++ b/lucene/src/java/org/apache/lucene/index/MultiFields.java
@@@ -19,14 -19,10 +19,14 @@@ package org.apache.lucene.index
import java.io.IOException;
import java.util.Map;
- import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
-import java.util.concurrent.ConcurrentHashMap;
+import org.apache.lucene.index.values.DocValues;
+import org.apache.lucene.index.values.MultiDocValues;
+import org.apache.lucene.index.values.Type;
+import org.apache.lucene.index.values.MultiDocValues.DocValuesIndex;
++import java.util.concurrent.ConcurrentHashMap;
import org.apache.lucene.util.ReaderUtil;
import org.apache.lucene.util.ReaderUtil.Gather; // for javadocs
import org.apache.lucene.util.Bits;
@@@ -50,8 -46,7 +50,8 @@@ import org.apache.lucene.util.BytesRef
public final class MultiFields extends Fields {
private final Fields[] subs;
private final ReaderUtil.Slice[] subSlices;
- private final Map<String,Terms> terms = new HashMap<String,Terms>();
- private final Map<String,DocValues> docValues = new HashMap<String,DocValues>();
+ private final Map<String,Terms> terms = new ConcurrentHashMap<String,Terms>();
++ private final Map<String,DocValues> docValues = new ConcurrentHashMap<String,DocValues>();
/** Returns a single {@link Fields} instance for this
* reader, merging fields/terms/docs/positions on the
@@@ -282,46 -271,5 +282,42 @@@
return result;
}
+
+ @Override
+ public DocValues docValues(String field) throws IOException {
- final DocValues result;
-
- if (!docValues.containsKey(field)) {
-
++ DocValues result = docValues.get(field);
++ if (result == null) {
+ // Lazy init: first time this field is requested, we
+ // create & add to docValues:
+ final List<MultiDocValues.DocValuesIndex> docValuesIndex = new ArrayList<MultiDocValues.DocValuesIndex>();
+ int docsUpto = 0;
+ Type type = null;
+ // Gather all sub-readers that share this field
+ for(int i=0;i<subs.length;i++) {
+ DocValues values = subs[i].docValues(field);
+ final int start = subSlices[i].start;
+ final int length = subSlices[i].length;
+ if (values != null) {
+ if (docsUpto != start) {
+ type = values.type();
+ docValuesIndex.add(new MultiDocValues.DocValuesIndex(new MultiDocValues.DummyDocValues(start, type), docsUpto, start - docsUpto));
+ }
+ docValuesIndex.add(new MultiDocValues.DocValuesIndex(values, start, length));
+ docsUpto = start+length;
+
+ } else if (i+1 == subs.length && !docValuesIndex.isEmpty()) {
+ docValuesIndex.add(new MultiDocValues.DocValuesIndex(
+ new MultiDocValues.DummyDocValues(start, type), docsUpto, start
+ - docsUpto));
+ }
-
+ }
- result = docValuesIndex.isEmpty()?null: new MultiDocValues(docValuesIndex.toArray(DocValuesIndex.EMPTY_ARRAY));
++ if (docValuesIndex.isEmpty()) {
++ return null;
++ }
++ result = new MultiDocValues(docValuesIndex.toArray(DocValuesIndex.EMPTY_ARRAY));
+ docValues.put(field, result);
- } else {
- result = docValues.get(field);
- }
-
- return result; }
-
-
++ }
++ return result;
++ }
}
diff --cc lucene/src/java/org/apache/lucene/index/PerFieldCodecWrapper.java
index 42eb222b01d,f7d4a1885d4..2decf76b178
--- a/lucene/src/java/org/apache/lucene/index/PerFieldCodecWrapper.java
+++ b/lucene/src/java/org/apache/lucene/index/PerFieldCodecWrapper.java
@@@ -110,16 -102,34 +110,34 @@@ final class PerFieldCodecWrapper extend
final int fieldCount = fieldInfos.size();
final Map<Codec, FieldsProducer> producers = new HashMap<Codec, FieldsProducer>();
- for (int i = 0; i < fieldCount; i++) {
- FieldInfo fi = fieldInfos.fieldInfo(i);
- if (fi.isIndexed || fi.hasDocValues()) { // TODO this does not work for non-indexed fields
- fields.add(fi.name);
- Codec codec = segmentCodecs.codecs[fi.codecId];
- if (!producers.containsKey(codec)) {
- producers.put(codec, codec.fieldsProducer(new SegmentReadState(dir,
- si, fieldInfos, readBufferSize, indexDivisor, ""+fi.codecId)));
+ boolean success = false;
+ try {
+ for (int i = 0; i < fieldCount; i++) {
+ FieldInfo fi = fieldInfos.fieldInfo(i);
- if (fi.isIndexed) { // TODO this does not work for non-indexed fields
++ if (fi.isIndexed || fi.hasDocValues()) { // TODO this does not work for non-indexed fields
+ fields.add(fi.name);
+ Codec codec = segmentCodecs.codecs[fi.codecId];
+ if (!producers.containsKey(codec)) {
+ producers.put(codec, codec.fieldsProducer(new SegmentReadState(dir,
+ si, fieldInfos, readBufferSize, indexDivisor, ""+fi.codecId)));
+ }
+ codecs.put(fi.name, producers.get(codec));
+ }
+ }
+ success = true;
+ } finally {
+ if (!success) {
+ // If we hit exception (eg, IOE because writer was
+ // committing, or, for any other reason) we must
+ // go back and close all FieldsProducers we opened:
+ for(FieldsProducer fp : producers.values()) {
+ try {
+ fp.close();
+ } catch (Throwable t) {
+ // Suppress all exceptions here so we continue
+ // to throw the original one
+ }
}
- codecs.put(fi.name, producers.get(codec));
}
}
}
diff --cc lucene/src/java/org/apache/lucene/index/SegmentMerger.java
index 5535bbe7725,9dc928678a4..36bf4da55c5
--- a/lucene/src/java/org/apache/lucene/index/SegmentMerger.java
+++ b/lucene/src/java/org/apache/lucene/index/SegmentMerger.java
@@@ -144,8 -121,9 +122,8 @@@ final class SegmentMerger
mergeTerms();
mergeNorms();
- if (mergeDocStores && fieldInfos.hasVectors())
+ if (fieldInfos.hasVectors())
mergeVectors();
-
return mergedDocs;
}
@@@ -154,10 -132,9 +132,8 @@@
// Basic files
for (String ext : IndexFileNames.COMPOUND_EXTENSIONS_NOT_CODEC) {
- if (mergeDocStores || (!ext.equals(IndexFileNames.FIELDS_EXTENSION) &&
- !ext.equals(IndexFileNames.FIELDS_INDEX_EXTENSION)))
- fileSet.add(IndexFileNames.segmentFileName(segment, "", ext));
+ fileSet.add(IndexFileNames.segmentFileName(segment, "", ext));
}
-
segmentWriteState.segmentCodecs.files(directory, info, fileSet);
// Fieldable norm files
@@@ -204,7 -181,7 +180,7 @@@
for (String field : names) {
fInfos.add(field, true, storeTermVectors,
storePositionWithTermVector, storeOffsetWithTermVector, !reader
-- .hasNorms(field), storePayloads, omitTFAndPositions);
++ .hasNorms(field), storePayloads, omitTFAndPositions, null);
}
}
@@@ -302,54 -261,43 +261,43 @@@
setMatchingSegmentReaders();
- if (mergeDocStores) {
- // merge field values
- final FieldsWriter fieldsWriter = new FieldsWriter(directory, segment, fieldInfos);
-
- try {
- int idx = 0;
- for (IndexReader reader : readers) {
- final SegmentReader matchingSegmentReader = matchingSegmentReaders[idx++];
- FieldsReader matchingFieldsReader = null;
- if (matchingSegmentReader != null) {
- final FieldsReader fieldsReader = matchingSegmentReader.getFieldsReader();
- if (fieldsReader != null) {
- matchingFieldsReader = fieldsReader;
- }
+ final FieldsWriter fieldsWriter = new FieldsWriter(directory, segment, fieldInfos);
+
+ try {
+ int idx = 0;
+ for (IndexReader reader : readers) {
+ final SegmentReader matchingSegmentReader = matchingSegmentReaders[idx++];
+ FieldsReader matchingFieldsReader = null;
+ if (matchingSegmentReader != null) {
+ final FieldsReader fieldsReader = matchingSegmentReader.getFieldsReader();
+ if (fieldsReader != null) {
+ matchingFieldsReader = fieldsReader;
}
- if (reader.hasDeletions()) {
- docCount += copyFieldsWithDeletions(fieldsWriter,
- reader, matchingFieldsReader);
- } else {
- docCount += copyFieldsNoDeletions(fieldsWriter,
+ }
+ if (reader.hasDeletions()) {
+ docCount += copyFieldsWithDeletions(fieldsWriter,
reader, matchingFieldsReader);
- }
+ } else {
+ docCount += copyFieldsNoDeletions(fieldsWriter,
+ reader, matchingFieldsReader);
}
- } finally {
- fieldsWriter.close();
}
+ } finally {
+ fieldsWriter.close();
+ }
- final String fileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.FIELDS_INDEX_EXTENSION);
- final long fdxFileLength = directory.fileLength(fileName);
-
- if (4+((long) docCount)*8 != fdxFileLength)
- // This is most likely a bug in Sun JRE 1.6.0_04/_05;
- // we detect that the bug has struck, here, and
- // throw an exception to prevent the corruption from
- // entering the index. See LUCENE-1282 for
- // details.
- throw new RuntimeException("mergeFields produced an invalid result: docCount is " + docCount + " but fdx file size is " + fdxFileLength + " file=" + fileName + " file exists?=" + directory.fileExists(fileName) + "; now aborting this merge to prevent index corruption");
+ final String fileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.FIELDS_INDEX_EXTENSION);
+ final long fdxFileLength = directory.fileLength(fileName);
- } else {
- // If we are skipping the doc stores, that means there
- // are no deletions in any of these segments, so we
- // just sum numDocs() of each segment to get total docCount
- for (final IndexReader reader : readers) {
- docCount += reader.numDocs();
- }
- }
+ if (4+((long) docCount)*8 != fdxFileLength)
+ // This is most likely a bug in Sun JRE 1.6.0_04/_05;
+ // we detect that the bug has struck, here, and
+ // throw an exception to prevent the corruption from
+ // entering the index. See LUCENE-1282 for
+ // details.
+ throw new RuntimeException("mergeFields produced an invalid result: docCount is " + docCount + " but fdx file size is " + fdxFileLength + " file=" + fileName + " file exists?=" + directory.fileExists(fileName) + "; now aborting this merge to prevent index corruption");
- segmentWriteState = new SegmentWriteState(null, directory, segment, fieldInfos, null, docCount, 0, termIndexInterval, codecInfo, new AtomicLong(0));
- segmentWriteState = new SegmentWriteState(null, directory, segment, fieldInfos, docCount, termIndexInterval, codecInfo);
++ segmentWriteState = new SegmentWriteState(null, directory, segment, fieldInfos, docCount, termIndexInterval, codecInfo, new AtomicLong(0));
return docCount;
}
diff --cc lucene/src/java/org/apache/lucene/index/SegmentWriteState.java
index 30d8db64c03,ae9477e76fa..cca418407a4
--- a/lucene/src/java/org/apache/lucene/index/SegmentWriteState.java
+++ b/lucene/src/java/org/apache/lucene/index/SegmentWriteState.java
@@@ -32,11 -31,9 +32,10 @@@ public class SegmentWriteState
public final Directory directory;
public final String segmentName;
public final FieldInfos fieldInfos;
- public final String docStoreSegmentName;
public final int numDocs;
- public int numDocsInStore;
+ public boolean hasVectors;
public final Collection<String> flushedFiles;
+ public final AtomicLong bytesUsed;
final SegmentCodecs segmentCodecs;
public final String codecId;
@@@ -63,8 -60,7 +62,7 @@@
public SegmentWriteState(PrintStream infoStream, Directory directory, String segmentName, FieldInfos fieldInfos,
- String docStoreSegmentName, int numDocs,
- int numDocsInStore, int termIndexInterval, SegmentCodecs segmentCodecs, AtomicLong bytesUsed) {
- int numDocs, int termIndexInterval, SegmentCodecs segmentCodecs) {
++ int numDocs, int termIndexInterval, SegmentCodecs segmentCodecs, AtomicLong bytesUsed) {
this.infoStream = infoStream;
this.directory = directory;
this.segmentName = segmentName;
diff --cc lucene/src/java/org/apache/lucene/index/codecs/FieldsConsumer.java
index 27d1a87d0c1,8389df02600..33fd19d732c
--- a/lucene/src/java/org/apache/lucene/index/codecs/FieldsConsumer.java
+++ b/lucene/src/java/org/apache/lucene/index/codecs/FieldsConsumer.java
@@@ -20,11 -20,6 +20,9 @@@ package org.apache.lucene.index.codecs
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.FieldsEnum;
- import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.TermsEnum;
+import org.apache.lucene.index.codecs.docvalues.DocValuesConsumer;
+import org.apache.lucene.index.values.DocValues;
- import org.apache.lucene.index.values.Writer;
import java.io.IOException;
import java.io.Closeable;
@@@ -42,13 -35,6 +38,11 @@@ public abstract class FieldsConsumer im
/** Add a new field */
public abstract TermsConsumer addField(FieldInfo field) throws IOException;
+
+ /** Adds a new DocValuesField */
+ public DocValuesConsumer addValuesField(FieldInfo field) throws IOException {
+ throw new UnsupportedOperationException("docvalues are not supported");
+ }
-
-
/** Called when we are done adding everything. */
public abstract void close() throws IOException;
@@@ -59,24 -45,8 +53,25 @@@
String field;
while((field = fieldsEnum.next()) != null) {
mergeState.fieldInfo = mergeState.fieldInfos.fieldInfo(field);
- final TermsConsumer termsConsumer = addField(mergeState.fieldInfo);
- termsConsumer.merge(mergeState, fieldsEnum.terms());
+ assert mergeState.fieldInfo != null : "FieldInfo for field is null: "+ field;
+ TermsEnum terms = fieldsEnum.terms();
+ if(terms != null) {
+ final TermsConsumer termsConsumer = addField(mergeState.fieldInfo);
+ termsConsumer.merge(mergeState, terms);
+ }
+ if (mergeState.fieldInfo.hasDocValues()) {
+ final DocValues docValues = fieldsEnum.docValues();
- // TODO: is this assert values and if so when?
- // assert docValues != null : "DocValues are null for " + mergeState.fieldInfo.getDocValues();
- if(docValues == null) { // for now just continue
++ if(docValues == null) {
++ /* It is actually possible that a fieldInfo has a values type but no values are actually available.
++ * this can happen if there are already segments without values around.
++ */
+ continue;
+ }
+ final DocValuesConsumer docValuesConsumer = addValuesField(mergeState.fieldInfo);
+ assert docValuesConsumer != null;
+ docValuesConsumer.merge(mergeState, docValues);
+ }
}
}
+
}
diff --cc lucene/src/java/org/apache/lucene/index/values/Bytes.java
index 5dabb6cdd41,00000000000..65346296f0f
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/Bytes.java
+++ b/lucene/src/java/org/apache/lucene/index/values/Bytes.java
@@@ -1,411 -1,0 +1,411 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * 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.
+ */
+
+/** Base class for specific Bytes Reader/Writer implementations */
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.index.values.DocValues.MissingValue;
+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;
+import org.apache.lucene.util.PagedBytes;
+
+/**
+ * Provides concrete Writer/Reader impls for byte[] value per document. There
+ * are 6 package-private impls of this, for all combinations of
+ * STRAIGHT/DEREF/SORTED X fixed/not fixed.
+ *
+ * <p>
+ * NOTE: The total amount of byte[] data stored (across a single segment) cannot
+ * exceed 2GB.
+ * </p>
+ * <p>
+ * NOTE: Each byte[] must be <= 32768 bytes in length
+ * </p>
+ * @lucene.experimental
+ */
- // TODO - add bulk copy where possible
+public final class Bytes {
++ //TODO - add bulk copy where possible
++ private Bytes() { /* don't instantiate! */ }
+
- // don't instantiate!
- private Bytes() {
- }
-
++ /**
++ *
++ *
++ */
+ public static enum Mode {
+ STRAIGHT, DEREF, SORTED
+ };
+
+ // TODO -- i shouldn't have to specify fixed? can
+ // track itself & do the write thing at write time?
+ public static Writer getWriter(Directory dir, String id, Mode mode,
+ Comparator<BytesRef> comp, boolean fixedSize, AtomicLong bytesUsed) throws IOException {
+
+ if (comp == null) {
+ comp = BytesRef.getUTF8SortedAsUnicodeComparator();
+ }
+
+ if (fixedSize) {
+ if (mode == Mode.STRAIGHT) {
+ return new FixedStraightBytesImpl.Writer(dir, id);
+ } else if (mode == Mode.DEREF) {
+ return new FixedDerefBytesImpl.Writer(dir, id, bytesUsed);
+ } else if (mode == Mode.SORTED) {
+ return new FixedSortedBytesImpl.Writer(dir, id, comp, bytesUsed);
+ }
+ } else {
+ if (mode == Mode.STRAIGHT) {
+ return new VarStraightBytesImpl.Writer(dir, id, bytesUsed);
+ } else if (mode == Mode.DEREF) {
+ return new VarDerefBytesImpl.Writer(dir, id, bytesUsed);
+ } else if (mode == Mode.SORTED) {
+ return new VarSortedBytesImpl.Writer(dir, id, comp, bytesUsed);
+ }
+ }
+
+ throw new IllegalArgumentException("");
+ }
+
+ // 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) {
+ if (mode == Mode.STRAIGHT) {
+ try {
+ return new FixedStraightBytesImpl.Reader(dir, id, maxDoc);
+ } catch (IOException e) {
+ throw e;
+ }
+ } else if (mode == Mode.DEREF) {
+ try {
+ return new FixedDerefBytesImpl.Reader(dir, id, maxDoc);
+ } catch (IOException e) {
+ throw e;
+ }
+ } else if (mode == Mode.SORTED) {
+ return new FixedSortedBytesImpl.Reader(dir, id, maxDoc);
+ }
+ } else {
+ if (mode == Mode.STRAIGHT) {
+ return new VarStraightBytesImpl.Reader(dir, id, maxDoc);
+ } else if (mode == Mode.DEREF) {
+ return new VarDerefBytesImpl.Reader(dir, id, maxDoc);
+ } else if (mode == Mode.SORTED) {
+ return new VarSortedBytesImpl.Reader(dir, id, maxDoc);
+ }
+ }
+
+ throw new IllegalArgumentException("");
+ }
+
+ static abstract class BytesBaseSource extends Source {
+ protected final IndexInput datIn;
+ protected final IndexInput idxIn;
+ 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();
+ this.datIn = datIn;
+ this.totalLengthInBytes = bytesToRead;
+ this.pagedBytes = pagedBytes;
+ this.pagedBytes.copy(datIn, bytesToRead);
+ data = pagedBytes.freeze(true);
+ this.idxIn = idxIn;
+ }
+
+ public void close() throws IOException {
+ data.close();
+ try {
+ if (datIn != null)
+ datIn.close();
+ } finally {
+ if (idxIn != null) // if straight - no index needed
+ idxIn.close();
+ }
+ }
+
+ protected abstract int maxDoc();
+
+ public long ramBytesUsed() {
+ return 0; // TODO
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource attrSource) throws IOException {
+ final MissingValue missing = getMissing();
+ return new SourceEnum(attrSource, type(), this, maxDoc()) {
+ @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 BytesBaseSortedSource extends SortedSource {
+ 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 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();
+ this.datIn = datIn;
+ this.pagedBytes = pagedBytes;
+ this.pagedBytes.copy(datIn, bytesToRead);
+ data = pagedBytes.freeze(true);
+ this.idxIn = idxIn;
+ this.comp = comp == null ? BytesRef.getUTF8SortedAsUnicodeComparator()
+ : comp;
+
+ }
+
+ @Override
+ public BytesRef getByOrd(int ord, BytesRef bytesRef) {
+ return ord == 0 ? null : deref(--ord, bytesRef);
+ }
+
+ public void close() throws IOException {
+ if (datIn != null)
+ datIn.close();
+ if (idxIn != null) // if straight
+ idxIn.close();
+ }
+
+ 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, bytesRef);
+ final int cmp = comp.compare(bytesRef, b);
+ if (cmp < 0) {
+ low = mid + 1;
+ } else if (cmp > 0) {
+ high = mid - 1;
+ } else {
+ lookupResult.ord = mid + 1;
+ lookupResult.found = true;
+ return lookupResult;
+ }
+ }
+ assert comp.compare(bytesRef, b) != 0;
+ lookupResult.ord = low;
+ lookupResult.found = false;
+ return lookupResult;
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource attrSource) throws IOException {
+ final MissingValue missing = getMissing();
+ return new SourceEnum(attrSource, type(), this, maxDoc()) {
+
+ @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 {
+
+ private final Directory dir;
+ private final String id;
+ protected IndexOutput idxOut;
+ protected IndexOutput datOut;
+ protected BytesRef bytesRef;
+ private final String codecName;
+ private final int version;
+ protected final ByteBlockPool pool;
+
+ protected BytesWriterBase(Directory dir, String id, String codecName,
+ int version, boolean initIndex, boolean initData, ByteBlockPool pool,
+ AtomicLong bytesUsed) throws IOException {
+ super(bytesUsed);
+ this.dir = dir;
+ this.id = id;
+ this.codecName = codecName;
+ this.version = version;
+ this.pool = pool;
+ if (initData)
+ initDataOut();
+ if (initIndex)
+ initIndexOut();
+ }
+
- protected void initDataOut() throws IOException {
++ private void initDataOut() throws IOException {
+ datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",
+ DATA_EXTENSION));
+ CodecUtil.writeHeader(datOut, codecName, version);
+ }
+
- protected void initIndexOut() throws IOException {
++ private void initIndexOut() throws IOException {
+ idxOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",
+ INDEX_EXTENSION));
+ CodecUtil.writeHeader(idxOut, codecName, version);
+ }
+
+ public long ramBytesUsed() {
+ return bytesUsed.get();
+ }
+
+ /**
+ * Must be called only with increasing docIDs. It's OK for some docIDs to be
+ * skipped; they will be filled with 0 bytes.
+ */
+ @Override
+ public abstract void add(int docID, BytesRef bytes) throws IOException;
+
+ @Override
+ public synchronized void finish(int docCount) throws IOException {
+ if (datOut != null)
+ datOut.close();
+ if (idxOut != null)
+ idxOut.close();
+ if (pool != null)
+ pool.reset();
+ }
+
+ @Override
+ protected void add(int docID) throws IOException {
+ add(docID, bytesRef);
+ }
+
+
+ @Override
+ public void add(int docID, PerDocFieldValues docValues) throws IOException {
+ final BytesRef ref;
+ if ((ref = docValues.getBytes()) != null) {
+ add(docID, ref);
+ }
+ }
+
+ @Override
+ protected void setNextEnum(DocValuesEnum valuesEnum) {
+ bytesRef = valuesEnum.bytes();
+ }
+
+ @Override
+ public void files(Collection<String> files) throws IOException {
+ assert datOut != null;
+ files.add(IndexFileNames.segmentFileName(id, "", DATA_EXTENSION));
+ if (idxOut != null) { // called after flush - so this must be initialized
+ // if needed or present
+ final String idxFile = IndexFileNames.segmentFileName(id, "",
+ INDEX_EXTENSION);
+ files.add(idxFile);
+ }
+ }
+ }
+
+ /**
+ * Opens all necessary files, but does not read any data in until you call
+ * {@link #load}.
+ */
+ static abstract class BytesReaderBase extends DocValues {
+ protected final IndexInput idxIn;
+ protected final IndexInput datIn;
+ protected final int version;
+ protected final String id;
+
+ protected BytesReaderBase(Directory dir, String id, String codecName,
+ int maxVersion, boolean doIndex) throws IOException {
+ this.id = id;
+ datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",
+ Writer.DATA_EXTENSION));
+ version = CodecUtil.checkHeader(datIn, codecName, maxVersion, maxVersion);
-
+ if (doIndex) {
+ idxIn = dir.openInput(IndexFileNames.segmentFileName(id, "",
+ Writer.INDEX_EXTENSION));
+ final int version2 = CodecUtil.checkHeader(idxIn, codecName,
+ maxVersion, maxVersion);
+ assert version == version2;
+ } else {
+ idxIn = null;
+ }
+
+ }
+
+ protected final IndexInput cloneData() {
+ assert datIn != null;
+ return (IndexInput) datIn.clone();
+ }
+
+ protected final IndexInput cloneIndex() { // TODO assert here for null
+ // rather than return null
+ return idxIn == null ? null : (IndexInput) idxIn.clone();
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+ if (datIn != null) {
+ datIn.close();
+ }
+ if (idxIn != null) {
+ idxIn.close();
+ }
+ }
+ }
+
+}
diff --cc lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java
index 15962b84548,00000000000..04da04ce9fd
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java
+++ b/lucene/src/java/org/apache/lucene/index/values/FixedDerefBytesImpl.java
@@@ -1,278 -1,0 +1,276 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * 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.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.index.values.Bytes.BytesBaseSource;
+import org.apache.lucene.index.values.Bytes.BytesReaderBase;
+import org.apache.lucene.index.values.Bytes.BytesWriterBase;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.AttributeSource;
+import org.apache.lucene.util.ByteBlockPool;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefHash;
+import org.apache.lucene.util.PagedBytes;
+import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.ByteBlockPool.Allocator;
+import org.apache.lucene.util.ByteBlockPool.DirectAllocator;
+import org.apache.lucene.util.BytesRefHash.TrackingDirectBytesStartArray;
+import org.apache.lucene.util.packed.PackedInts;
+
+// Stores fixed-length byte[] by deref, ie when two docs
+// have the same value, they store only 1 byte[]
+/**
+ * @lucene.experimental
+ */
+class FixedDerefBytesImpl {
+
+ static final String CODEC_NAME = "FixedDerefBytes";
+ static final int VERSION_START = 0;
+ static final int VERSION_CURRENT = VERSION_START;
+
+ static class Writer extends BytesWriterBase {
+ private int size = -1;
+ private int[] docToID;
- private final BytesRefHash hash = new BytesRefHash(pool, BytesRefHash.DEFAULT_CAPACITY,
- new TrackingDirectBytesStartArray(BytesRefHash.DEFAULT_CAPACITY, bytesUsed));
++ private final BytesRefHash hash = new BytesRefHash(pool,
++ BytesRefHash.DEFAULT_CAPACITY, new TrackingDirectBytesStartArray(
++ BytesRefHash.DEFAULT_CAPACITY, bytesUsed));
+
- public Writer(Directory dir, String id, AtomicLong bytesUsed) throws IOException {
++ public Writer(Directory dir, String id, AtomicLong bytesUsed)
++ throws IOException {
+ this(dir, id, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE),
+ bytesUsed);
+ }
+
+ public Writer(Directory dir, String id, Allocator allocator,
+ AtomicLong bytesUsed) throws IOException {
- super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false,
++ super(dir, id, CODEC_NAME, VERSION_CURRENT, true, true,
+ new ByteBlockPool(allocator), bytesUsed);
+ docToID = new int[1];
- bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT); // TODO BytesRefHash uses bytes too!
++ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT); // TODO BytesRefHash
++ // uses bytes too!
+ }
+
+ @Override
+ synchronized public void add(int docID, BytesRef bytes) throws IOException {
+ if (bytes.length == 0) // default value - skip it
+ return;
+ if (size == -1) {
+ size = bytes.length;
- initDataOut();
+ datOut.writeInt(size);
+ } else if (bytes.length != size) {
+ throw new IllegalArgumentException("expected bytes size=" + size
+ + " but got " + bytes.length);
+ }
+ int ord = hash.add(bytes);
+
+ if (ord >= 0) {
+ // new added entry
+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);
+ } else {
+ ord = (-ord) - 1;
+ }
+
+ if (docID >= docToID.length) {
+ final int size = docToID.length;
+ docToID = ArrayUtil.grow(docToID, 1 + docID);
+ bytesUsed.addAndGet((docToID.length - size)
+ * RamUsageEstimator.NUM_BYTES_INT);
+ }
+ docToID[docID] = 1 + ord;
+ }
+
+ // Important that we get docCount, in case there were
+ // some last docs that we didn't see
+ @Override
+ synchronized public void finish(int docCount) throws IOException {
- if (datOut == null) // no added data
- return;
- initIndexOut();
- final int count = 1 + hash.size();
- idxOut.writeInt(count - 1);
- // write index
- final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,
- PackedInts.bitsRequired(count - 1));
- final int limit = docCount > docToID.length ? docToID.length : docCount;
- for (int i = 0; i < limit; i++) {
- w.add(docToID[i]);
- }
- // fill up remaining doc with zeros
- for (int i = limit; i < docCount; i++) {
- w.add(0);
++ try {
++ if (size == -1) {
++ datOut.writeInt(size);
++ }
++ final int count = 1 + hash.size();
++ idxOut.writeInt(count - 1);
++ // write index
++ final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,
++ PackedInts.bitsRequired(count - 1));
++ final int limit = docCount > docToID.length ? docToID.length : docCount;
++ for (int i = 0; i < limit; i++) {
++ w.add(docToID[i]);
++ }
++ // fill up remaining doc with zeros
++ for (int i = limit; i < docCount; i++) {
++ w.add(0);
++ }
++ w.finish();
++ } finally {
++ hash.close();
++ super.finish(docCount);
++ bytesUsed
++ .addAndGet((-docToID.length) * RamUsageEstimator.NUM_BYTES_INT);
++ docToID = null;
+ }
- w.finish();
- hash.close();
- super.finish(docCount);
- bytesUsed.addAndGet((-docToID.length)
- * RamUsageEstimator.NUM_BYTES_INT);
- docToID = null;
+ }
+ }
+
+ public static class Reader extends BytesReaderBase {
+ private final int size;
+
+ Reader(Directory dir, String id, int maxDoc) throws IOException {
+ super(dir, id, CODEC_NAME, VERSION_START, true);
- try {
- size = datIn.readInt();
- } catch (IOException e) {
- throw e;
- }
++ size = datIn.readInt();
+ }
+
+ @Override
+ public Source load() throws IOException {
+ final IndexInput index = cloneIndex();
+ return new Source(cloneData(), index, size, index.readInt());
+ }
+
+ private static class Source extends BytesBaseSource {
+ 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 {
+ super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), size * numValues);
+ this.size = size;
+ this.numValues = numValues;
+ index = PackedInts.getReader(idxIn);
+ }
+
+ @Override
+ public BytesRef getBytes(int docID, BytesRef bytesRef) {
+ final int id = (int) index.get(docID);
+ if (id == 0) {
+ return null;
+ }
+ return data.fillSlice(bytesRef, ((id - 1) * size), size);
+ }
+
+ @Override
+ public int getValueCount() {
+ return numValues;
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_FIXED_DEREF;
+ }
+
+ @Override
+ protected int maxDoc() {
+ return index.size();
+ }
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource source) throws IOException {
- return new DerefBytesEnum(source, cloneData(), cloneIndex(),
- size);
++ return new DerefBytesEnum(source, cloneData(), cloneIndex(), size);
+ }
+
+ static class DerefBytesEnum extends DocValuesEnum {
+ protected final IndexInput datIn;
+ private final PackedInts.ReaderIterator idx;
+ protected final long fp;
+ private final int size;
+ private final int valueCount;
+ private int pos = -1;
+
+ public DerefBytesEnum(AttributeSource source, IndexInput datIn,
+ IndexInput idxIn, int size) throws IOException {
+ this(source, datIn, idxIn, size, Type.BYTES_FIXED_DEREF);
+ }
+
+ protected DerefBytesEnum(AttributeSource source, IndexInput datIn,
- IndexInput idxIn, int size, Type enumType)
- throws IOException {
++ IndexInput idxIn, int size, Type enumType) throws IOException {
+ super(source, enumType);
+ this.datIn = datIn;
+ this.size = size;
+ idxIn.readInt();// read valueCount
+ idx = PackedInts.getReaderIterator(idxIn);
+ fp = datIn.getFilePointer();
+ bytesRef.grow(this.size);
+ bytesRef.length = this.size;
+ bytesRef.offset = 0;
+ valueCount = idx.size();
+ }
-
+
+ protected void copyReferences(DocValuesEnum valuesEnum) {
+ bytesRef = valuesEnum.bytesRef;
- if(bytesRef.bytes.length < size) {
++ if (bytesRef.bytes.length < size) {
+ bytesRef.grow(size);
+ }
+ bytesRef.length = size;
+ bytesRef.offset = 0;
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ if (target < valueCount) {
+ long address;
+ while ((address = idx.advance(target)) == 0) {
+ if (++target >= valueCount) {
+ return pos = NO_MORE_DOCS;
+ }
+ }
+ pos = idx.ord();
+ fill(address, bytesRef);
+ return pos;
+ }
+ return pos = NO_MORE_DOCS;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ if (pos >= valueCount) {
+ return pos = NO_MORE_DOCS;
+ }
+ return advance(pos + 1);
+ }
+
+ public void close() throws IOException {
+ datIn.close();
+ idx.close();
+ }
+
+ protected void fill(long address, BytesRef ref) throws IOException {
+ datIn.seek(fp + ((address - 1) * size));
+ datIn.readBytes(ref.bytes, 0, size);
+ ref.length = size;
+ ref.offset = 0;
+ }
+
+ @Override
+ public int docID() {
+ return pos;
+ }
+
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_FIXED_DEREF;
+ }
+ }
+
+}
diff --cc lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java
index 583d93b3d7b,00000000000..108f382b480
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java
+++ b/lucene/src/java/org/apache/lucene/index/values/FixedSortedBytesImpl.java
@@@ -1,240 -1,0 +1,241 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * 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.Comparator;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.index.values.Bytes.BytesBaseSortedSource;
+import org.apache.lucene.index.values.Bytes.BytesReaderBase;
+import org.apache.lucene.index.values.Bytes.BytesWriterBase;
+import org.apache.lucene.index.values.FixedDerefBytesImpl.Reader.DerefBytesEnum;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.AttributeSource;
+import org.apache.lucene.util.ByteBlockPool;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefHash;
+import org.apache.lucene.util.CodecUtil;
+import org.apache.lucene.util.PagedBytes;
+import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.ByteBlockPool.Allocator;
+import org.apache.lucene.util.ByteBlockPool.DirectAllocator;
+import org.apache.lucene.util.BytesRefHash.TrackingDirectBytesStartArray;
+import org.apache.lucene.util.packed.PackedInts;
+
+// Stores fixed-length byte[] by deref, ie when two docs
+// have the same value, they store only 1 byte[]
+
+/**
+ * @lucene.experimental
+ */
+class FixedSortedBytesImpl {
+
+ static final String CODEC_NAME = "FixedSortedBytes";
+ static final int VERSION_START = 0;
+ static final int VERSION_CURRENT = VERSION_START;
+
+ static class Writer extends BytesWriterBase {
+ private int size = -1;
+ private int[] docToEntry;
+ private final Comparator<BytesRef> comp;
+
- private final BytesRefHash hash = new BytesRefHash(pool, BytesRefHash.DEFAULT_CAPACITY,
- new TrackingDirectBytesStartArray(BytesRefHash.DEFAULT_CAPACITY, bytesUsed));
++ private final BytesRefHash hash = new BytesRefHash(pool,
++ BytesRefHash.DEFAULT_CAPACITY, new TrackingDirectBytesStartArray(
++ BytesRefHash.DEFAULT_CAPACITY, bytesUsed));
+
- public Writer(Directory dir, String id, Comparator<BytesRef> comp, AtomicLong bytesUsed)
- throws IOException {
++ public Writer(Directory dir, String id, Comparator<BytesRef> comp,
++ AtomicLong bytesUsed) throws IOException {
+ this(dir, id, comp, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE),
+ bytesUsed);
+ }
+
+ public Writer(Directory dir, String id, Comparator<BytesRef> comp,
+ Allocator allocator, AtomicLong bytesUsed) throws IOException {
- super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false,
++ super(dir, id, CODEC_NAME, VERSION_CURRENT, true, true,
+ new ByteBlockPool(allocator), bytesUsed);
+ docToEntry = new int[1];
+ // docToEntry[0] = -1;
+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);
+ this.comp = comp;
+ }
+
+ @Override
+ synchronized public void add(int docID, BytesRef bytes) throws IOException {
+ if (bytes.length == 0)
+ return; // default - skip it
+ if (size == -1) {
+ size = bytes.length;
- initDataOut();
+ datOut.writeInt(size);
+ } else if (bytes.length != size) {
+ throw new IllegalArgumentException("expected bytes size=" + size
+ + " but got " + bytes.length);
+ }
+ if (docID >= docToEntry.length) {
- int[] newArray = new int[ArrayUtil.oversize(1 + docID,
++ final int[] newArray = new int[ArrayUtil.oversize(1 + docID,
+ RamUsageEstimator.NUM_BYTES_INT)];
+ System.arraycopy(docToEntry, 0, newArray, 0, docToEntry.length);
- // Arrays.fill(newArray, docToEntry.length, newArray.length, -1);
-
+ bytesUsed.addAndGet((newArray.length - docToEntry.length)
+ * RamUsageEstimator.NUM_BYTES_INT);
+ docToEntry = newArray;
+ }
+ int e = hash.add(bytes);
+ docToEntry[docID] = 1 + (e < 0 ? (-e) - 1 : e);
+ }
+
+ // Important that we get docCount, in case there were
+ // some last docs that we didn't see
+ @Override
+ synchronized public void finish(int docCount) throws IOException {
- if (datOut == null)// no data added
- return;
- initIndexOut();
- final int[] sortedEntries = hash.sort(comp);
- final int count = hash.size();
- int[] address = new int[count];
- // first dump bytes data, recording address as we go
- for (int i = 0; i < count; i++) {
- final int e = sortedEntries[i];
- final BytesRef bytes = hash.get(e, new BytesRef());
- assert bytes.length == size;
- datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);
- address[e] = 1 + i;
- }
++ try {
++ if (size == -1) {// no data added
++ datOut.writeInt(size);
++ }
++ final int[] sortedEntries = hash.sort(comp);
++ final int count = hash.size();
++ int[] address = new int[count];
++ // first dump bytes data, recording address as we go
++ for (int i = 0; i < count; i++) {
++ final int e = sortedEntries[i];
++ final BytesRef bytes = hash.get(e, new BytesRef());
++ assert bytes.length == size;
++ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);
++ address[e] = 1 + i;
++ }
+
- idxOut.writeInt(count);
++ idxOut.writeInt(count);
+
- // next write index
- PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount, PackedInts
- .bitsRequired(count));
- final int limit;
- if (docCount > docToEntry.length) {
- limit = docToEntry.length;
- } else {
- limit = docCount;
- }
- for (int i = 0; i < limit; i++) {
- final int e = docToEntry[i];
- if (e == 0) {
- // null is encoded as zero
- w.add(0);
++ // next write index
++ PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,
++ PackedInts.bitsRequired(count));
++ final int limit;
++ if (docCount > docToEntry.length) {
++ limit = docToEntry.length;
+ } else {
- assert e > 0 && e <= count : "index must 0 > && <= " + count
- + " was: " + e;
- w.add(address[e - 1]);
++ limit = docCount;
++ }
++ for (int i = 0; i < limit; i++) {
++ final int e = docToEntry[i];
++ if (e == 0) {
++ // null is encoded as zero
++ w.add(0);
++ } else {
++ assert e > 0 && e <= count : "index must 0 > && <= " + count
++ + " was: " + e;
++ w.add(address[e - 1]);
++ }
+ }
- }
+
- for (int i = limit; i < docCount; i++) {
- w.add(0);
++ for (int i = limit; i < docCount; i++) {
++ w.add(0);
++ }
++ w.finish();
++ } finally {
++ super.finish(docCount);
++ bytesUsed.addAndGet((-docToEntry.length)
++ * RamUsageEstimator.NUM_BYTES_INT);
++ docToEntry = null;
++ hash.close();
+ }
- w.finish();
-
- super.finish(docCount);
- bytesUsed.addAndGet((-docToEntry.length)
- * RamUsageEstimator.NUM_BYTES_INT);
- docToEntry = null;
- hash.close();
+ }
+ }
+
+ public static class Reader extends BytesReaderBase {
+ private final int size;
+
+ public Reader(Directory dir, String id, int maxDoc) throws IOException {
+ super(dir, id, CODEC_NAME, VERSION_START, true);
+ size = datIn.readInt();
+ }
+
+ @Override
+ public org.apache.lucene.index.values.DocValues.Source load()
+ throws IOException {
+ return loadSorted(null);
+ }
+
+ @Override
+ public SortedSource loadSorted(Comparator<BytesRef> comp)
+ throws IOException {
+ final IndexInput idxInput = cloneIndex();
+ final IndexInput datInput = cloneData();
+ datInput.seek(CodecUtil.headerLength(CODEC_NAME) + 4);
+ idxInput.seek(CodecUtil.headerLength(CODEC_NAME));
+ return new Source(datInput, idxInput, size, idxInput.readInt(), comp);
+ }
+
+ private static class Source extends BytesBaseSortedSource {
+
+ private final PackedInts.Reader index;
+ private final int numValue;
+ private final int size;
+
- public Source(IndexInput datIn, IndexInput idxIn, int size, int numValues,
- Comparator<BytesRef> comp) throws IOException {
- super(datIn, idxIn, comp, new PagedBytes(PAGED_BYTES_BITS), size*numValues );
++ public Source(IndexInput datIn, IndexInput idxIn, int size,
++ int numValues, Comparator<BytesRef> comp) throws IOException {
++ super(datIn, idxIn, comp, new PagedBytes(PAGED_BYTES_BITS), size
++ * numValues);
+ this.size = size;
+ this.numValue = numValues;
+ index = PackedInts.getReader(idxIn);
+ }
+
+ @Override
+ public int ord(int docID) {
+ return (int) index.get(docID);
+ }
+
+ @Override
+ public LookupResult getByValue(BytesRef bytes, BytesRef tmpRef) {
+ return binarySearch(bytes, tmpRef, 0, numValue - 1);
+ }
+
+ @Override
+ public int getValueCount() {
+ return numValue;
+ }
++
+ @Override
+ protected BytesRef deref(int ord, BytesRef bytesRef) {
- return data.fillSlice(bytesRef, (ord* size), size);
++ return data.fillSlice(bytesRef, (ord * size), size);
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_FIXED_SORTED;
+ }
+
+ @Override
+ protected int maxDoc() {
+ return index.size();
+ }
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource source) throws IOException {
+ // do unsorted
- return new DerefBytesEnum(source, cloneData(), cloneIndex(),
- size);
++ return new DerefBytesEnum(source, cloneData(), cloneIndex(), size);
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_FIXED_SORTED;
+ }
+ }
+}
diff --cc lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java
index 77d51a6f431,00000000000..a907eefea23
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java
+++ b/lucene/src/java/org/apache/lucene/index/values/FixedStraightBytesImpl.java
@@@ -1,235 -1,0 +1,244 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.IOException;
+
+import org.apache.lucene.index.values.Bytes.BytesBaseSource;
+import org.apache.lucene.index.values.Bytes.BytesReaderBase;
+import org.apache.lucene.index.values.Bytes.BytesWriterBase;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.AttributeSource;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.PagedBytes;
+
+// Simplest storage: stores fixed length byte[] per
+// document, with no dedup and no sorting.
+/**
+ * @lucene.experimental
+ */
+class FixedStraightBytesImpl {
+
+ static final String CODEC_NAME = "FixedStraightBytes";
+ static final int VERSION_START = 0;
+ static final int VERSION_CURRENT = VERSION_START;
+
+ static class Writer extends BytesWriterBase {
+ private int size = -1;
+ // start at -1 if the first added value is > 0
+ private int lastDocID = -1;
+ private byte[] oneRecord;
+
+ protected Writer(Directory dir, String id) throws IOException {
- super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false, null, null);
++ super(dir, id, CODEC_NAME, VERSION_CURRENT, false, true, null, null);
+ }
-
++
+ // TODO - impl bulk copy here!
+
+ @Override
+ synchronized public void add(int docID, BytesRef bytes) throws IOException {
+ if (size == -1) {
+ size = bytes.length;
- initDataOut();
+ datOut.writeInt(size);
+ oneRecord = new byte[size];
+ } else if (bytes.length != size) {
- throw new IllegalArgumentException("expected bytes size=" + size + " but got " + bytes.length);
++ throw new IllegalArgumentException("expected bytes size=" + size
++ + " but got " + bytes.length);
+ }
+ fill(docID);
+ assert bytes.bytes.length >= bytes.length;
+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);
+ }
+
- /* (non-Javadoc)
- * @see org.apache.lucene.index.values.Writer#merge(org.apache.lucene.index.values.Writer.MergeState)
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * org.apache.lucene.index.values.Writer#merge(org.apache.lucene.index.values
++ * .Writer.MergeState)
+ */
+ @Override
+ protected void merge(MergeState state) throws IOException {
- if(state.bits == null && state.reader instanceof Reader){
++ if (state.bits == null && state.reader instanceof Reader) {
+ Reader reader = (Reader) state.reader;
+ final int maxDocs = reader.maxDoc;
- if(maxDocs == 0)
++ if (maxDocs == 0)
+ return;
- if(size == -1) {
++ if (size == -1) {
+ size = reader.size;
- initDataOut();
+ datOut.writeInt(size);
+ oneRecord = new byte[size];
+ }
- fill(state.docBase);
- // TODO should we add a transfer to API to each reader?
- datOut.copyBytes(reader.cloneData(), size * maxDocs);
- lastDocID += maxDocs-1;
++ fill(state.docBase);
++ // TODO should we add a transfer to API to each reader?
++ datOut.copyBytes(reader.cloneData(), size * maxDocs);
++ lastDocID += maxDocs - 1;
+ } else
+ super.merge(state);
+ }
+
+ // Fills up to but not including this docID
+ private void fill(int docID) throws IOException {
+ assert size >= 0;
- for(int i=lastDocID+1;i<docID;i++) {
++ for (int i = lastDocID + 1; i < docID; i++) {
+ datOut.writeBytes(oneRecord, size);
+ }
+ lastDocID = docID;
+ }
+
+ @Override
+ synchronized public void finish(int docCount) throws IOException {
- if(datOut == null) // no data added
- return;
- fill(docCount);
- super.finish(docCount);
++ try {
++ if (size == -1) {// no data added
++ datOut.writeInt(0);
++ } else {
++ fill(docCount);
++ }
++ } finally {
++ super.finish(docCount);
++ }
+ }
+
+ public long ramBytesUsed() {
+ return 0;
+ }
-
++
+ }
+
+ public static class Reader extends BytesReaderBase {
+ private final int size;
+ private final int maxDoc;
+
- 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, false);
+ size = datIn.readInt();
+ this.maxDoc = maxDoc;
+ }
+
+ @Override
+ public Source load() throws IOException {
+ return new Source(cloneData(), cloneIndex(), size, maxDoc);
+ }
+
+ @Override
+ public void close() throws IOException {
+ datIn.close();
+ }
+
+ private static class Source extends BytesBaseSource {
+ 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);
++ 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.missingValue.bytesValue = new BytesRef(size);
+ this.maxDoc = maxDoc;
+ }
-
++
+ @Override
- public BytesRef getBytes(int docID, BytesRef bytesRef) {
++ public BytesRef getBytes(int docID, BytesRef bytesRef) {
+ return data.fillSlice(bytesRef, docID * size, size);
+ }
+
+ @Override
+ public int getValueCount() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_FIXED_STRAIGHT;
+ }
+
+ @Override
+ protected int maxDoc() {
+ return maxDoc;
+ }
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource source) throws IOException {
+ return new FixedStraightBytesEnum(source, cloneData(), size, maxDoc);
+ }
-
++
+ private static final class FixedStraightBytesEnum extends DocValuesEnum {
+ private final IndexInput datIn;
+ private final int size;
+ private final int maxDoc;
+ private int pos = -1;
+ private final long fp;
+
- public FixedStraightBytesEnum(AttributeSource source, IndexInput datIn, int size, int maxDoc) throws IOException{
++ public FixedStraightBytesEnum(AttributeSource source, IndexInput datIn,
++ int size, int maxDoc) throws IOException {
+ super(source, Type.BYTES_FIXED_STRAIGHT);
+ this.datIn = datIn;
+ this.size = size;
+ this.maxDoc = maxDoc;
+ bytesRef.grow(size);
+ bytesRef.length = size;
+ bytesRef.offset = 0;
+ fp = datIn.getFilePointer();
+ }
-
++
+ protected void copyReferences(DocValuesEnum valuesEnum) {
+ bytesRef = valuesEnum.bytesRef;
- if(bytesRef.bytes.length < size) {
++ if (bytesRef.bytes.length < size) {
+ bytesRef.grow(size);
+ }
+ bytesRef.length = size;
+ bytesRef.offset = 0;
+ }
-
++
+ public void close() throws IOException {
+ datIn.close();
+ }
-
++
+ @Override
+ public int advance(int target) throws IOException {
- if(target >= maxDoc){
++ if (target >= maxDoc || size == 0) {
+ return pos = NO_MORE_DOCS;
+ }
- if((target-1) != pos) // pos inc == 1
++ if ((target - 1) != pos) // pos inc == 1
+ datIn.seek(fp + target * size);
+ datIn.readBytes(bytesRef.bytes, 0, size);
+ return pos = target;
+ }
-
++
+ @Override
+ public int docID() {
+ return pos;
+ }
-
++
+ @Override
+ public int nextDoc() throws IOException {
- if(pos >= maxDoc){
++ if (pos >= maxDoc) {
+ return pos = NO_MORE_DOCS;
+ }
- return advance(pos+1);
++ return advance(pos + 1);
+ }
+ }
-
++
+ @Override
+ public Type type() {
+ return Type.BYTES_FIXED_STRAIGHT;
+ }
+ }
+}
diff --cc lucene/src/java/org/apache/lucene/index/values/Floats.java
index 0bf082ab98b,00000000000..c728eacf3a8
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/Floats.java
+++ b/lucene/src/java/org/apache/lucene/index/values/Floats.java
@@@ -1,473 -1,0 +1,476 @@@
+package org.apache.lucene.index.values;
++
+/**
+ * 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.nio.ByteBuffer;
+import java.nio.DoubleBuffer;
+import java.nio.FloatBuffer;
+import java.util.Collection;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.index.IndexFileNames;
+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.CodecUtil;
+import org.apache.lucene.util.FloatsRef;
+
+/**
+ * Exposes writer/reader for floating point values. You can specify 4 (java
+ * float) or 8 (java double) byte precision.
++ *
+ * @lucene.experimental
+ */
+// TODO - add bulk copy where possible
+public 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_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, AtomicLong bytesUsed)
- throws IOException {
++ public static Writer getWriter(Directory dir, String id, int precisionBytes,
++ AtomicLong bytesUsed) throws IOException {
+ if (precisionBytes != 4 && precisionBytes != 8) {
+ throw new IllegalArgumentException("precisionBytes must be 4 or 8; got "
+ + precisionBytes);
+ }
+ if (precisionBytes == 4) {
+ return new Float4Writer(dir, id, bytesUsed);
+ } else {
+ return new Float8Writer(dir, id, bytesUsed);
+ }
+ }
+
+ public static DocValues getValues(Directory dir, String id, int maxDoc)
+ throws IOException {
+ return new FloatsReader(dir, id, maxDoc);
+ }
+
+ abstract static class FloatsWriter extends Writer {
+ private final Directory dir;
+ private final String id;
+ private FloatsRef floatsRef;
+ protected int lastDocId = -1;
+ protected IndexOutput datOut;
+ private final byte precision;
+
- protected FloatsWriter(Directory dir, String id, int precision, AtomicLong bytesUsed)
- throws IOException {
++ protected FloatsWriter(Directory dir, String id, int precision,
++ AtomicLong bytesUsed) throws IOException {
+ super(bytesUsed);
+ this.dir = dir;
+ this.id = id;
+ this.precision = (byte) precision;
++ initDatOut();
+ }
+
- protected void initDatOut() throws IOException {
++ private void initDatOut() throws IOException {
+ datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",
+ Writer.DATA_EXTENSION));
+ CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);
+ assert datOut.getFilePointer() == CodecUtil.headerLength(CODEC_NAME);
+ datOut.writeByte(precision);
+ }
+
+ public long ramBytesUsed() {
+ return 0;
+ }
+
+ @Override
+ protected void add(int docID) throws IOException {
+ add(docID, floatsRef.get());
+ }
+
+ @Override
+ public void add(int docID, PerDocFieldValues docValues) throws IOException {
- add(docID, docValues.getFloat());
++ add(docID, docValues.getFloat());
+ }
+
+ @Override
+ protected void setNextEnum(DocValuesEnum valuesEnum) {
+ floatsRef = valuesEnum.getFloat();
+ }
+
+ protected abstract int fillDefault(int num) throws IOException;
+
+ @Override
+ protected void merge(MergeState state) throws IOException {
+ if (state.bits == null && state.reader instanceof FloatsReader) {
+ // no deletes - bulk copy
+ // TODO: should be do bulks with deletes too?
+ final FloatsReader reader = (FloatsReader) state.reader;
+ assert reader.precisionBytes == (int) precision;
+ if (reader.maxDoc == 0)
+ return;
+ if (datOut == null)
+ initDatOut();
+ final int docBase = state.docBase;
+ if (docBase - lastDocId > 1) {
+ // fill with default values
+ lastDocId += fillDefault(docBase - lastDocId - 1);
+ }
+ lastDocId += reader.transferTo(datOut);
+ } else
+ super.merge(state);
+ }
+
+ @Override
+ public void files(Collection<String> files) throws IOException {
+ files.add(IndexFileNames.segmentFileName(id, "", Writer.DATA_EXTENSION));
+ }
+
+ }
+
+ // Writes 4 bytes (float) per value
+ static class Float4Writer extends FloatsWriter {
+
- protected Float4Writer(Directory dir, String id, AtomicLong bytesUsed) throws IOException {
++ protected Float4Writer(Directory dir, String id, AtomicLong bytesUsed)
++ throws IOException {
+ super(dir, id, 4, bytesUsed);
+ }
+
+ @Override
+ synchronized public void add(final int docID, final double v)
+ throws IOException {
+ assert docID > lastDocId : "docID: " + docID
+ + " must be greater than the last added doc id: " + lastDocId;
- if (datOut == null) {
- initDatOut();
- }
+ if (docID - lastDocId > 1) {
+ // fill with default values
+ lastDocId += fillDefault(docID - lastDocId - 1);
+ }
+ assert datOut != null;
+ datOut.writeInt(Float.floatToRawIntBits((float) v));
+ ++lastDocId;
+ }
+
+ @Override
+ synchronized public void finish(int docCount) throws IOException {
- if (datOut == null)
- return; // no data added - don't create file!
- if (docCount > lastDocId + 1)
- for (int i = lastDocId; i < docCount; i++) {
- datOut.writeInt(INT_DEFAULT); // default value
- }
- datOut.close();
++ try {
++ if (docCount > lastDocId + 1)
++ for (int i = lastDocId; i < docCount; i++) {
++ datOut.writeInt(INT_DEFAULT); // default value
++ }
++ } finally {
++ datOut.close();
++ }
+ }
+
+ @Override
+ protected int fillDefault(int numValues) throws IOException {
+ for (int i = 0; i < numValues; i++) {
+ datOut.writeInt(INT_DEFAULT);
+ }
+ return numValues;
+ }
+ }
+
+ // Writes 8 bytes (double) per value
+ static class Float8Writer extends FloatsWriter {
+
- protected Float8Writer(Directory dir, String id, AtomicLong bytesUsed) throws IOException {
++ protected Float8Writer(Directory dir, String id, AtomicLong bytesUsed)
++ throws IOException {
+ super(dir, id, 8, bytesUsed);
+ }
+
+ @Override
+ synchronized public void add(int docID, double v) throws IOException {
+ assert docID > lastDocId : "docID: " + docID
+ + " must be greater than the last added doc id: " + lastDocId;
- if (datOut == null) {
- initDatOut();
- }
+ if (docID - lastDocId > 1) {
+ // fill with default values
+ lastDocId += fillDefault(docID - lastDocId - 1);
+ }
+ assert datOut != null;
+ datOut.writeLong(Double.doubleToRawLongBits(v));
+ ++lastDocId;
+ }
+
+ @Override
+ synchronized public void finish(int docCount) throws IOException {
- if (datOut == null)
- return; // no data added - don't create file!
- if (docCount > lastDocId + 1)
- for (int i = lastDocId; i < docCount; i++) {
- datOut.writeLong(LONG_DEFAULT); // default value
- }
- datOut.close();
++ try {
++ if (docCount > lastDocId + 1)
++ for (int i = lastDocId; i < docCount; i++) {
++ datOut.writeLong(LONG_DEFAULT); // default value
++ }
++ } finally {
++ datOut.close();
++ }
+ }
+
+ @Override
+ protected int fillDefault(int numValues) throws IOException {
+ for (int i = 0; i < numValues; i++) {
+ datOut.writeLong(LONG_DEFAULT);
+ }
+ return numValues;
+ }
+ }
+
+ /**
+ * Opens all necessary files, but does not read any data in until you call
+ * {@link #load}.
+ */
+ static class FloatsReader extends DocValues {
+
+ private final IndexInput datIn;
+ private final int precisionBytes;
+ // TODO(simonw) is ByteBuffer the way to go here?
+ private final int maxDoc;
+
+ protected FloatsReader(Directory dir, String id, int maxDoc)
+ throws IOException {
+ datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",
+ Writer.DATA_EXTENSION));
+ CodecUtil.checkHeader(datIn, CODEC_NAME, VERSION_START, VERSION_START);
+ precisionBytes = datIn.readByte();
+ assert precisionBytes == 4 || precisionBytes == 8;
+ this.maxDoc = maxDoc;
+ }
+
+ int transferTo(IndexOutput out) throws IOException {
+ IndexInput indexInput = (IndexInput) datIn.clone();
+ try {
+ indexInput.seek(CodecUtil.headerLength(CODEC_NAME));
+ // skip precision:
+ indexInput.readByte();
+ out.copyBytes(indexInput, precisionBytes * maxDoc);
+ } finally {
+ indexInput.close();
+ }
+ return maxDoc;
+ }
+
+ /**
+ * Loads the actual values. You may call this more than once, eg if you
+ * already previously loaded but then discarded the Source.
+ */
+ @Override
+ public Source load() throws IOException {
+ ByteBuffer buffer = ByteBuffer.allocate(precisionBytes * maxDoc);
+ IndexInput indexInput = (IndexInput) datIn.clone();
+ indexInput.seek(CodecUtil.headerLength(CODEC_NAME));
+ // skip precision:
+ indexInput.readByte();
+ assert buffer.hasArray() : "Buffer must support Array";
+ final byte[] arr = buffer.array();
+ indexInput.readBytes(arr, 0, arr.length);
+ return precisionBytes == 4 ? new Source4(buffer) : new Source8(buffer);
+ }
+
+ private class Source4 extends Source {
+ private final FloatBuffer values;
+
+ Source4(ByteBuffer buffer) {
+ values = buffer.asFloatBuffer();
+ missingValue.doubleValue = Float.NEGATIVE_INFINITY;
+ }
+
+ @Override
+ public double getFloat(int docID) {
+ return values.get(docID);
+ }
+
+ @Override
- public DocValuesEnum getEnum(AttributeSource attrSource) throws IOException {
++ public DocValuesEnum getEnum(AttributeSource attrSource)
++ throws IOException {
+ final MissingValue missing = getMissing();
+ return new SourceEnum(attrSource, Type.SIMPLE_FLOAT_4BYTE, this, maxDoc) {
+ @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;
+ }
+ }
+ floatsRef.floats[floatsRef.offset] = source.getFloat(target);
+ return pos = target;
+ }
+ };
+ }
+
+ @Override
+ public Type type() {
+ return Type.SIMPLE_FLOAT_4BYTE;
+ }
+ }
+
+ private class Source8 extends Source {
+ private final DoubleBuffer values;
+
+ Source8(ByteBuffer buffer) {
+ values = buffer.asDoubleBuffer();
+ missingValue.doubleValue = Double.NEGATIVE_INFINITY;
+
+ }
+
+ @Override
+ public double getFloat(int docID) {
+ return values.get(docID);
+ }
+
+ @Override
- public DocValuesEnum getEnum(AttributeSource attrSource) throws IOException {
++ public DocValuesEnum getEnum(AttributeSource attrSource)
++ throws IOException {
+ final MissingValue missing = getMissing();
+ return new SourceEnum(attrSource, type(), this, maxDoc) {
+ @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;
+ }
+ }
+ floatsRef.floats[floatsRef.offset] = source.getFloat(target);
+ return pos = target;
+ }
+ };
+ }
+
+ @Override
+ public Type type() {
+ return Type.SIMPLE_FLOAT_8BYTE;
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+ datIn.close();
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource source) throws IOException {
+ IndexInput indexInput = (IndexInput) datIn.clone();
+ indexInput.seek(CodecUtil.headerLength(CODEC_NAME));
+ // skip precision:
+ indexInput.readByte();
+ return precisionBytes == 4 ? new Floats4Enum(source, indexInput, maxDoc)
+ : new Floats8EnumImpl(source, indexInput, maxDoc);
+ }
+
+ @Override
+ public Type type() {
+ return precisionBytes == 4 ? Type.SIMPLE_FLOAT_4BYTE
+ : Type.SIMPLE_FLOAT_8BYTE;
+ }
+ }
+
+ static final class Floats4Enum extends FloatsEnumImpl {
+
+ Floats4Enum(AttributeSource source, IndexInput dataIn, int maxDoc)
+ throws IOException {
+ super(source, dataIn, 4, maxDoc, Type.SIMPLE_FLOAT_4BYTE);
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ if (target >= maxDoc)
+ return pos = NO_MORE_DOCS;
+ dataIn.seek(fp + (target * precision));
+ int intBits;
+ while ((intBits = dataIn.readInt()) == INT_DEFAULT) {
+ if (++target >= maxDoc)
+ return pos = NO_MORE_DOCS;
+ }
+ floatsRef.floats[0] = Float.intBitsToFloat(intBits);
+ floatsRef.offset = 0;
+ return pos = target;
+ }
+
+ @Override
+ public int docID() {
+ return pos;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ if (pos >= maxDoc) {
+ return pos = NO_MORE_DOCS;
+ }
+ return advance(pos + 1);
+ }
+ }
+
+ private static final class Floats8EnumImpl extends FloatsEnumImpl {
+
+ Floats8EnumImpl(AttributeSource source, IndexInput dataIn, int maxDoc)
+ throws IOException {
+ super(source, dataIn, 8, maxDoc, Type.SIMPLE_FLOAT_8BYTE);
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ if (target >= maxDoc) {
+ return pos = NO_MORE_DOCS;
+ }
+ dataIn.seek(fp + (target * precision));
+ long value;
+ while ((value = dataIn.readLong()) == LONG_DEFAULT) {
+ if (++target >= maxDoc)
+ return pos = NO_MORE_DOCS;
+ }
+ floatsRef.floats[0] = Double.longBitsToDouble(value);
+ floatsRef.offset = 0;
+ return pos = target;
+ }
+
+ @Override
+ public int docID() {
+ return pos;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ if (pos >= maxDoc) {
+ return pos = NO_MORE_DOCS;
+ }
+ return advance(pos + 1);
+ }
+ }
+
+ static abstract class FloatsEnumImpl extends DocValuesEnum {
+ protected final IndexInput dataIn;
+ protected int pos = -1;
+ protected final int precision;
+ protected final int maxDoc;
+ protected final long fp;
+
+ FloatsEnumImpl(AttributeSource source, IndexInput dataIn, int precision,
+ int maxDoc, Type type) throws IOException {
+ super(source, precision == 4 ? Type.SIMPLE_FLOAT_4BYTE
+ : Type.SIMPLE_FLOAT_8BYTE);
+ this.dataIn = dataIn;
+ this.precision = precision;
+ this.maxDoc = maxDoc;
+ fp = dataIn.getFilePointer();
+ floatsRef.offset = 0;
+ }
+
+ @Override
+ public void close() throws IOException {
+ dataIn.close();
+ }
+ }
+}
diff --cc lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.java
index 8466bb2db7f,00000000000..74ec4abe6d5
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.java
+++ b/lucene/src/java/org/apache/lucene/index/values/PackedIntsImpl.java
@@@ -1,293 -1,0 +1,304 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import java.io.IOException;
+import java.util.Collection;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.index.IndexFileNames;
+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.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;
+
- /** Stores ints packed with fixed-bit precision.
++/**
++ * Stores ints packed with fixed-bit precision.
+ *
+ * @lucene.experimental
+ * */
+class PackedIntsImpl {
+
+ private static final String CODEC_NAME = "PackedInts";
+
+ static final int VERSION_START = 0;
+ static final int VERSION_CURRENT = VERSION_START;
+
+ static class IntsWriter extends Writer {
+
+ // TODO: can we bulkcopy this on a merge?
+ private LongsRef intsRef;
+ private long[] docToValue;
+ private long minValue;
+ private long maxValue;
+ private boolean started;
- private final Directory dir;
+ private final String id;
+ private final OpenBitSet defaultValues = new OpenBitSet(1);
+ private int lastDocId = -1;
++ private IndexOutput datOut;
+
- protected IntsWriter(Directory dir, String id, AtomicLong bytesUsed) throws IOException {
++ protected IntsWriter(Directory dir, String id, AtomicLong bytesUsed)
++ throws IOException {
+ super(bytesUsed);
- this.dir = dir;
+ this.id = id;
+ docToValue = new long[1];
- bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_LONG); // TODO the bitset needs memory too
++ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_LONG); // TODO the bitset
++ // needs memory too
++ datOut = dir.createOutput(IndexFileNames.segmentFileName(id, "",
++ DATA_EXTENSION));
++ CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);
+ }
+
+ @Override
+ public synchronized void add(int docID, long v) throws IOException {
+ assert lastDocId < docID;
+ if (!started) {
+ started = true;
+ minValue = maxValue = v;
+ } else {
+ if (v < minValue) {
+ minValue = v;
+ } else if (v > maxValue) {
+ maxValue = v;
+ }
+ }
+ defaultValues.set(docID);
+ lastDocId = docID;
+
+ if (docID >= docToValue.length) {
- final long len = docToValue.length ;
++ final long len = docToValue.length;
+ docToValue = ArrayUtil.grow(docToValue, 1 + docID);
+ defaultValues.ensureCapacity(docToValue.length);
- bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_LONG * ((docToValue.length) - len));
++ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_LONG
++ * ((docToValue.length) - len));
+ }
+ docToValue[docID] = v;
+ }
+
+ @Override
+ public synchronized void finish(int docCount) throws IOException {
- if (!started)
- return;
- final IndexOutput datOut = dir.createOutput(IndexFileNames
- .segmentFileName(id, "", DATA_EXTENSION));
- CodecUtil.writeHeader(datOut, CODEC_NAME, VERSION_CURRENT);
-
- // TODO -- long can't work right since it's signed
- datOut.writeLong(minValue);
- // write a default value to recognize docs without a value for that field
- final long defaultValue = ++maxValue - minValue;
- datOut.writeLong(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
- }
- 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
++ try {
++ if (!started) {
++ minValue = maxValue = 0;
+ }
++ // TODO -- long can't work right since it's signed
++ datOut.writeLong(minValue);
++ // write a default value to recognize docs without a value for that
++ // field
++ final long defaultValue = ++maxValue - minValue;
++ datOut.writeLong(defaultValue);
++ PackedInts.Writer w = PackedInts.getWriter(datOut, docCount,
++ PackedInts.bitsRequired(maxValue - minValue));
++ final int firstDoc = defaultValues.nextSetBit(0);
++ lastDocId++;
++ if(firstDoc != -1) {
++ for (int i = 0; i < firstDoc; i++) {
++ w.add(defaultValue); // fill with defaults until first bit set
++ }
++
++ 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 = lastDocId; i < docCount; i++) {
++ w.add(defaultValue);
++ }
++ w.finish();
++ } finally {
++ datOut.close();
++ bytesUsed
++ .addAndGet(-(RamUsageEstimator.NUM_BYTES_LONG * docToValue.length));
++ docToValue = null;
+ }
- for (int i = lastDocId; i < docCount; i++) {
- w.add(defaultValue);
- }
- w.finish();
- datOut.close();
- bytesUsed.addAndGet(-(RamUsageEstimator.NUM_BYTES_LONG * docToValue.length ));
- docToValue = null;
-
++
+ }
+
+ @Override
+ protected void add(int docID) throws IOException {
+ add(docID, intsRef.get());
+ }
+
+ @Override
+ protected void setNextEnum(DocValuesEnum valuesEnum) {
+ intsRef = valuesEnum.getInt();
+ }
+
+ @Override
+ public void add(int docID, PerDocFieldValues docValues) throws IOException {
- add(docID, docValues.getInt());
++ add(docID, docValues.getInt());
+ }
+
+ @Override
+ public void files(Collection<String> files) throws IOException {
+ files.add(IndexFileNames.segmentFileName(id, "", DATA_EXTENSION));
+ }
+ }
+
+ /**
+ * Opens all necessary files, but does not read any data in until you call
+ * {@link #load}.
+ */
+ static class IntsReader extends DocValues {
+ private final IndexInput datIn;
+
+ protected IntsReader(Directory dir, String id) throws IOException {
+ datIn = dir.openInput(IndexFileNames.segmentFileName(id, "",
+ Writer.DATA_EXTENSION));
+ CodecUtil.checkHeader(datIn, CODEC_NAME, VERSION_START, VERSION_START);
+ }
+
+ /**
+ * Loads the actual values. You may call this more than once, eg if you
+ * already previously loaded but then discarded the Source.
+ */
+ @Override
+ public Source load() throws IOException {
+ return new IntsSource((IndexInput) datIn.clone());
+ }
+
+ private static class IntsSource extends Source {
+ private final long minValue;
+ private final long defaultValue;
+ private final PackedInts.Reader values;
+
+ public IntsSource(IndexInput dataIn) throws IOException {
+ dataIn.seek(CodecUtil.headerLength(CODEC_NAME));
+ minValue = dataIn.readLong();
+ defaultValue = dataIn.readLong();
+ values = PackedInts.getReader(dataIn);
+ missingValue.longValue = minValue + defaultValue;
+ }
+
+ @Override
+ public long getInt(int docID) {
+ // TODO -- can we somehow avoid 2X method calls
+ // on each get? must push minValue down, and make
+ // PackedInts implement Ints.Source
+ return minValue + values.get(docID);
+ }
+
+ @Override
- public DocValuesEnum getEnum(AttributeSource attrSource) throws IOException {
++ public DocValuesEnum getEnum(AttributeSource attrSource)
++ throws IOException {
+ final MissingValue missing = getMissing();
+ return new SourceEnum(attrSource, type(), this, values.size()) {
+ @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;
+ }
+ }
+ intsRef.ints[intsRef.offset] = source.getInt(target);
+ return pos = target;
+ }
+ };
+ }
+
+ @Override
+ public Type type() {
+ return Type.PACKED_INTS;
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+ datIn.close();
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource source) throws IOException {
+ return new IntsEnumImpl(source, (IndexInput) datIn.clone());
+ }
+
+ @Override
+ public Type type() {
+ return Type.PACKED_INTS;
+ }
+
+ }
+
+ private static final class IntsEnumImpl extends DocValuesEnum {
+ private final PackedInts.ReaderIterator ints;
+ private long minValue;
+ private final IndexInput dataIn;
+ private final long defaultValue;
+ private final int maxDoc;
+ private int pos = -1;
+
+ private IntsEnumImpl(AttributeSource source, IndexInput dataIn)
+ throws IOException {
+ super(source, Type.PACKED_INTS);
+ intsRef.offset = 0;
+ this.dataIn = dataIn;
+ dataIn.seek(CodecUtil.headerLength(CODEC_NAME));
+ minValue = dataIn.readLong();
+ defaultValue = dataIn.readLong();
+ this.ints = PackedInts.getReaderIterator(dataIn);
+ maxDoc = ints.size();
+ }
+
+ @Override
+ public void close() throws IOException {
+ ints.close();
+ dataIn.close();
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ if (target >= maxDoc) {
+ return pos = NO_MORE_DOCS;
+ }
+ long val = ints.advance(target);
+ while (val == defaultValue) {
+ if (++target >= maxDoc) {
+ return pos = NO_MORE_DOCS;
+ }
+ val = ints.advance(target);
+ }
+ intsRef.ints[0] = minValue + val;
+ intsRef.offset = 0; // can we skip this?
+ return pos = target;
+ }
+
+ @Override
+ public int docID() {
+ return pos;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ if (pos >= maxDoc) {
+ return pos = NO_MORE_DOCS;
+ }
+ return advance(pos + 1);
+ }
+ }
+}
diff --cc lucene/src/java/org/apache/lucene/index/values/Type.java
index 717741abab8,00000000000..b02fd0a9194
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/Type.java
+++ b/lucene/src/java/org/apache/lucene/index/values/Type.java
@@@ -1,47 -1,0 +1,80 @@@
+package org.apache.lucene.index.values;
++
++import org.apache.lucene.index.values.DocValues.SortedSource;
++
+/**
+ * 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.
+ */
+
- /** Controls whether per-field values are stored into
- * index. This storage is non-sparse, so it's best to
- * use this when all docs have the field, and loads all
- * values into RAM, exposing a random access API, when
- * loaded.
- *
- * @lucene.experimental
++/**
++ * {@link Type} specifies the type of the {@link DocValues} for a certain field.
++ * A {@link Type} can specify the actual data type for a field, used compression
++ * schemes and high-level data-structures.
++ *
++ * @lucene.experimental
+ */
+public enum Type {
+
- /** Integral value is stored as packed ints. The bit
- * precision is fixed across the segment, and
- * determined by the min/max values in the field. */
++ /**
++ * Integral value is stored as packed ints. The bit precision is fixed across
++ * the segment, and determined by the min/max values in the field.
++ */
+ PACKED_INTS,
++ /**
++ * 32 bit floating point value stored without modification or compression.
++ */
+ SIMPLE_FLOAT_4BYTE,
++ /**
++ * 64 bit floating point value stored without modification or compression.
++ */
+ SIMPLE_FLOAT_8BYTE,
+
+ // TODO(simonw): -- shouldn't lucene decide/detect straight vs
+ // deref, as well fixed vs var?
++ /**
++ * Fixed length straight stored byte variant
++ */
+ BYTES_FIXED_STRAIGHT,
++
++ /**
++ * Fixed length dereferenced (indexed) byte variant
++ */
+ BYTES_FIXED_DEREF,
++
++ /**
++ * Fixed length pre-sorted byte variant
++ *
++ * @see SortedSource
++ */
+ BYTES_FIXED_SORTED,
+
++ /**
++ * Variable length straight stored byte variant
++ */
+ BYTES_VAR_STRAIGHT,
++
++ /**
++ * Variable length dereferenced (indexed) byte variant
++ */
+ BYTES_VAR_DEREF,
- BYTES_VAR_SORTED
+
- // TODO(simonw): -- need STRING variants as well
++ /**
++ * Variable length pre-sorted byte variant
++ *
++ * @see SortedSource
++ */
++ BYTES_VAR_SORTED
+}
diff --cc lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java
index c28e7e57759,00000000000..132a5e4336f
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java
+++ b/lucene/src/java/org/apache/lucene/index/values/VarDerefBytesImpl.java
@@@ -1,280 -1,0 +1,277 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * 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.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.index.values.Bytes.BytesBaseSource;
+import org.apache.lucene.index.values.Bytes.BytesReaderBase;
+import org.apache.lucene.index.values.Bytes.BytesWriterBase;
+import org.apache.lucene.index.values.FixedDerefBytesImpl.Reader.DerefBytesEnum;
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.AttributeSource;
+import org.apache.lucene.util.ByteBlockPool;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefHash;
+import org.apache.lucene.util.CodecUtil;
+import org.apache.lucene.util.PagedBytes;
+import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.ByteBlockPool.Allocator;
+import org.apache.lucene.util.ByteBlockPool.DirectAllocator;
+import org.apache.lucene.util.BytesRefHash.TrackingDirectBytesStartArray;
+import org.apache.lucene.util.packed.PackedInts;
+
+// Stores variable-length byte[] by deref, ie when two docs
+// have the same value, they store only 1 byte[] and both
+// docs reference that single source
+
+/**
+ * @lucene.experimental
+ */
+class VarDerefBytesImpl {
+
+ static final String CODEC_NAME = "VarDerefBytes";
+ static final int VERSION_START = 0;
+ static final int VERSION_CURRENT = VERSION_START;
+
+ private static final class AddressByteStartArray extends
+ TrackingDirectBytesStartArray {
+ int[] address;
+
+ AddressByteStartArray(int size, AtomicLong bytesUsed) {
+ super(size, bytesUsed);
+ }
+
+ @Override
+ public AtomicLong bytesUsed() {
+ return bytesUsed;
+ }
+
+ @Override
+ public int[] clear() {
+ if (address != null) {
+ bytesUsed.addAndGet(-address.length * RamUsageEstimator.NUM_BYTES_INT);
+ address = null;
+ }
+ return super.clear();
+ }
+
+ @Override
+ public int[] grow() {
+ assert address != null;
+ final int oldSize = address.length;
+ final int[] retVal = super.grow();
+ address = ArrayUtil.grow(address, retVal.length);
+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT
+ * (address.length - oldSize));
+ return retVal;
+ }
+
+ @Override
+ public int[] init() {
+ if (address == null) {
+ address = new int[ArrayUtil.oversize(initSize,
+ RamUsageEstimator.NUM_BYTES_INT)];
+ bytesUsed.addAndGet((address.length) * RamUsageEstimator.NUM_BYTES_INT);
+ }
+ return super.init();
+ }
+
+ }
+
+ static class Writer extends BytesWriterBase {
+ private int[] docToAddress;
+ private int address = 1;
+
+ private final AddressByteStartArray array = new AddressByteStartArray(1,
+ bytesUsed);
+ private final BytesRefHash hash = new BytesRefHash(pool, 16, array);
+
+ public Writer(Directory dir, String id, AtomicLong bytesUsed)
+ throws IOException {
+ this(dir, id, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE),
+ bytesUsed);
+ }
+
+ public Writer(Directory dir, String id, Allocator allocator,
+ AtomicLong bytesUsed) throws IOException {
- super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false,
++ super(dir, id, CODEC_NAME, VERSION_CURRENT, true, true,
+ new ByteBlockPool(allocator), bytesUsed);
+ docToAddress = new int[1];
+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);
+ }
+
+ @Override
+ synchronized public void add(int docID, BytesRef bytes) throws IOException {
+ if (bytes.length == 0)
+ return; // default
- 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));
+ }
+ final int docAddress;
+ if (e >= 0) {
+ docAddress = array.address[e] = address;
+ address += writePrefixLength(datOut, bytes);
+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);
+ address += bytes.length;
+ } else {
+ docAddress = array.address[(-e) - 1];
+ }
+ docToAddress[docID] = docAddress;
+ }
+
+ private static int writePrefixLength(DataOutput datOut, BytesRef bytes)
+ throws IOException {
+ if (bytes.length < 128) {
+ datOut.writeByte((byte) bytes.length);
+ return 1;
+ } else {
+ datOut.writeByte((byte) (0x80 | (bytes.length >> 8)));
+ datOut.writeByte((byte) (bytes.length & 0xff));
+ return 2;
+ }
+ }
+
+ // Important that we get docCount, in case there were
+ // some last docs that we didn't see
+ @Override
+ synchronized public void finish(int docCount) throws IOException {
- if (datOut == null)
- return;
- initIndexOut();
- 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 int limit;
- if (docCount > docToAddress.length) {
- limit = docToAddress.length;
- } else {
- limit = docCount;
- }
- for (int i = 0; i < limit; i++) {
- w.add(docToAddress[i]);
- }
- for (int i = limit; i < docCount; i++) {
- w.add(0);
++ try {
++ 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 int limit;
++ if (docCount > docToAddress.length) {
++ limit = docToAddress.length;
++ } else {
++ limit = docCount;
++ }
++ for (int i = 0; i < limit; i++) {
++ w.add(docToAddress[i]);
++ }
++ for (int i = limit; i < docCount; i++) {
++ w.add(0);
++ }
++ w.finish();
++ } finally {
++ hash.close();
++ super.finish(docCount);
++ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT
++ * (-docToAddress.length));
++ docToAddress = null;
+ }
- w.finish();
- hash.close();
- super.finish(docCount);
- bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT
- * (-docToAddress.length));
- docToAddress = null;
+ }
+ }
+
+ public static class Reader extends BytesReaderBase {
+
+ Reader(Directory dir, String id, int maxDoc) throws IOException {
+ super(dir, id, CODEC_NAME, VERSION_START, true);
+ }
+
+ @Override
+ public Source load() throws IOException {
+ final IndexInput data = cloneData();
+ final IndexInput index = cloneIndex();
+ 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);
+ }
+
+ private static class Source extends BytesBaseSource {
+ private final PackedInts.Reader index;
+
+ 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, BytesRef bytesRef) {
+ long address = index.get(docID);
+ return address == 0 ? null : data.fillSliceWithPrefix(bytesRef,
+ --address);
+ }
+
+ @Override
+ public int getValueCount() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_VAR_DEREF;
+ }
+
+ @Override
+ protected int maxDoc() {
+ return index.size();
+ }
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource source) throws IOException {
+ return new VarDerefBytesEnum(source, cloneData(), cloneIndex());
+ }
+
+ static class VarDerefBytesEnum extends DerefBytesEnum {
+
+ public VarDerefBytesEnum(AttributeSource source, IndexInput datIn,
+ IndexInput idxIn) throws IOException {
+ super(source, datIn, idxIn, -1, Type.BYTES_VAR_DEREF);
+ }
+
+ @Override
+ protected void fill(long address, BytesRef ref) throws IOException {
+ datIn.seek(fp + --address);
+ final byte sizeByte = datIn.readByte();
+ final int size;
+ if ((sizeByte & 128) == 0) {
+ // length is 1 byte
+ size = sizeByte;
+ } else {
+ size = ((sizeByte & 0x7f) << 8) | ((datIn.readByte() & 0xff));
+ }
+ if (ref.bytes.length < size)
+ ref.grow(size);
+ ref.length = size;
+ ref.offset = 0;
+ datIn.readBytes(ref.bytes, 0, size);
+ }
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_VAR_DEREF;
+ }
+ }
+}
diff --cc lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java
index ab023a1f817,00000000000..2711b435923
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java
+++ b/lucene/src/java/org/apache/lucene/index/values/VarSortedBytesImpl.java
@@@ -1,316 -1,0 +1,315 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.index.values.Bytes.BytesBaseSortedSource;
+import org.apache.lucene.index.values.Bytes.BytesReaderBase;
+import org.apache.lucene.index.values.Bytes.BytesWriterBase;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.AttributeSource;
+import org.apache.lucene.util.ByteBlockPool;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefHash;
+import org.apache.lucene.util.PagedBytes;
+import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.ByteBlockPool.Allocator;
+import org.apache.lucene.util.ByteBlockPool.DirectAllocator;
+import org.apache.lucene.util.BytesRefHash.TrackingDirectBytesStartArray;
+import org.apache.lucene.util.packed.PackedInts;
+
+// Stores variable-length byte[] by deref, ie when two docs
+// have the same value, they store only 1 byte[] and both
+// docs reference that single source
+
+/**
+ * @lucene.experimental
+ */
+class VarSortedBytesImpl {
+
+ static final String CODEC_NAME = "VarDerefBytes";
+ static final int VERSION_START = 0;
+ static final int VERSION_CURRENT = VERSION_START;
+
+ static class Writer extends BytesWriterBase {
+ private int[] docToEntry;
+ private final Comparator<BytesRef> comp;
+
- private final BytesRefHash hash = new BytesRefHash(pool, BytesRefHash.DEFAULT_CAPACITY,
- new TrackingDirectBytesStartArray(BytesRefHash.DEFAULT_CAPACITY, bytesUsed));
++ private final BytesRefHash hash = new BytesRefHash(pool,
++ BytesRefHash.DEFAULT_CAPACITY, new TrackingDirectBytesStartArray(
++ BytesRefHash.DEFAULT_CAPACITY, bytesUsed));
+
- public Writer(Directory dir, String id, Comparator<BytesRef> comp, AtomicLong bytesUsed)
- throws IOException {
- this(dir, id, comp, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE), bytesUsed);
++ public Writer(Directory dir, String id, Comparator<BytesRef> comp,
++ AtomicLong bytesUsed) throws IOException {
++ this(dir, id, comp, new DirectAllocator(ByteBlockPool.BYTE_BLOCK_SIZE),
++ bytesUsed);
+ }
+
+ public Writer(Directory dir, String id, Comparator<BytesRef> comp,
+ Allocator allocator, AtomicLong bytesUsed) throws IOException {
- super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false,
++ super(dir, id, CODEC_NAME, VERSION_CURRENT, true, true,
+ new ByteBlockPool(allocator), bytesUsed);
+ this.comp = comp;
+ docToEntry = new int[1];
+ docToEntry[0] = -1;
+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);
+
+ }
+
+ @Override
+ synchronized public void add(int docID, BytesRef bytes) throws IOException {
+ if (bytes.length == 0)
+ return;// default
+ if (docID >= docToEntry.length) {
+ int[] newArray = new int[ArrayUtil.oversize(1 + docID,
+ RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
+ System.arraycopy(docToEntry, 0, newArray, 0, docToEntry.length);
+ Arrays.fill(newArray, docToEntry.length, newArray.length, -1);
+ bytesUsed.addAndGet((newArray.length - docToEntry.length)
+ * RamUsageEstimator.NUM_BYTES_INT);
+ docToEntry = newArray;
+ }
+ final int e = hash.add(bytes);
+ docToEntry[docID] = e < 0 ? (-e) - 1 : e;
+ }
+
+ // Important that we get docCount, in case there were
+ // some last docs that we didn't see
+ @Override
+ synchronized public void finish(int docCount) throws IOException {
+ final int count = hash.size();
- if (count == 0)
- return;
- initIndexOut();
- initDataOut();
- int[] sortedEntries = hash.sort(comp);
-
- // first dump bytes data, recording index & offset as
- // we go
- long offset = 0;
- long lastOffset = 0;
- final int[] index = new int[count];
- final long[] offsets = new long[count];
- for (int i = 0; i < count; i++) {
- final int e = sortedEntries[i];
- offsets[i] = offset;
- index[e] = 1 + i;
-
- final BytesRef bytes = hash.get(e, new BytesRef());
- // TODO: we could prefix code...
- datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);
- lastOffset = offset;
- offset += bytes.length;
- }
++ try {
++ final int[] sortedEntries = hash.sort(comp);
++
++ // first dump bytes data, recording index & offset as
++ // we go
++ long offset = 0;
++ long lastOffset = 0;
++ final int[] index = new int[count];
++ final long[] offsets = new long[count];
++ for (int i = 0; i < count; i++) {
++ final int e = sortedEntries[i];
++ offsets[i] = offset;
++ index[e] = 1 + i;
++
++ final BytesRef bytes = hash.get(e, new BytesRef());
++ // TODO: we could prefix code...
++ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);
++ lastOffset = offset;
++ offset += bytes.length;
++ }
+
- // total bytes of data
- idxOut.writeLong(offset);
-
- // write index -- first doc -> 1+ord
- // TODO(simonw): allow not -1:
- final PackedInts.Writer indexWriter = PackedInts.getWriter(idxOut,
- docCount, PackedInts.bitsRequired(count));
- final int limit = docCount > docToEntry.length ? docToEntry.length
- : docCount;
- for (int i = 0; i < limit; i++) {
- final int e = docToEntry[i];
- indexWriter.add(e == -1 ? 0 : index[e]);
- }
- for (int i = limit; i < docCount; i++) {
- indexWriter.add(0);
- }
- indexWriter.finish();
-
- // next ord (0-based) -> offset
- // TODO(simonw): -- allow not -1:
- PackedInts.Writer offsetWriter = PackedInts.getWriter(idxOut, count,
- PackedInts.bitsRequired(lastOffset));
- for (int i = 0; i < count; i++) {
- offsetWriter.add(offsets[i]);
++ // total bytes of data
++ idxOut.writeLong(offset);
++
++ // write index -- first doc -> 1+ord
++ // TODO(simonw): allow not -1:
++ final PackedInts.Writer indexWriter = PackedInts.getWriter(idxOut,
++ docCount, PackedInts.bitsRequired(count));
++ final int limit = docCount > docToEntry.length ? docToEntry.length
++ : docCount;
++ for (int i = 0; i < limit; i++) {
++ final int e = docToEntry[i];
++ indexWriter.add(e == -1 ? 0 : index[e]);
++ }
++ for (int i = limit; i < docCount; i++) {
++ indexWriter.add(0);
++ }
++ indexWriter.finish();
++
++ // next ord (0-based) -> offset
++ // TODO(simonw): -- allow not -1:
++ PackedInts.Writer offsetWriter = PackedInts.getWriter(idxOut, count,
++ PackedInts.bitsRequired(lastOffset));
++ for (int i = 0; i < count; i++) {
++ offsetWriter.add(offsets[i]);
++ }
++ offsetWriter.finish();
++ } finally {
++ super.finish(docCount);
++ bytesUsed.addAndGet((-docToEntry.length)
++ * RamUsageEstimator.NUM_BYTES_INT);
++ hash.close();
+ }
- offsetWriter.finish();
-
- super.finish(docCount);
- bytesUsed.addAndGet((-docToEntry.length)
- * RamUsageEstimator.NUM_BYTES_INT);
- hash.close();
-
+ }
+ }
+
+ public static class Reader extends BytesReaderBase {
+
+ Reader(Directory dir, String id, int maxDoc) throws IOException {
+ super(dir, id, CODEC_NAME, VERSION_START, true);
+ }
+
+ @Override
+ public org.apache.lucene.index.values.DocValues.Source load()
+ throws IOException {
+ return loadSorted(null);
+ }
+
+ @Override
+ public SortedSource loadSorted(Comparator<BytesRef> comp)
+ throws IOException {
+ IndexInput indexIn = cloneIndex();
- return new Source(cloneData(), indexIn , comp, indexIn.readLong());
++ return new Source(cloneData(), indexIn, comp, indexIn.readLong());
+ }
+
+ private static class Source extends BytesBaseSortedSource {
+ private final PackedInts.Reader docToOrdIndex;
+ private final PackedInts.Reader ordToOffsetIndex; // 0-based
+ private final long totBytes;
+ private final int valueCount;
+
+ public Source(IndexInput datIn, IndexInput idxIn,
- Comparator<BytesRef> comp, long dataLength) throws IOException {
++ Comparator<BytesRef> comp, long dataLength) throws IOException {
+ super(datIn, idxIn, comp, new PagedBytes(PAGED_BYTES_BITS), dataLength);
+ totBytes = dataLength;
+ docToOrdIndex = PackedInts.getReader(idxIn);
+ ordToOffsetIndex = PackedInts.getReader(idxIn);
+ valueCount = ordToOffsetIndex.size();
+ }
+
+ @Override
+ public int ord(int docID) {
+ return (int) docToOrdIndex.get(docID);
+ }
+
+ @Override
+ public LookupResult getByValue(BytesRef bytes, BytesRef tmpRef) {
+ return binarySearch(bytes, tmpRef, 0, valueCount - 1);
+ }
+
+ @Override
+ public int getValueCount() {
+ return valueCount;
+ }
+
+ // ord is 0-based
+ @Override
+ protected BytesRef deref(int ord, BytesRef bytesRef) {
+ final long nextOffset;
+ if (ord == valueCount - 1) {
+ nextOffset = totBytes;
+ } else {
+ nextOffset = ordToOffsetIndex.get(1 + ord);
+ }
+ final long offset = ordToOffsetIndex.get(ord);
- data.fillSlice(bytesRef, offset , (int)(nextOffset - offset));
++ data.fillSlice(bytesRef, offset, (int) (nextOffset - offset));
+ return bytesRef;
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_VAR_SORTED;
+ }
+
+ @Override
+ protected int maxDoc() {
+ return docToOrdIndex.size();
+ }
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource source) throws IOException {
+ return new VarSortedBytesEnum(source, cloneData(), cloneIndex());
+ }
+
+ private static class VarSortedBytesEnum extends DocValuesEnum {
+ private PackedInts.Reader docToOrdIndex;
+ private PackedInts.Reader ordToOffsetIndex;
+ private IndexInput idxIn;
+ private IndexInput datIn;
+ private int valueCount;
+ private long totBytes;
+ private int docCount;
+ private int pos = -1;
+ private final long fp;
+
+ protected VarSortedBytesEnum(AttributeSource source, IndexInput datIn,
+ IndexInput idxIn) throws IOException {
+ super(source, Type.BYTES_VAR_SORTED);
+ totBytes = idxIn.readLong();
+ // keep that in memory to prevent lots of disk seeks
+ docToOrdIndex = PackedInts.getReader(idxIn);
+ ordToOffsetIndex = PackedInts.getReader(idxIn);
+ valueCount = ordToOffsetIndex.size();
+ docCount = docToOrdIndex.size();
+ fp = datIn.getFilePointer();
+ this.idxIn = idxIn;
+ this.datIn = datIn;
+ }
+
+ @Override
+ public void close() throws IOException {
+ idxIn.close();
+ datIn.close();
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ if (target >= docCount) {
+ return pos = NO_MORE_DOCS;
+ }
+ int ord;
- while((ord =(int) docToOrdIndex.get(target)) == 0) {
- if(++target >= docCount) {
++ 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;
+ } else {
+ nextOffset = ordToOffsetIndex.get(1 + ord);
+ }
+ final int length = (int) (nextOffset - offset);
+ datIn.seek(fp + offset);
+ if (bytesRef.bytes.length < length)
+ bytesRef.grow(length);
+ datIn.readBytes(bytesRef.bytes, 0, length);
+ bytesRef.length = length;
+ bytesRef.offset = 0;
+ return pos = target;
+ }
+
+ @Override
+ public int docID() {
+ return pos;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ if (pos >= docCount) {
+ return pos = NO_MORE_DOCS;
+ }
+ return advance(pos + 1);
+ }
+ }
-
++
+ @Override
+ public Type type() {
+ return Type.BYTES_VAR_SORTED;
+ }
+ }
+}
diff --cc lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java
index 18f0272a268,00000000000..239b1c141ef
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java
+++ b/lucene/src/java/org/apache/lucene/index/values/VarStraightBytesImpl.java
@@@ -1,227 -1,0 +1,234 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * 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.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.index.values.Bytes.BytesBaseSource;
+import org.apache.lucene.index.values.Bytes.BytesReaderBase;
+import org.apache.lucene.index.values.Bytes.BytesWriterBase;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.AttributeSource;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.PagedBytes;
+import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.packed.PackedInts;
+
+// Variable length byte[] per document, no sharing
+
+/**
+ * @lucene.experimental
+ */
+class VarStraightBytesImpl {
+
+ static final String CODEC_NAME = "VarStraightBytes";
+ static final int VERSION_START = 0;
+ static final int VERSION_CURRENT = VERSION_START;
+
+ static class Writer extends BytesWriterBase {
+ private long address;
+ // start at -1 if the first added value is > 0
+ private int lastDocID = -1;
+ private long[] docToAddress;
+
+ public Writer(Directory dir, String id, AtomicLong bytesUsed)
+ throws IOException {
- super(dir, id, CODEC_NAME, VERSION_CURRENT, false, false, null, bytesUsed);
++ super(dir, id, CODEC_NAME, VERSION_CURRENT, true, true, null, bytesUsed);
+ docToAddress = new long[1];
+ bytesUsed.addAndGet(RamUsageEstimator.NUM_BYTES_INT);
+ }
+
+ public Writer(Directory dir, String id) throws IOException {
+ this(dir, id, new AtomicLong());
+ }
+
+ // Fills up to but not including this docID
+ private void fill(final int docID) {
+ if (docID >= docToAddress.length) {
+ int oldSize = docToAddress.length;
+ docToAddress = ArrayUtil.grow(docToAddress, 1 + docID);
+ bytesUsed.addAndGet((docToAddress.length - oldSize)
+ * RamUsageEstimator.NUM_BYTES_INT);
+ }
+ for (int i = lastDocID + 1; i < docID; i++) {
+ docToAddress[i] = address;
+ }
+ lastDocID = docID;
+ }
+
+ @Override
+ synchronized public void add(int docID, BytesRef bytes) throws IOException {
+ if (bytes.length == 0)
+ return; // default
- if (datOut == null)
- initDataOut();
+ fill(docID);
+ docToAddress[docID] = address;
+ datOut.writeBytes(bytes.bytes, bytes.offset, bytes.length);
+ address += bytes.length;
+ }
+
+ @Override
+ synchronized public void finish(int docCount) throws IOException {
- if (datOut == null) {
- return;
- }
- initIndexOut();
- fill(docCount);
- idxOut.writeVLong(address);
- final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,
- PackedInts.bitsRequired(address));
- for (int i = 0; i < docCount; i++) {
- w.add(docToAddress[i]);
++ try {
++ if (lastDocID == -1) {
++ idxOut.writeVLong(0);
++ final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,
++ PackedInts.bitsRequired(0));
++ for (int i = 0; i < docCount; i++) {
++ w.add(0);
++ }
++ w.finish();
++ } else {
++ fill(docCount);
++ idxOut.writeVLong(address);
++ final PackedInts.Writer w = PackedInts.getWriter(idxOut, docCount,
++ PackedInts.bitsRequired(address));
++ for (int i = 0; i < docCount; i++) {
++ w.add(docToAddress[i]);
++ }
++ w.finish();
++ }
++ } finally {
++ bytesUsed.addAndGet(-(docToAddress.length)
++ * RamUsageEstimator.NUM_BYTES_INT);
++ docToAddress = null;
++ super.finish(docCount);
+ }
- w.finish();
- bytesUsed.addAndGet(-(docToAddress.length)
- * RamUsageEstimator.NUM_BYTES_INT);
- docToAddress = null;
- super.finish(docCount);
+ }
+
+ public long ramBytesUsed() {
+ return bytesUsed.get();
+ }
+ }
+
+ public static class Reader extends BytesReaderBase {
+ private final int maxDoc;
+
+ Reader(Directory dir, String id, int maxDoc) throws IOException {
+ super(dir, id, CODEC_NAME, VERSION_START, true);
+ this.maxDoc = maxDoc;
+ }
+
+ @Override
+ public Source load() throws IOException {
+ return new Source(cloneData(), cloneIndex());
+ }
+
+ private class Source extends BytesBaseSource {
+ private final PackedInts.Reader addresses;
+
+ public Source(IndexInput datIn, IndexInput idxIn) throws IOException {
- super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), idxIn.readVLong());
++ super(datIn, idxIn, new PagedBytes(PAGED_BYTES_BITS), idxIn.readVLong());
+ addresses = PackedInts.getReader(idxIn);
+ missingValue.bytesValue = new BytesRef(0); // empty
+ }
+
+ @Override
+ 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.fillSlice(bytesRef, address, length);
+ }
+
+ @Override
+ public int getValueCount() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_VAR_STRAIGHT;
+ }
+
+ @Override
+ protected int maxDoc() {
+ return addresses.size();
+ }
+ }
+
+ @Override
+ public DocValuesEnum getEnum(AttributeSource source) throws IOException {
+ return new VarStraightBytesEnum(source, cloneData(), cloneIndex());
+ }
+
+ private class VarStraightBytesEnum extends DocValuesEnum {
+ private final PackedInts.Reader addresses;
+ private final IndexInput datIn;
+ private final IndexInput idxIn;
+ private final long fp;
- private final int totBytes;
++ private final long totBytes;
+ private int pos = -1;
+
+ protected VarStraightBytesEnum(AttributeSource source, IndexInput datIn,
+ IndexInput idxIn) throws IOException {
+ super(source, Type.BYTES_VAR_STRAIGHT);
- totBytes = idxIn.readVInt();
++ totBytes = idxIn.readVLong();
+ fp = datIn.getFilePointer();
+ addresses = PackedInts.getReader(idxIn);
+ this.datIn = datIn;
+ this.idxIn = idxIn;
+ }
+
+ @Override
+ public void close() throws IOException {
+ datIn.close();
+ idxIn.close();
+ }
+
+ @Override
+ public int advance(final int target) throws IOException {
+ if (target >= maxDoc) {
+ return pos = NO_MORE_DOCS;
+ }
+ final long addr = addresses.get(target);
+ if (addr == totBytes) { // empty values at the end
+ bytesRef.length = 0;
+ bytesRef.offset = 0;
+ return pos = target;
+ }
+ datIn.seek(fp + addr);
+ final int size = (int) (target == maxDoc - 1 ? totBytes - addr
+ : addresses.get(target + 1) - addr);
+ if (bytesRef.bytes.length < size) {
+ bytesRef.grow(size);
+ }
+ bytesRef.length = size;
+ datIn.readBytes(bytesRef.bytes, 0, size);
+ return pos = target;
+ }
+
+ @Override
+ public int docID() {
+ return pos;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ return advance(pos + 1);
+ }
+ }
+
+ @Override
+ public Type type() {
+ return Type.BYTES_VAR_STRAIGHT;
+ }
+ }
+}
diff --cc lucene/src/java/org/apache/lucene/search/FieldComparator.java
index fc6cb5cacb3,de8c59d8408..3f9bade3350
--- a/lucene/src/java/org/apache/lucene/search/FieldComparator.java
+++ b/lucene/src/java/org/apache/lucene/search/FieldComparator.java
@@@ -39,10 -38,11 +39,11 @@@ import org.apache.lucene.search.cache.C
import org.apache.lucene.search.cache.CachedArray.IntValues;
import org.apache.lucene.search.cache.CachedArray.LongValues;
import org.apache.lucene.search.cache.CachedArray.ShortValues;
+ import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.packed.Direct8;
import org.apache.lucene.util.packed.Direct16;
import org.apache.lucene.util.packed.Direct32;
+import org.apache.lucene.util.packed.Direct8;
import org.apache.lucene.util.packed.PackedInts;
/**
diff --cc lucene/src/java/org/apache/lucene/util/IOUtils.java
index 40cde1b9095,b31f3b00aac..37ca12322f1
--- a/lucene/src/java/org/apache/lucene/util/IOUtils.java
+++ b/lucene/src/java/org/apache/lucene/util/IOUtils.java
@@@ -59,10 -59,32 +59,33 @@@ public final class IOUtils
}
}
- if (priorException != null)
+ if (priorException != null) {
throw priorException;
- else if (firstIOE != null)
+ } else if (firstIOE != null) {
throw firstIOE;
+ }
}
+
+ /**
+ * <p>Closes all given <tt>Closeable</tt>s, suppressing all thrown exceptions. Some of the <tt>Closeable</tt>s
+ * may be null, they are ignored. After everything is closed, method either throws the first of suppressed exceptions,
+ * or completes normally.</p>
+ * @param objects objects to call <tt>close()</tt> on
+ */
+ public static void closeSafely(Closeable... objects) throws IOException {
+ IOException firstIOE = null;
+
+ for (Closeable object : objects) {
+ try {
+ if (object != null)
+ object.close();
+ } catch (IOException ioe) {
+ if (firstIOE == null)
+ firstIOE = ioe;
+ }
+ }
+
+ if (firstIOE != null)
+ throw firstIOE;
+ }
}
diff --cc lucene/src/test/org/apache/lucene/index/TestCodecs.java
index 38c80c30bec,92b8368b5b8..544f6e5a887
--- a/lucene/src/test/org/apache/lucene/index/TestCodecs.java
+++ b/lucene/src/test/org/apache/lucene/index/TestCodecs.java
@@@ -608,8 -607,8 +608,7 @@@ public class TestCodecs extends LuceneT
final int termIndexInterval = this.nextInt(13, 27);
final SegmentCodecs codecInfo = SegmentCodecs.build(fieldInfos, CodecProvider.getDefault());
- final SegmentWriteState state = new SegmentWriteState(null, dir, SEGMENT, fieldInfos, null, 10000, 10000, termIndexInterval, codecInfo, new AtomicLong());
- final SegmentWriteState state = new SegmentWriteState(null, dir, SEGMENT, fieldInfos, 10000, termIndexInterval, codecInfo);
--
++ final SegmentWriteState state = new SegmentWriteState(null, dir, SEGMENT, fieldInfos, 10000, termIndexInterval, codecInfo, new AtomicLong());
final FieldsConsumer consumer = state.segmentCodecs.codec().fieldsConsumer(state);
Arrays.sort(fields);
for (final FieldData field : fields) {
diff --cc lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.java
index e3961c9418c,00000000000..b3ad9f5a213
mode 100644,000000..100644
--- a/lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.java
+++ b/lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.java
@@@ -1,594 -1,0 +1,598 @@@
+package org.apache.lucene.index.values;
+
+/**
+ * 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.Closeable;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.List;
+
+import org.apache.lucene.analysis.MockAnalyzer;
+import org.apache.lucene.document.AbstractField;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.ValuesField;
+import org.apache.lucene.document.Field.Index;
+import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.index.CorruptIndexException;
+import org.apache.lucene.index.Fields;
+import org.apache.lucene.index.FieldsEnum;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.LogDocMergePolicy;
+import org.apache.lucene.index.LogMergePolicy;
+import org.apache.lucene.index.MergePolicy;
+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.MissingValue;
+import org.apache.lucene.index.values.DocValues.Source;
+import org.apache.lucene.queryParser.ParseException;
+import org.apache.lucene.queryParser.QueryParser;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.ScoreDoc;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.LockObtainFailedException;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.FloatsRef;
+import org.apache.lucene.util.LongsRef;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.OpenBitSet;
+import org.apache.lucene.util._TestUtil;
+import org.junit.Before;
+
+/**
+ *
+ * Tests DocValues integration into IndexWriter & Codecs
+ *
+ */
+public class TestDocValuesIndexing extends LuceneTestCase {
+ /*
+ * TODO: Roadmap to land on trunk
+ *
- * - Add documentation for: - Source and ValuesEnum - DocValues - ValuesField
- * - ValuesAttribute - Values - Add @lucene.experimental to all necessary
- * classes - add test for unoptimized case with deletes - add a test for
- * addIndexes - split up existing testcases and give them meaningfull names -
- * run RAT - add tests for FieldComparator FloatIndexValuesComparator vs.
- * FloatValuesComparator etc.
++ * - Add documentation for:
++ * - Source and ValuesEnum
++ * - DocValues
++ * - ValuesField
++ * - Values
++ * - Add @lucene.experimental to all necessary classes
++ * - add test for unoptimized case with deletes
++ * - run RAT
++ * - add tests for FieldComparator FloatIndexValuesComparator vs. FloatValuesComparator etc.
++ *
+ */
+
+ private DocValuesCodec docValuesCodec;
+ private CodecProvider provider;
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp();
+ String defaultFieldCodec = CodecProvider.getDefault()
+ .getDefaultFieldCodec();
+ provider = new CodecProvider();
+ docValuesCodec = new DocValuesCodec(CodecProvider.getDefault().lookup(
+ defaultFieldCodec));
+ provider.register(docValuesCodec);
+ provider.setDefaultFieldCodec(docValuesCodec.name);
+ }
+
+ /*
+ * Simple test case to show how to use the API
+ */
+ public void testDocValuesSimple() throws CorruptIndexException, IOException,
+ ParseException {
+ Directory dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, writerConfig(false));
+ for (int i = 0; i < 5; i++) {
+ Document doc = new Document();
+ ValuesField valuesField = new ValuesField("docId");
+ valuesField.setInt(i);
+ doc.add(valuesField);
+ doc.add(new Field("docId", "" + i, Store.NO, Index.ANALYZED));
+ writer.addDocument(doc);
+ }
+ writer.commit();
+ writer.optimize(true);
+
- writer.close();
++ writer.close(true);
+
+ IndexReader reader = IndexReader.open(dir, null, true, 1, provider);
+ assertTrue(reader.isOptimized());
+
+ IndexSearcher searcher = new IndexSearcher(reader);
+ QueryParser parser = new QueryParser(TEST_VERSION_CURRENT, "docId",
+ new MockAnalyzer());
+ TopDocs search = searcher.search(parser.parse("0 OR 1 OR 2 OR 3 OR 4"), 10);
+ assertEquals(5, search.totalHits);
+ ScoreDoc[] scoreDocs = search.scoreDocs;
+ DocValues docValues = MultiFields.getDocValues(reader, "docId");
+ Source source = docValues.getSource();
+ for (int i = 0; i < scoreDocs.length; i++) {
+ assertEquals(i, scoreDocs[i].doc);
+ assertEquals(i, source.getInt(scoreDocs[i].doc));
+ }
+ reader.close();
+ dir.close();
+ }
+
+ /**
+ * Tests complete indexing of {@link Type} including deletions, merging and
+ * sparse value fields on Compound-File
+ */
+ 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 Type} including deletions, merging and
+ * sparse value fields on None-Compound-File
+ */
+ 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);
+ }
+
+ public void testAddIndexes() throws IOException {
+ int valuesPerIndex = 10;
+ List<Type> values = Arrays.asList(Type.values());
+ Collections.shuffle(values, random);
+ Type first = values.get(0);
+ Type second = values.get(1);
+ String msg = "[first=" + first.name() + ", second=" + second.name() + "]";
+ // index first index
+ Directory d_1 = newDirectory();
+ IndexWriter w_1 = new IndexWriter(d_1, writerConfig(random.nextBoolean()));
+ indexValues(w_1, valuesPerIndex, first, values, false, 7);
+ w_1.commit();
+ assertEquals(valuesPerIndex, w_1.maxDoc());
+ _TestUtil.checkIndex(d_1, w_1.getConfig().getCodecProvider());
+
+ // index second index
+ Directory d_2 = newDirectory();
+ IndexWriter w_2 = new IndexWriter(d_2, writerConfig(random.nextBoolean()));
+ indexValues(w_2, valuesPerIndex, second, values, false, 7);
+ w_2.commit();
+ assertEquals(valuesPerIndex, w_2.maxDoc());
+ _TestUtil.checkIndex(d_2, w_2.getConfig().getCodecProvider());
+
+ Directory target = newDirectory();
+ IndexWriter w = new IndexWriter(target, writerConfig(random.nextBoolean()));
+ IndexReader r_1 = IndexReader.open(w_1);
+ IndexReader r_2 = IndexReader.open(w_2);
+ if (random.nextBoolean()) {
+ w.addIndexes(d_1, d_2);
+ } else {
+ w.addIndexes(r_1, r_2);
+ }
- w.optimize();
++ w.optimize(true);
+ w.commit();
+
+ _TestUtil.checkIndex(target, w.getConfig().getCodecProvider());
+ assertEquals(valuesPerIndex * 2, w.maxDoc());
+
+ // check values
+
+ IndexReader merged = IndexReader.open(w);
+ DocValuesEnum vE_1 = getValuesEnum(getDocValues(r_1, first.name()));
+ DocValuesEnum vE_2 = getValuesEnum(getDocValues(r_2, second.name()));
+ DocValuesEnum vE_1_merged = getValuesEnum(getDocValues(merged, first.name()));
+ DocValuesEnum vE_2_merged = getValuesEnum(getDocValues(merged, second
+ .name()));
+ if (second == Type.BYTES_VAR_STRAIGHT || second == Type.BYTES_FIXED_STRAIGHT) {
+ assertEquals(msg, valuesPerIndex-1, vE_2_merged.advance(valuesPerIndex-1));
+ }
+ for (int i = 0; i < valuesPerIndex; i++) {
+ assertEquals(msg, i, vE_1.nextDoc());
+ assertEquals(msg, i, vE_1_merged.nextDoc());
+
+ assertEquals(msg, i, vE_2.nextDoc());
+ assertEquals(msg, i + valuesPerIndex, vE_2_merged.nextDoc());
+ }
+ assertEquals(msg, DocValuesEnum.NO_MORE_DOCS, vE_1.nextDoc());
+ assertEquals(msg, DocValuesEnum.NO_MORE_DOCS, vE_2.nextDoc());
+ assertEquals(msg, DocValuesEnum.NO_MORE_DOCS, vE_1_merged.advance(valuesPerIndex*2));
+ assertEquals(msg, DocValuesEnum.NO_MORE_DOCS, vE_2_merged.nextDoc());
+
+ // close resources
+ r_1.close();
+ r_2.close();
+ merged.close();
- w_1.close();
- w_2.close();
- w.close();
++ w_1.close(true);
++ w_2.close(true);
++ w.close(true);
+ d_1.close();
+ d_2.close();
+ target.close();
+ }
+
+ private IndexWriterConfig writerConfig(boolean useCompoundFile) {
+ final IndexWriterConfig cfg = newIndexWriterConfig(TEST_VERSION_CURRENT,
+ new MockAnalyzer());
+ MergePolicy mergePolicy = cfg.getMergePolicy();
+ if (mergePolicy instanceof LogMergePolicy) {
+ ((LogMergePolicy) mergePolicy).setUseCompoundFile(useCompoundFile);
+ } else if (useCompoundFile) {
+ LogMergePolicy policy = new LogDocMergePolicy();
+ policy.setUseCompoundFile(useCompoundFile);
+ cfg.setMergePolicy(policy);
+ }
+ cfg.setCodecProvider(provider);
+ return cfg;
+ }
+
+ public void runTestNumerics(IndexWriterConfig cfg, boolean withDeletions)
+ throws IOException {
+ Directory d = newDirectory();
+ IndexWriter w = new IndexWriter(d, cfg);
+ final int numValues = 179 + random.nextInt(151);
+ final List<Type> numVariantList = new ArrayList<Type>(NUMERICS);
+
+ // run in random order to test if fill works correctly during merges
+ Collections.shuffle(numVariantList, random);
+ for (Type val : numVariantList) {
+ OpenBitSet deleted = indexValues(w, numValues, val, numVariantList,
+ withDeletions, 7);
+ List<Closeable> closeables = new ArrayList<Closeable>();
+ IndexReader r = IndexReader.open(w);
+ final int numRemainingValues = (int) (numValues - deleted.cardinality());
+ final int base = r.numDocs() - numRemainingValues;
+ switch (val) {
+ case PACKED_INTS: {
+ DocValues intsReader = getDocValues(r, val.name());
+ assertNotNull(intsReader);
+
+ Source ints = getSource(intsReader);
+ MissingValue missing = ints.getMissing();
+
+ for (int i = 0; i < base; i++) {
+ long value = ints.getInt(i);
+ assertEquals("index " + i, missing.longValue, value);
+ }
+
+ DocValuesEnum 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)) {
+ expected++;
+ }
+ assertEquals("advance failed at index: " + i + " of " + r.numDocs()
+ + " docs", i, intsEnum.advance(i));
+ assertEquals(expected, enumRef.get());
+ assertEquals(expected, ints.getInt(i));
+
+ }
+ }
+ break;
+ case SIMPLE_FLOAT_4BYTE:
+ case SIMPLE_FLOAT_8BYTE: {
+ DocValues floatReader = getDocValues(r, val.name());
+ assertNotNull(floatReader);
+ Source floats = getSource(floatReader);
+ MissingValue missing = floats.getMissing();
+
+ for (int i = 0; i < base; i++) {
+ double value = floats.getFloat(i);
+ assertEquals(" floats failed for doc: " + i + " base: " + base,
+ missing.doubleValue, value, 0.0d);
+ }
+ DocValuesEnum 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)) {
+ expected++;
+ }
+ assertEquals("advance failed at index: " + i + " of " + r.numDocs()
+ + " docs base:" + base, i, floatEnum.advance(i));
+ assertEquals(floatEnum.getClass() + " index " + i, 2.0 * expected,
+ enumRef.get(), 0.00001);
+ assertEquals("index " + i, 2.0 * expected, floats.getFloat(i),
+ 0.00001);
+ }
+ }
+ break;
+ default:
+ fail("unexpected value " + val);
+ }
+
+ closeables.add(r);
+ for (Closeable toClose : closeables) {
+ toClose.close();
+ }
+ }
+ w.close();
+ d.close();
+ }
+
+ public void runTestIndexBytes(IndexWriterConfig cfg, boolean withDeletions)
+ throws CorruptIndexException, LockObtainFailedException, IOException {
+ final Directory d = newDirectory();
+ IndexWriter w = new IndexWriter(d, cfg);
+ final List<Type> byteVariantList = new ArrayList<Type>(BYTES);
+ // run in random order to test if fill works correctly during merges
+ Collections.shuffle(byteVariantList, random);
+ final int numValues = 179 + random.nextInt(151);
+ for (Type byteIndexValue : byteVariantList) {
+ List<Closeable> closeables = new ArrayList<Closeable>();
+
+ int bytesSize = 7 + random.nextInt(128);
+ OpenBitSet deleted = indexValues(w, numValues, byteIndexValue,
+ byteVariantList, withDeletions, bytesSize);
+ final IndexReader r = IndexReader.open(w);
+ assertEquals(0, r.numDeletedDocs());
+ final int numRemainingValues = (int) (numValues - deleted.cardinality());
+ final int base = r.numDocs() - numRemainingValues;
+ DocValues bytesReader = getDocValues(r, byteIndexValue.name());
+ assertNotNull("field " + byteIndexValue.name()
+ + " returned null reader - maybe merged failed", bytesReader);
+ Source bytes = getSource(bytesReader);
+ byte upto = 0;
+
+ // test the filled up slots for correctness
+ MissingValue missing = bytes.getMissing();
+ for (int i = 0; i < base; 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:
+ // fixed straight returns bytesref with zero bytes all of fixed
+ // length
+ 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:
+ case BYTES_FIXED_SORTED:
+ case BYTES_VAR_DEREF:
+ case BYTES_FIXED_DEREF:
+ default:
+ assertNull("expected null - " + msg + " " + br, br);
+ // make sure we advance at least until base
+ DocValuesEnum bytesEnum = getValuesEnum(bytesReader);
+ final int advancedTo = bytesEnum.advance(0);
+ assertTrue(byteIndexValue.name() + " advanced failed base:" + base
+ + " advancedTo: " + advancedTo, base <= advancedTo);
+
+ }
+ }
+
+ DocValuesEnum bytesEnum = getValuesEnum(bytesReader);
+ final BytesRef enumRef = bytesEnum.bytes();
+ // test the actual doc values added in this iteration
+ assertEquals(base + numRemainingValues, r.numDocs());
+ int v = 0;
+ for (int i = base; i < r.numDocs(); i++) {
+ String msg = " field: " + byteIndexValue.name() + " at index: " + i
+ + " base: " + base + " numDocs:" + r.numDocs() + " bytesSize: "
+ + bytesSize;
+ while (withDeletions && deleted.get(v++)) {
+ upto += bytesSize;
+ }
+
+ 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++) {
+ assertTrue(" enumRef not initialized " + msg,
+ enumRef.bytes.length > 0);
+ 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]);
+ }
+ }
+
+ // clean up
+ closeables.add(r);
+ for (Closeable toClose : closeables) {
+ toClose.close();
+ }
+ }
+
+ w.close();
+ d.close();
+ }
+
+ private DocValues getDocValues(IndexReader reader, String field)
+ throws IOException {
+ boolean optimized = reader.isOptimized();
+ reader.isCurrent();
+ Fields fields = optimized ? reader.getSequentialSubReaders()[0].fields()
+ : MultiFields.getFields(reader);
+ switch (random.nextInt(optimized ? 3 : 2)) { // case 2 only if optimized
+ case 0:
+ return fields.docValues(field);
+ case 1:
+ FieldsEnum iterator = fields.iterator();
+ String name;
+ while ((name = iterator.next()) != null) {
+ if (name.equals(field))
+ return iterator.docValues();
+ }
+ throw new RuntimeException("no such field " + field);
+ case 2:// this only works if we are on an optimized index!
+ return reader.getSequentialSubReaders()[0].docValues(field);
+ }
+ throw new RuntimeException();
+ }
+
+ private Source getSource(DocValues values) throws IOException {
+ Source source;
+ if (random.nextInt(10) == 0) {
+ source = values.load();
+ } else {
+ // getSource uses cache internally
+ source = values.getSource();
+ }
+ assertNotNull(source);
+ return source;
+ }
+
+ private DocValuesEnum getValuesEnum(DocValues values) throws IOException {
+ DocValuesEnum 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<Type> BYTES = EnumSet.of(Type.BYTES_FIXED_DEREF,
+ Type.BYTES_FIXED_SORTED, Type.BYTES_FIXED_STRAIGHT, Type.BYTES_VAR_DEREF,
+ Type.BYTES_VAR_SORTED, Type.BYTES_VAR_STRAIGHT);
+
+ private static EnumSet<Type> NUMERICS = EnumSet.of(Type.PACKED_INTS,
+ Type.SIMPLE_FLOAT_4BYTE, Type.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, Type value,
+ List<Type> 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)];
+ AbstractField 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);
+ ValuesField valField = new ValuesField("prototype");
+ final BytesRef bytesRef = new BytesRef();
+
+ 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:
+ valField.setInt(i);
+ break;
+ case SIMPLE_FLOAT_4BYTE:
+ case SIMPLE_FLOAT_8BYTE:
+ valField.setFloat(2.0f * i);
+ break;
+ default:
+ fail("unexpected value " + value);
+ }
+ } else {
+ for (int j = 0; j < b.length; j++) {
+ b[j] = upto++;
+ }
+ valField.setBytes(bytesRef, value);
+ }
+ doc.removeFields("id");
+ doc.add(new Field("id", idBase + i, Store.YES,
+ Index.NOT_ANALYZED_NO_NORMS));
+ valField.set(field);
+ w.addDocument(doc);
+
+ if (i % 7 == 0) {
+ if (withDeletions && random.nextBoolean()) {
+ Type 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();
++ w.optimize(true);
+ return deleted;
+ }
+}