Apache Lucene open-source search software
catch up with trunk and moved DocValues to PerDoc Codec API
Simon Willnauera54567963a44
diff --cc lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.javaindex 742e101ce93,301ff986fc2..656a5a48ed8--- a/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.java+++ b/lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.java@@@ -32,8 -32,7 +32,7 @@@ import java.util.Comparatorimport org.apache.lucene.document.Document;import org.apache.lucene.document.FieldSelector;import org.apache.lucene.index.*;- import org.apache.lucene.index.values.DocValues;--import org.apache.lucene.index.IndexReader.ReaderContext;++import org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.store.Directory;import org.apache.lucene.util.BitVector;import org.apache.lucene.util.BytesRef;@@@ -498,4 -487,4 +487,9 @@@ public class InstantiatedIndexReader ex}}}++++ @Override++ public PerDocValues perDocValues() throws IOException {++ return null;++ }}diff --cc lucene/contrib/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.javaindex 8103b01f30c,89e79e01689..947d2eb658b--- a/lucene/contrib/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java+++ b/lucene/contrib/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.java@@@ -52,7 -52,6 +52,7 @@@ import org.apache.lucene.index.TermPosiimport org.apache.lucene.index.TermVectorMapper;import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.index.IndexReader.ReaderContext;- import org.apache.lucene.index.values.DocValues;++import org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.search.Collector;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;@@@ -1287,6 -1274,6 +1275,11 @@@ public class MemoryIndexreturn Collections.unmodifiableSet(fields.keySet());}++++ @Override++ public PerDocValues perDocValues() throws IOException {++ return null;++ }}diff --cc lucene/src/java/org/apache/lucene/index/DirectoryReader.javaindex e89ac12ac68,78174cdf3b6..0c1a297b742--- a/lucene/src/java/org/apache/lucene/index/DirectoryReader.java+++ b/lucene/src/java/org/apache/lucene/index/DirectoryReader.java@@@ -35,6 -35,6 +35,7 @@@ import org.apache.lucene.store.Directorimport org.apache.lucene.store.Lock;import org.apache.lucene.store.LockObtainFailedException;import org.apache.lucene.index.codecs.CodecProvider;++import org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.MapBackedSet;@@@ -1024,4 -1024,4 +1025,9 @@@ class DirectoryReader extends IndexReadthrow new UnsupportedOperationException("This IndexCommit does not support deletions");}}++++ @Override++ public PerDocValues perDocValues() throws IOException {++ throw new UnsupportedOperationException("please use MultiPerDoc#getPerDocs, or wrap your IndexReader with SlowMultiReaderWrapper, if you really need a top level Fields");++ }}diff --cc lucene/src/java/org/apache/lucene/index/DocFieldProcessor.javaindex a566e72f9bb,7dbeb099c41..3f7faf62c20--- a/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java+++ b/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java@@@ -20,13 -20,14 +20,20 @@@ package org.apache.lucene.indeximport java.io.IOException;import java.util.Collection;import java.util.HashMap;+ import java.util.HashSet;+ import java.util.List;import java.util.Map;- import org.apache.lucene.index.codecs.FieldsConsumer;+ import org.apache.lucene.document.Document;+ import org.apache.lucene.document.Fieldable;++import org.apache.lucene.index.DocumentsWriterPerThread.DocState;++import org.apache.lucene.index.codecs.Codec;++import org.apache.lucene.index.codecs.PerDocConsumer;+import org.apache.lucene.index.codecs.docvalues.DocValuesConsumer;+import org.apache.lucene.index.values.PerDocFieldValues;+import org.apache.lucene.store.Directory;+/*** This is a DocConsumer that gathers all fields under the* same name, and calls per-field consumers to process field@@@ -104,12 -78,24 +84,35 @@@ final class DocFieldProcessor extends D// FieldInfo.storePayload.final String fileName = IndexFileNames.segmentFileName(state.segmentName, "", IndexFileNames.FIELD_INFOS_EXTENSION);state.fieldInfos.write(state.directory, fileName);++ for (DocValuesConsumer consumers : docValues.values()) {++ consumers.finish(state.numDocs);++ };}@Overridepublic void abort() {- fieldsWriter.abort();- consumer.abort();+ for(int i=0;i<fieldHash.length;i++) {+ DocFieldProcessorPerField field = fieldHash[i];+ while(field != null) {+ final DocFieldProcessorPerField next = field.next;+ field.abort();+ field = next;+ }+ }++++ for(PerDocConsumer consumer : perDocConsumers.values()) {++ try {++ consumer.close(); // TODO add abort to PerDocConsumer!++ } catch (IOException e) {++ // nocommit handle exce++ }++ }++ try {+ fieldsWriter.abort();+ } finally {+ consumer.abort();+ }}@Override@@@ -117,8 -103,213 +120,250 @@@return consumer.freeRAM();}+ public Collection<DocFieldConsumerPerField> fields() {+ Collection<DocFieldConsumerPerField> fields = new HashSet<DocFieldConsumerPerField>();+ for(int i=0;i<fieldHash.length;i++) {+ DocFieldProcessorPerField field = fieldHash[i];+ while(field != null) {+ fields.add(field.consumer);+ field = field.next;+ }+ }+ assert fields.size() == totalFieldCount;+ return fields;+ }++ /** In flush we reset the fieldHash to not maintain per-field state+ * across segments */+ @Override+ void doAfterFlush() {+ fieldHash = new DocFieldProcessorPerField[2];+ hashMask = 1;+ totalFieldCount = 0;++ for(PerDocConsumer consumer : perDocConsumers.values()) {++ try {++ consumer.close();++ } catch (IOException e) {++ // nocommit handle exce++ }++ }++ perDocConsumers.clear();++ docValues.clear();+ }++ private void rehash() {+ final int newHashSize = (fieldHash.length*2);+ assert newHashSize > fieldHash.length;++ final DocFieldProcessorPerField newHashArray[] = new DocFieldProcessorPerField[newHashSize];++ // Rehash+ int newHashMask = newHashSize-1;+ for(int j=0;j<fieldHash.length;j++) {+ DocFieldProcessorPerField fp0 = fieldHash[j];+ while(fp0 != null) {+ final int hashPos2 = fp0.fieldInfo.name.hashCode() & newHashMask;+ DocFieldProcessorPerField nextFP0 = fp0.next;+ fp0.next = newHashArray[hashPos2];+ newHashArray[hashPos2] = fp0;+ fp0 = nextFP0;+ }+ }++ fieldHash = newHashArray;+ hashMask = newHashMask;+ }++ @Override+ public void processDocument(FieldInfos fieldInfos) throws IOException {++ consumer.startDocument();+ fieldsWriter.startDocument();++ final Document doc = docState.doc;++ fieldCount = 0;++ final int thisFieldGen = fieldGen++;++ final List<Fieldable> docFields = doc.getFields();+ final int numDocFields = docFields.size();++ // Absorb any new fields first seen in this document.+ // Also absorb any changes to fields we had already+ // seen before (eg suddenly turning on norms or+ // vectors, etc.):++ for(int i=0;i<numDocFields;i++) {+ Fieldable field = docFields.get(i);+ final String fieldName = field.name();++ // Make sure we have a PerField allocated+ final int hashPos = fieldName.hashCode() & hashMask;+ DocFieldProcessorPerField fp = fieldHash[hashPos];+ while(fp != null && !fp.fieldInfo.name.equals(fieldName)) {+ fp = fp.next;+ }++ if (fp == null) {++ // TODO FI: we need to genericize the "flags" that a+ // field holds, and, how these flags are merged; it+ // needs to be more "pluggable" such that if I want+ // to have a new "thing" my Fields can do, I can+ // easily add it+ FieldInfo fi = fieldInfos.addOrUpdate(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;+ totalFieldCount++;++ if (totalFieldCount >= fieldHash.length/2)+ rehash();+ } else {+ fieldInfos.addOrUpdate(fp.fieldInfo.name, field.isIndexed(), field.isTermVectorStored(),+ field.isStorePositionWithTermVector(), field.isStoreOffsetWithTermVector(),- field.getOmitNorms(), false, field.getOmitTermFreqAndPositions());++ field.getOmitNorms(), false, field.getOmitTermFreqAndPositions(), field.docValuesType());+ }++ if (thisFieldGen != fp.lastGen) {++ // First time we're seeing this field for this doc+ fp.fieldCount = 0;++ if (fieldCount == fields.length) {+ final int newSize = fields.length*2;+ DocFieldProcessorPerField newArray[] = new DocFieldProcessorPerField[newSize];+ System.arraycopy(fields, 0, newArray, 0, fieldCount);+ fields = newArray;+ }++ fields[fieldCount++] = fp;+ fp.lastGen = thisFieldGen;+ }++ fp.addField(field);++ if (field.isStored()) {+ fieldsWriter.addField(field, fp.fieldInfo);+ }++ if (field.hasDocValues()) {++ final DocValuesConsumer docValuesConsumer = docValuesConsumer(docState, fp.fieldInfo, fieldInfos);++ docValuesConsumer.add(docState.docID, field.getDocValues());++ }+ }++ // If we are writing vectors then we must visit+ // fields in sorted order so they are written in+ // sorted order. TODO: we actually only need to+ // sort the subset of fields that have vectors+ // enabled; we could save [small amount of] CPU+ // here.+ quickSort(fields, 0, fieldCount-1);++ for(int i=0;i<fieldCount;i++)+ fields[i].consumer.processFields(fields[i].fields, fields[i].fieldCount);++ if (docState.maxTermPrefix != null && docState.infoStream != null) {+ docState.infoStream.println("WARNING: document contains at least one immense term (whose UTF8 encoding is longer than the max length " + DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8 + "), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '" + docState.maxTermPrefix + "...'");+ docState.maxTermPrefix = null;+ }+ }+@Override- public DocConsumerPerThread addThread(DocumentsWriterThreadState threadState) throws IOException {- return new DocFieldProcessorPerThread(threadState, this);+ void finishDocument() throws IOException {+ try {+ fieldsWriter.finishDocument();+ } finally {+ consumer.finishDocument();+ }}++ void quickSort(DocFieldProcessorPerField[] array, int lo, int hi) {+ if (lo >= hi)+ return;+ else if (hi == 1+lo) {+ if (array[lo].fieldInfo.name.compareTo(array[hi].fieldInfo.name) > 0) {+ final DocFieldProcessorPerField tmp = array[lo];+ array[lo] = array[hi];+ array[hi] = tmp;+ }+ return;+ }++ int mid = (lo + hi) >>> 1;++ if (array[lo].fieldInfo.name.compareTo(array[mid].fieldInfo.name) > 0) {+ DocFieldProcessorPerField tmp = array[lo];+ array[lo] = array[mid];+ array[mid] = tmp;+ }++ if (array[mid].fieldInfo.name.compareTo(array[hi].fieldInfo.name) > 0) {+ DocFieldProcessorPerField tmp = array[mid];+ array[mid] = array[hi];+ array[hi] = tmp;++ if (array[lo].fieldInfo.name.compareTo(array[mid].fieldInfo.name) > 0) {+ DocFieldProcessorPerField tmp2 = array[lo];+ array[lo] = array[mid];+ array[mid] = tmp2;+ }+ }++ int left = lo + 1;+ int right = hi - 1;++ if (left >= right)+ return;++ DocFieldProcessorPerField partition = array[mid];++ for (; ;) {+ while (array[right].fieldInfo.name.compareTo(partition.fieldInfo.name) > 0)+ --right;++ while (left < right && array[left].fieldInfo.name.compareTo(partition.fieldInfo.name) <= 0)+ ++left;++ if (left < right) {+ DocFieldProcessorPerField tmp = array[left];+ array[left] = array[right];+ array[right] = tmp;+ --right;+ } else {+ break;+ }+ }++ quickSort(array, lo, left);+ quickSort(array, left + 1, hi);+ }++ final private Map<String, DocValuesConsumer> docValues = new HashMap<String, DocValuesConsumer>();++ final private Map<Integer, PerDocConsumer> perDocConsumers = new HashMap<Integer, PerDocConsumer>();++++ DocValuesConsumer docValuesConsumer(DocState docState, FieldInfo fieldInfo, FieldInfos infos)++ throws IOException {++ DocValuesConsumer docValuesConsumer = docValues.get(fieldInfo.name);++ if (docValuesConsumer != null) {++ return docValuesConsumer;++ }++ PerDocConsumer perDocConsumer = perDocConsumers.get(fieldInfo.getCodecId());++ if (perDocConsumer == null) {++ PerDocWriteState perDocWriteState = docState.docWriter.newPerDocWriteState(fieldInfo.getCodecId());++ SegmentCodecs codecs = perDocWriteState.segmentCodecs;++ assert codecs.codecs.length > fieldInfo.getCodecId();++++ Codec codec = codecs.codecs[fieldInfo.getCodecId()];++ perDocConsumer = codec.docsConsumer(perDocWriteState);++ perDocConsumers.put(Integer.valueOf(fieldInfo.getCodecId()), perDocConsumer);++ }++ docValuesConsumer = perDocConsumer.addValuesField(fieldInfo);++ docValues.put(fieldInfo.name, docValuesConsumer);++ return docValuesConsumer;++ }++}diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThread.javaindex 00000000000,4ffb1e0ccf7..e943055bc37mode 000000,100644..100644--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java@@@ -1,0 -1,496 +1,501 @@@+ package org.apache.lucene.index;++ /**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++ import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_MASK;+ import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE;++ import java.io.IOException;+ import java.io.PrintStream;+ import java.text.NumberFormat;+ import java.util.concurrent.atomic.AtomicLong;++ import org.apache.lucene.analysis.Analyzer;+ import org.apache.lucene.document.Document;+ import org.apache.lucene.index.DocumentsWriterDeleteQueue.DeleteSlice;+ import org.apache.lucene.search.SimilarityProvider;+ import org.apache.lucene.store.Directory;+ import org.apache.lucene.util.BitVector;+ import org.apache.lucene.util.ByteBlockPool.Allocator;+ import org.apache.lucene.util.RamUsageEstimator;++ public class DocumentsWriterPerThread {++ /**+ * The IndexingChain must define the {@link #getChain(DocumentsWriter)} method+ * which returns the DocConsumer that the DocumentsWriter calls to process the+ * documents.+ */+ abstract static class IndexingChain {+ abstract DocConsumer getChain(DocumentsWriterPerThread documentsWriterPerThread);+ }+++ static final IndexingChain defaultIndexingChain = new IndexingChain() {++ @Override+ DocConsumer getChain(DocumentsWriterPerThread documentsWriterPerThread) {+ /*+ This is the current indexing chain:++ DocConsumer / DocConsumerPerThread+ --> code: DocFieldProcessor / DocFieldProcessorPerThread+ --> DocFieldConsumer / DocFieldConsumerPerThread / DocFieldConsumerPerField+ --> code: DocFieldConsumers / DocFieldConsumersPerThread / DocFieldConsumersPerField+ --> code: DocInverter / DocInverterPerThread / DocInverterPerField+ --> InvertedDocConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField+ --> code: TermsHash / TermsHashPerThread / TermsHashPerField+ --> TermsHashConsumer / TermsHashConsumerPerThread / TermsHashConsumerPerField+ --> code: FreqProxTermsWriter / FreqProxTermsWriterPerThread / FreqProxTermsWriterPerField+ --> code: TermVectorsTermsWriter / TermVectorsTermsWriterPerThread / TermVectorsTermsWriterPerField+ --> InvertedDocEndConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField+ --> code: NormsWriter / NormsWriterPerThread / NormsWriterPerField+ --> code: StoredFieldsWriter / StoredFieldsWriterPerThread / StoredFieldsWriterPerField+ */++ // Build up indexing chain:++ final TermsHashConsumer termVectorsWriter = new TermVectorsTermsWriter(documentsWriterPerThread);+ final TermsHashConsumer freqProxWriter = new FreqProxTermsWriter();++ final InvertedDocConsumer termsHash = new TermsHash(documentsWriterPerThread, freqProxWriter, true,+ new TermsHash(documentsWriterPerThread, termVectorsWriter, false, null));+ final NormsWriter normsWriter = new NormsWriter();+ final DocInverter docInverter = new DocInverter(documentsWriterPerThread.docState, termsHash, normsWriter);+ return new DocFieldProcessor(documentsWriterPerThread, docInverter);+ }+ };++ static class DocState {+ final DocumentsWriterPerThread docWriter;+ Analyzer analyzer;+ PrintStream infoStream;+ SimilarityProvider similarityProvider;+ int docID;+ Document doc;+ String maxTermPrefix;++ DocState(DocumentsWriterPerThread docWriter) {+ this.docWriter = docWriter;+ }++ // Only called by asserts+ public boolean testPoint(String name) {+ return docWriter.writer.testPoint(name);+ }++ public void clear() {+ // don't hold onto doc nor analyzer, in case it is+ // largish:+ doc = null;+ analyzer = null;+ }+ }++ static class FlushedSegment {+ final SegmentInfo segmentInfo;+ final BufferedDeletes segmentDeletes;+ final BitVector deletedDocuments;++ private FlushedSegment(SegmentInfo segmentInfo,+ BufferedDeletes segmentDeletes, BitVector deletedDocuments) {+ this.segmentInfo = segmentInfo;+ this.segmentDeletes = segmentDeletes;+ this.deletedDocuments = deletedDocuments;+ }+ }++ /** Called if we hit an exception at a bad time (when+ * updating the index files) and must discard all+ * currently buffered docs. This resets our state,+ * discarding any docs added since last flush. */+ void abort() throws IOException {+ hasAborted = aborting = true;+ try {+ if (infoStream != null) {+ message("docWriter: now abort");+ }+ try {+ consumer.abort();+ } catch (Throwable t) {+ }++ pendingDeletes.clear();+ deleteSlice = deleteQueue.newSlice();+ // Reset all postings data+ doAfterFlush();++ } finally {+ aborting = false;+ if (infoStream != null) {+ message("docWriter: done abort");+ }+ }+ }++ final DocumentsWriter parent;+ final IndexWriter writer;+ final Directory directory;+ final DocState docState;+ final DocConsumer consumer;+ final AtomicLong bytesUsed;++ SegmentWriteState flushState;+ //Deletes for our still-in-RAM (to be flushed next) segment+ BufferedDeletes pendingDeletes;+ String segment; // Current segment we are working on+ boolean aborting = false; // True if an abort is pending+ boolean hasAborted = false; // True if the last exception throws by #updateDocument was aborting++ private FieldInfos fieldInfos;+ private final PrintStream infoStream;+ private int numDocsInRAM;+ private int flushedDocCount;+ DocumentsWriterDeleteQueue deleteQueue;+ DeleteSlice deleteSlice;+ private final NumberFormat nf = NumberFormat.getInstance();+++ public DocumentsWriterPerThread(Directory directory, DocumentsWriter parent,+ FieldInfos fieldInfos, IndexingChain indexingChain) {+ this.directory = directory;+ this.parent = parent;+ this.fieldInfos = fieldInfos;+ this.writer = parent.indexWriter;+ this.infoStream = parent.indexWriter.getInfoStream();+ this.docState = new DocState(this);+ this.docState.similarityProvider = parent.indexWriter.getConfig()+ .getSimilarityProvider();++ consumer = indexingChain.getChain(this);+ bytesUsed = new AtomicLong(0);+ pendingDeletes = new BufferedDeletes(false);+ initialize();+ }++ public DocumentsWriterPerThread(DocumentsWriterPerThread other, FieldInfos fieldInfos) {+ this(other.directory, other.parent, fieldInfos, other.parent.chain);+ }++ void initialize() {+ deleteQueue = parent.deleteQueue;+ assert numDocsInRAM == 0 : "num docs " + numDocsInRAM;+ pendingDeletes.clear();+ deleteSlice = null;+ }++ void setAborting() {+ aborting = true;+ }++ boolean checkAndResetHasAborted() {+ final boolean retval = hasAborted;+ hasAborted = false;+ return retval;+ }++ public void updateDocument(Document doc, Analyzer analyzer, Term delTerm) throws IOException {+ assert writer.testPoint("DocumentsWriterPerThread addDocument start");+ assert deleteQueue != null;+ docState.doc = doc;+ docState.analyzer = analyzer;+ docState.docID = numDocsInRAM;+ if (segment == null) {+ // this call is synchronized on IndexWriter.segmentInfos+ segment = writer.newSegmentName();+ assert numDocsInRAM == 0;+ }++ boolean success = false;+ try {+ try {+ consumer.processDocument(fieldInfos);+ } finally {+ docState.clear();+ }+ success = true;+ } finally {+ if (!success) {+ if (!aborting) {+ // mark document as deleted+ deleteDocID(docState.docID);+ numDocsInRAM++;+ } else {+ abort();+ }+ }+ }+ success = false;+ try {+ consumer.finishDocument();+ success = true;+ } finally {+ if (!success) {+ abort();+ }+ }+ finishDocument(delTerm);+ }++ private void finishDocument(Term delTerm) throws IOException {+ /*+ * here we actually finish the document in two steps 1. push the delete into+ * the queue and update our slice. 2. increment the DWPT private document+ * id.+ *+ * the updated slice we get from 1. holds all the deletes that have occurred+ * since we updated the slice the last time.+ */+ if (deleteSlice == null) {+ deleteSlice = deleteQueue.newSlice();+ if (delTerm != null) {+ deleteQueue.add(delTerm, deleteSlice);+ deleteSlice.reset();+ }++ } else {+ if (delTerm != null) {+ deleteQueue.add(delTerm, deleteSlice);+ assert deleteSlice.isTailItem(delTerm) : "expected the delete term as the tail item";+ deleteSlice.apply(pendingDeletes, numDocsInRAM);+ } else if (deleteQueue.updateSlice(deleteSlice)) {+ deleteSlice.apply(pendingDeletes, numDocsInRAM);+ }+ }+ ++numDocsInRAM;+ }++ // Buffer a specific docID for deletion. Currently only+ // used when we hit a exception when adding a document+ void deleteDocID(int docIDUpto) {+ pendingDeletes.addDocID(docIDUpto);+ // NOTE: we do not trigger flush here. This is+ // potentially a RAM leak, if you have an app that tries+ // to add docs but every single doc always hits a+ // non-aborting exception. Allowing a flush here gets+ // very messy because we are only invoked when handling+ // exceptions so to do this properly, while handling an+ // exception we'd have to go off and flush new deletes+ // which is risky (likely would hit some other+ // confounding exception).+ }++ /**+ * Returns the number of delete terms in this {@link DocumentsWriterPerThread}+ */+ public int numDeleteTerms() {+ // public for FlushPolicy+ return pendingDeletes.numTermDeletes.get();+ }++ /**+ * Returns the number of RAM resident documents in this {@link DocumentsWriterPerThread}+ */+ public int getNumDocsInRAM() {+ // public for FlushPolicy+ return numDocsInRAM;+ }++ SegmentCodecs getCodec() {+ return flushState.segmentCodecs;+ }++ /** Reset after a flush */+ private void doAfterFlush() throws IOException {+ segment = null;+ consumer.doAfterFlush();+ fieldInfos = new FieldInfos(fieldInfos);+ parent.subtractFlushedNumDocs(numDocsInRAM);+ numDocsInRAM = 0;+ }++ /**+ * Prepares this DWPT for flushing. This method will freeze and return the+ * {@link DocumentsWriterDeleteQueue}s global buffer and apply all pending+ * deletes to this DWPT.+ */+ FrozenBufferedDeletes prepareFlush() {+ assert numDocsInRAM > 0;+ final FrozenBufferedDeletes globalDeletes = deleteQueue.freezeGlobalBuffer(deleteSlice);+ /* deleteSlice can possibly be null if we have hit non-aborting exceptions during indexing and never succeeded+ adding a document. */+ if (deleteSlice != null) {+ // apply all deletes before we flush and release the delete slice+ deleteSlice.apply(pendingDeletes, numDocsInRAM);+ assert deleteSlice.isEmpty();+ deleteSlice = null;+ }+ return globalDeletes;+ }++ /** Flush all pending docs to a new segment */+ FlushedSegment flush() throws IOException {+ assert numDocsInRAM > 0;+ assert deleteSlice == null : "all deletes must be applied in prepareFlush";+ flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,+ numDocsInRAM, writer.getConfig().getTermIndexInterval(),+ fieldInfos.buildSegmentCodecs(true), pendingDeletes);+ final double startMBUsed = parent.flushControl.netBytes() / 1024. / 1024.;+ // Apply delete-by-docID now (delete-byDocID only+ // happens when an exception is hit processing that+ // doc, eg if analyzer has some problem w/ the text):+ if (pendingDeletes.docIDs.size() > 0) {+ flushState.deletedDocs = new BitVector(numDocsInRAM);+ for(int delDocID : pendingDeletes.docIDs) {+ flushState.deletedDocs.set(delDocID);+ }+ pendingDeletes.bytesUsed.addAndGet(-pendingDeletes.docIDs.size() * BufferedDeletes.BYTES_PER_DEL_DOCID);+ pendingDeletes.docIDs.clear();+ }++ if (infoStream != null) {+ message("flush postings as segment " + flushState.segmentName + " numDocs=" + numDocsInRAM);+ }++ if (aborting) {+ if (infoStream != null) {+ message("flush: skip because aborting is set");+ }+ return null;+ }++ boolean success = false;++ try {++ SegmentInfo newSegment = new SegmentInfo(segment, flushState.numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false, fieldInfos);+ consumer.flush(flushState);+ pendingDeletes.terms.clear();+ newSegment.setHasVectors(flushState.hasVectors);++ if (infoStream != null) {+ message("new segment has " + (flushState.deletedDocs == null ? 0 : flushState.deletedDocs.count()) + " deleted docs");+ message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors"));+ message("flushedFiles=" + newSegment.files());+ message("flushed codecs=" + newSegment.getSegmentCodecs());+ }+ flushedDocCount += flushState.numDocs;++ final BufferedDeletes segmentDeletes;+ if (pendingDeletes.queries.isEmpty()) {+ pendingDeletes.clear();+ segmentDeletes = null;+ } else {+ segmentDeletes = pendingDeletes;+ pendingDeletes = new BufferedDeletes(false);+ }++ if (infoStream != null) {+ final double newSegmentSizeNoStore = newSegment.sizeInBytes(false)/1024./1024.;+ final double newSegmentSize = newSegment.sizeInBytes(true)/1024./1024.;+ message("flushed: segment=" + newSegment ++ " ramUsed=" + nf.format(startMBUsed) + " MB" ++ " newFlushedSize=" + nf.format(newSegmentSize) + " MB" ++ " (" + nf.format(newSegmentSizeNoStore) + " MB w/o doc stores)" ++ " docs/MB=" + nf.format(flushedDocCount / newSegmentSize) ++ " new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startMBUsed) + "%");+ }+ doAfterFlush();+ success = true;++ return new FlushedSegment(newSegment, segmentDeletes, flushState.deletedDocs);+ } finally {+ if (!success) {+ if (segment != null) {+ synchronized(parent.indexWriter) {+ parent.indexWriter.deleter.refresh(segment);+ }+ }+ abort();+ }+ }+ }++ /** Get current segment name we are writing. */+ String getSegment() {+ return segment;+ }++ long bytesUsed() {+ return bytesUsed.get() + pendingDeletes.bytesUsed.get();+ }++ FieldInfos getFieldInfos() {+ return fieldInfos;+ }++ void message(String message) {+ writer.message("DWPT: " + message);+ }++ /* Initial chunks size of the shared byte[] blocks used to+ store postings data */+ final static int BYTE_BLOCK_NOT_MASK = ~BYTE_BLOCK_MASK;++ /* if you increase this, you must fix field cache impl for+ * getTerms/getTermsIndex requires <= 32768 */+ final static int MAX_TERM_LENGTH_UTF8 = BYTE_BLOCK_SIZE-2;++ /* Initial chunks size of the shared int[] blocks used to+ store postings data */+ final static int INT_BLOCK_SHIFT = 13;+ final static int INT_BLOCK_SIZE = 1 << INT_BLOCK_SHIFT;+ final static int INT_BLOCK_MASK = INT_BLOCK_SIZE - 1;++ /* Allocate another int[] from the shared pool */+ int[] getIntBlock() {+ int[] b = new int[INT_BLOCK_SIZE];+ bytesUsed.addAndGet(INT_BLOCK_SIZE*RamUsageEstimator.NUM_BYTES_INT);+ return b;+ }++ void recycleIntBlocks(int[][] blocks, int offset, int length) {+ bytesUsed.addAndGet(-(length *(INT_BLOCK_SIZE*RamUsageEstimator.NUM_BYTES_INT)));+ }++ final Allocator byteBlockAllocator = new DirectTrackingAllocator();+++ private class DirectTrackingAllocator extends Allocator {+ public DirectTrackingAllocator() {+ this(BYTE_BLOCK_SIZE);+ }++ public DirectTrackingAllocator(int blockSize) {+ super(blockSize);+ }++ public byte[] getByteBlock() {+ bytesUsed.addAndGet(blockSize);+ return new byte[blockSize];+ }+ @Override+ public void recycleByteBlocks(byte[][] blocks, int start, int end) {+ bytesUsed.addAndGet(-((end-start)* blockSize));+ for (int i = start; i < end; i++) {+ blocks[i] = null;+ }+ }++ };++++ PerDocWriteState newPerDocWriteState(int codecId) {++ assert segment != null;++ return new PerDocWriteState(infoStream, directory, segment, fieldInfos, bytesUsed, codecId);++ }+ }diff --cc lucene/src/java/org/apache/lucene/index/FieldInfo.javaindex 144e0e1e3cb,6ee2592e896..3aba2850b42--- a/lucene/src/java/org/apache/lucene/index/FieldInfo.java+++ b/lucene/src/java/org/apache/lucene/index/FieldInfo.java@@@ -22,11 -20,11 +22,13 @@@ import org.apache.lucene.index.values.T/** @lucene.experimental */public final class FieldInfo {public static final int UNASSIGNED_CODEC_ID = -1;- public String name;++ public final String name;+ public final int number;+public boolean isIndexed;- public int number;+ Type docValues;+// true if term vector for this field should be storedboolean storeTermVector;@@@ -104,21 -103,9 +108,23 @@@}if (this.omitTermFreqAndPositions != omitTermFreqAndPositions) {this.omitTermFreqAndPositions = true; // if one require omitTermFreqAndPositions at least once, it remains off for life+ this.storePayloads = false;}}+ assert !this.omitTermFreqAndPositions || !this.storePayloads;}++ void setDocValues(Type v) {+ if (docValues == null) {+ docValues = v;+ }+ }++ public boolean hasDocValues() {+ return docValues != null;+ }++ public Type getDocValues() {+ return docValues;+ }}diff --cc lucene/src/java/org/apache/lucene/index/FieldInfos.javaindex 33124c772b5,3b882f0cf28..c62649a6bf1--- a/lucene/src/java/org/apache/lucene/index/FieldInfos.java+++ b/lucene/src/java/org/apache/lucene/index/FieldInfos.java@@@ -28,9 -28,9 +28,10 @@@ import java.util.SortedMapimport java.util.TreeMap;import java.util.Map.Entry;+ import org.apache.lucene.index.SegmentCodecs; // Required for Java 1.5 javadocsimport org.apache.lucene.index.SegmentCodecs.SegmentCodecsBuilder;import org.apache.lucene.index.codecs.CodecProvider;+import org.apache.lucene.index.values.Type;import org.apache.lucene.store.Directory;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;@@@ -647,45 -608,15 +651,53 @@@ public final class FieldInfos implementboolean omitNorms = (bits & OMIT_NORMS) != 0;boolean storePayloads = (bits & STORE_PAYLOADS) != 0;boolean omitTermFreqAndPositions = (bits & OMIT_TERM_FREQ_AND_POSITIONS) != 0;++ // LUCENE-3027: past indices were able to write+ // storePayloads=true when omitTFAP is also true,+ // which is invalid. We correct that, here:+ if (omitTermFreqAndPositions) {+ storePayloads = false;+ }+- final FieldInfo addInternal = addInternal(name, fieldNumber, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions);+ Type docValuesType = null;+ if (format <= FORMAT_INDEX_VALUES) {+ final byte b = input.readByte();+ switch(b) {+ case 0:+ docValuesType = null;+ break;+ case 1:+ docValuesType = Type.INTS;+ break;+ case 2:+ docValuesType = Type.FLOAT_32;+ break;+ case 3:+ docValuesType = Type.FLOAT_64;+ break;+ case 4:+ docValuesType = Type.BYTES_FIXED_STRAIGHT;+ break;+ case 5:+ docValuesType = Type.BYTES_FIXED_DEREF;+ break;+ case 6:+ docValuesType = Type.BYTES_FIXED_SORTED;+ break;+ case 7:+ docValuesType = Type.BYTES_VAR_STRAIGHT;+ break;+ case 8:+ docValuesType = Type.BYTES_VAR_DEREF;+ break;+ case 9:+ docValuesType = Type.BYTES_VAR_SORTED;+ break;+ default:+ throw new IllegalStateException("unhandled indexValues type " + b);+ }+ }+ final FieldInfo addInternal = addInternal(name, fieldNumber, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions, docValuesType);addInternal.setCodecId(codecId);}diff --cc lucene/src/java/org/apache/lucene/index/Fields.javaindex 20e7176f4ec,d7b0bba997f..01b7f0d50ca--- a/lucene/src/java/org/apache/lucene/index/Fields.java+++ b/lucene/src/java/org/apache/lucene/index/Fields.java@@@ -33,16 -31,6 +31,6 @@@ public abstract class Fields/** Get the {@link Terms} for this field. This will return* null if the field does not exist. */public abstract Terms terms(String field) throws IOException;-+- /**- * Returns {@link DocValues} for the current field.- *- * @param field the field name- * @return the {@link DocValues} for this field or <code>null</code> if not- * applicable.- * @throws IOException- */- public abstract DocValues docValues(String field) throws IOException;-public final static Fields[] EMPTY_ARRAY = new Fields[0];}diff --cc lucene/src/java/org/apache/lucene/index/FieldsEnum.javaindex 290cd107cfb,bc5efaccc95..51ffa5f04b9--- a/lucene/src/java/org/apache/lucene/index/FieldsEnum.java+++ b/lucene/src/java/org/apache/lucene/index/FieldsEnum.java@@@ -57,17 -55,7 +57,7 @@@ public abstract class FieldsEnum* null this method should not be called. This method* will not return null. */public abstract TermsEnum terms() throws IOException;-+- /**- * Returns {@link DocValues} for the current field.- *- * @return the {@link DocValues} for this field or <code>null</code> if not- * applicable.- * @throws IOException- */- public abstract DocValues docValues() throws IOException;--public final static FieldsEnum[] EMPTY_ARRAY = new FieldsEnum[0];/** Provides zero fields */diff --cc lucene/src/java/org/apache/lucene/index/FilterIndexReader.javaindex 4dc7cfee89e,d922a48da7e..8d17f534db4--- a/lucene/src/java/org/apache/lucene/index/FilterIndexReader.java+++ b/lucene/src/java/org/apache/lucene/index/FilterIndexReader.java@@@ -19,9 -19,7 +19,7 @@@ package org.apache.lucene.indeximport org.apache.lucene.document.Document;import org.apache.lucene.document.FieldSelector;--import org.apache.lucene.index.IndexReader.ReaderContext;- import org.apache.lucene.index.values.DocValues;- import org.apache.lucene.index.values.DocValuesEnum;++import org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.store.Directory;import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;@@@ -475,4 -463,4 +463,9 @@@ public class FilterIndexReader extendssuper.removeReaderFinishedListener(listener);in.removeReaderFinishedListener(listener);}++++ @Override++ public PerDocValues perDocValues() throws IOException {++ return in.perDocValues();++ }}diff --cc lucene/src/java/org/apache/lucene/index/IndexReader.javaindex ae49b504868,9f3494c4654..984f77b7117--- a/lucene/src/java/org/apache/lucene/index/IndexReader.java+++ b/lucene/src/java/org/apache/lucene/index/IndexReader.java@@@ -23,7 -23,6 +23,8 @@@ import org.apache.lucene.search.FieldCaimport org.apache.lucene.search.Similarity;import org.apache.lucene.index.codecs.Codec;import org.apache.lucene.index.codecs.CodecProvider;++import org.apache.lucene.index.codecs.PerDocValues;+import org.apache.lucene.index.values.DocValues;import org.apache.lucene.store.*;import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.Bits;@@@ -1051,6 -1063,6 +1068,9 @@@ public abstract class IndexReader imple* using {@link ReaderUtil#gatherSubReaders} and iterate* through them yourself. */public abstract Fields fields() throws IOException;++++ // nocommit javadoc++ public abstract PerDocValues perDocValues() throws IOException;public int docFreq(Term term) throws IOException {return docFreq(term.field(), term.bytes());@@@ -1552,14 -1564,7 +1572,14 @@@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) {++ final PerDocValues perDoc = perDocValues();++ if (perDoc == null) {+ return null;+ }- return fields.docValues(field);++ return perDoc.docValues(field);+ }private volatile Fields fields;@@@ -1572,6 -1577,6 +1592,19 @@@Fields retrieveFields() {return fields;}++++ private volatile PerDocValues perDocValues;++++ /** @lucene.internal */++ void storePerDoc(PerDocValues perDocValues) {++ this.perDocValues = perDocValues;++ }++++ /** @lucene.internal */++ PerDocValues retrievePerDoc() {++ return perDocValues;++ }++/*** A struct like class that represents a hierarchical relationship betweendiff --cc lucene/src/java/org/apache/lucene/index/MultiFields.javaindex 0943aacbdaa,6abf54346bc..841349a4a33--- a/lucene/src/java/org/apache/lucene/index/MultiFields.java+++ b/lucene/src/java/org/apache/lucene/index/MultiFields.java@@@ -192,13 -187,7 +191,7 @@@ public final class MultiFields extendsreturn fields.terms(field);}}-+- /** This method may return null if the field does not exist.*/- public static DocValues getDocValues(IndexReader r, String field) throws IOException {- final Fields fields = getFields(r);- return fields == null? null: fields.docValues(field);- }-/** Returns {@link DocsEnum} for the specified field &* term. This may return null if the term does not* exist. */@@@ -282,42 -271,5 +275,6 @@@return result;}+- @Override- public DocValues docValues(String field) throws IOException {- 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));- }- }- if (docValuesIndex.isEmpty()) {- return null;- }- result = new MultiDocValues(docValuesIndex.toArray(DocValuesIndex.EMPTY_ARRAY));- docValues.put(field, result);- }- return result;- }}diff --cc lucene/src/java/org/apache/lucene/index/MultiFieldsEnum.javaindex e3faceb1f9a,06ecd3bb5db..173cd68d6c4--- a/lucene/src/java/org/apache/lucene/index/MultiFieldsEnum.java+++ b/lucene/src/java/org/apache/lucene/index/MultiFieldsEnum.java@@@ -17,12 -17,8 +17,9 @@@ package org.apache.lucene.index* limitations under the License.*/- 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.util.PriorityQueue;import org.apache.lucene.util.ReaderUtil;- import org.apache.lucene.util.ReaderUtil.Slice;import java.io.IOException;import java.util.List;@@@ -152,38 -138,5 +149,38 @@@ public final class MultiFieldsEnum extreturn fieldsA.current.compareTo(fieldsB.current) < 0;}}+- @Override- public DocValues docValues() throws IOException {- final List<MultiDocValues.DocValuesIndex> docValuesIndex = new ArrayList<MultiDocValues.DocValuesIndex>();- int docsUpto = 0;- Type type = null;- final int numEnums = enumWithSlices.length;- for (int i = 0; i < numEnums; i++) {- FieldsEnumWithSlice withSlice = enumWithSlices[i];- Slice slice = withSlice.slice;- final DocValues values = withSlice.fields.docValues();- final int start = slice.start;- final int length = slice.length;- if (values != null && currentField.equals(withSlice.current)) {- 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 == numEnums && !docValuesIndex.isEmpty()) {- docValuesIndex.add(new MultiDocValues.DocValuesIndex(- new MultiDocValues.DummyDocValues(start, type), docsUpto, start- - docsUpto));- }- }- return docValuesIndex.isEmpty() ? null : docValues.reset(docValuesIndex- .toArray(MultiDocValues.DocValuesIndex.EMPTY_ARRAY));- }++// @Override++// public DocValues docValues() throws IOException {++// final List<MultiDocValues.DocValuesIndex> docValuesIndex = new ArrayList<MultiDocValues.DocValuesIndex>();++// int docsUpto = 0;++// Type type = null;++// final int numEnums = enumWithSlices.length;++// for (int i = 0; i < numEnums; i++) {++// FieldsEnumWithSlice withSlice = enumWithSlices[i];++// Slice slice = withSlice.slice;++// final DocValues values = withSlice.fields.docValues();++// final int start = slice.start;++// final int length = slice.length;++// if (values != null && currentField.equals(withSlice.current)) {++// 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 == numEnums && !docValuesIndex.isEmpty()) {++// docValuesIndex.add(new MultiDocValues.DocValuesIndex(++// new MultiDocValues.DummyDocValues(start, type), docsUpto, start++// - docsUpto));++// }++// }++// return docValuesIndex.isEmpty() ? null : docValues.reset(docValuesIndex++// .toArray(MultiDocValues.DocValuesIndex.EMPTY_ARRAY));++// }}diff --cc lucene/src/java/org/apache/lucene/index/MultiPerDocValues.javaindex 00000000000,00000000000..bf10a43f6a0new file mode 100644--- /dev/null+++ b/lucene/src/java/org/apache/lucene/index/MultiPerDocValues.java@@@ -1,0 -1,0 +1,148 @@@++package org.apache.lucene.index;++/**++ * Licensed to the Apache Software Foundation (ASF) under one or more++ * contributor license agreements. See the NOTICE file distributed with++ * this work for additional information regarding copyright ownership.++ * The ASF licenses this file to You under the Apache License, Version 2.0++ * (the "License"); you may not use this file except in compliance with++ * the License. You may obtain a copy of the License at++ *++ * http://www.apache.org/licenses/LICENSE-2.0++ *++ * Unless required by applicable law or agreed to in writing, software++ * distributed under the License is distributed on an "AS IS" BASIS,++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.++ * See the License for the specific language governing permissions and++ * limitations under the License.++ */++import java.io.IOException;++import java.util.ArrayList;++import java.util.Collection;++import java.util.List;++import java.util.Map;++import java.util.TreeSet;++import java.util.concurrent.ConcurrentHashMap;++++import org.apache.lucene.index.codecs.PerDocValues;++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 org.apache.lucene.util.ReaderUtil;++++/**++ *++ * nocommit - javadoc++ * @experimental++ */++public class MultiPerDocValues extends PerDocValues {++ private final PerDocValues[] subs;++ private final ReaderUtil.Slice[] subSlices;++ private final Map<String, DocValues> docValues = new ConcurrentHashMap<String, DocValues>();++ private final TreeSet<String> fields;++++ public MultiPerDocValues(PerDocValues[] subs, ReaderUtil.Slice[] subSlices) {++ this.subs = subs;++ this.subSlices = subSlices;++ fields = new TreeSet<String>();++ for (PerDocValues sub : subs) {++ fields.addAll(sub.fields());++ }++ }++++ public static PerDocValues getPerDocs(IndexReader r) throws IOException {++ final IndexReader[] subs = r.getSequentialSubReaders();++ if (subs == null) {++ // already an atomic reader++ return r.perDocValues();++ } else if (subs.length == 0) {++ // no fields++ return null;++ } else if (subs.length == 1) {++ return getPerDocs(subs[0]);++ }++ PerDocValues perDocValues = r.retrievePerDoc();++ if (perDocValues == null) {++++ final List<PerDocValues> producer = new ArrayList<PerDocValues>();++ final List<ReaderUtil.Slice> slices = new ArrayList<ReaderUtil.Slice>();++++ new ReaderUtil.Gather(r) {++ @Override++ protected void add(int base, IndexReader r) throws IOException {++ final PerDocValues f = r.perDocValues();++ if (f != null) {++ producer.add(f);++ slices++ .add(new ReaderUtil.Slice(base, r.maxDoc(), producer.size() - 1));++ }++ }++ }.run();++++ if (producer.size() == 0) {++ return null;++ } else if (producer.size() == 1) {++ perDocValues = producer.get(0);++ } else {++ perDocValues = new MultiPerDocValues(++ producer.toArray(PerDocValues.EMPTY_ARRAY),++ slices.toArray(ReaderUtil.Slice.EMPTY_ARRAY));++ }++ r.storePerDoc(perDocValues);++ }++ return perDocValues;++ }++++ public DocValues docValues(String field) throws IOException {++ 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));++ }++ }++ if (docValuesIndex.isEmpty()) {++ return null;++ }++ result = new MultiDocValues(++ docValuesIndex.toArray(DocValuesIndex.EMPTY_ARRAY));++ docValues.put(field, result);++ }++ return result;++ }++++ @Override++ public void close() throws IOException {++ PerDocValues[] perDocValues = this.subs;++ for (PerDocValues values : perDocValues) {++ values.close();++ }++ }++++ @Override++ public Collection<String> fields() {++ return fields;++ }++}diff --cc lucene/src/java/org/apache/lucene/index/MultiReader.javaindex c2682e40231,c2682e40231..7a943fadcd0--- a/lucene/src/java/org/apache/lucene/index/MultiReader.java+++ b/lucene/src/java/org/apache/lucene/index/MultiReader.java@@@ -24,6 -24,6 +24,7 @@@ import java.util.concurrent.ConcurrentHimport org.apache.lucene.document.Document;import org.apache.lucene.document.FieldSelector;++import org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.util.Bits;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.ReaderUtil;@@@ -403,4 -403,4 +404,9 @@@ public class MultiReader extends IndexRsub.removeReaderFinishedListener(listener);}}++++ @Override++ public PerDocValues perDocValues() throws IOException {++ throw new UnsupportedOperationException("please use MultiPerDoc#getPerDocs, or wrap your IndexReader with SlowMultiReaderWrapper, if you really need a top level Fields");++ }}diff --cc lucene/src/java/org/apache/lucene/index/ParallelReader.javaindex 57476e2cd94,004066c4daa..4b5d78d5682--- a/lucene/src/java/org/apache/lucene/index/ParallelReader.java+++ b/lucene/src/java/org/apache/lucene/index/ParallelReader.java@@@ -21,9 -21,7 +21,8 @@@ import org.apache.lucene.document.Documimport org.apache.lucene.document.FieldSelector;import org.apache.lucene.document.FieldSelectorResult;import org.apache.lucene.document.Fieldable;- import org.apache.lucene.index.values.DocValues;++import org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.util.Bits;- import org.apache.lucene.util.Pair;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.MapBackedSet;@@@ -182,22 -180,14 +181,16 @@@ public class ParallelReader extends Indreturn TermsEnum.EMPTY;}}+- @Override- public DocValues docValues() throws IOException {- assert currentReader != null;- return MultiFields.getDocValues(currentReader, currentField);- }}// Single instance of this, per ParallelReader instanceprivate class ParallelFields extends Fields {- final HashMap<String,Pair<Terms, DocValues>> fields = new HashMap<String,Pair<Terms, DocValues>>();+ final HashMap<String,Terms> fields = new HashMap<String,Terms>();public void addField(String field, IndexReader r) throws IOException {- fields.put(field, MultiFields.getFields(r).terms(field));+ Fields multiFields = MultiFields.getFields(r);- fields.put(field, new Pair<Terms, DocValues>( multiFields.terms(field),- multiFields.docValues(field)));++ fields.put(field, multiFields.terms(field));}@Override@@@ -206,16 -196,11 +199,11 @@@}@Overridepublic Terms terms(String field) throws IOException {- return fields.get(field).cur;- }-- @Override- public DocValues docValues(String field) throws IOException {- return fields.get(field).cud;+ return fields.get(field);}}-- @Override++ @Overridepublic Bits getDeletedDocs() {return MultiFields.getDeletedDocs(readers.get(0));}@@@ -578,6 -563,6 +566,12 @@@reader.removeReaderFinishedListener(listener);}}++++ @Override++ public PerDocValues perDocValues() throws IOException {++ // TODO Auto-generated method stub++ return null;++ }}diff --cc lucene/src/java/org/apache/lucene/index/PerDocWriteState.javaindex 00000000000,00000000000..652f1b6d5a5new file mode 100644--- /dev/null+++ b/lucene/src/java/org/apache/lucene/index/PerDocWriteState.java@@@ -1,0 -1,0 +1,77 @@@++package org.apache.lucene.index;++/**++ * Licensed to the Apache Software Foundation (ASF) under one or more++ * contributor license agreements. See the NOTICE file distributed with++ * this work for additional information regarding copyright ownership.++ * The ASF licenses this file to You under the Apache License, Version 2.0++ * (the "License"); you may not use this file except in compliance with++ * the License. You may obtain a copy of the License at++ *++ * http://www.apache.org/licenses/LICENSE-2.0++ *++ * Unless required by applicable law or agreed to in writing, software++ * distributed under the License is distributed on an "AS IS" BASIS,++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.++ * See the License for the specific language governing permissions and++ * limitations under the License.++ */++import java.io.PrintStream;++import java.util.concurrent.atomic.AtomicLong;++++import org.apache.lucene.store.Directory;++++/**++ * nocommit - javadoc++ * @lucene.experimental++ */++public class PerDocWriteState {++ public final PrintStream infoStream;++ public final Directory directory;++ public final String segmentName;++ public final FieldInfos fieldInfos;++ public final AtomicLong bytesUsed;++ public final SegmentCodecs segmentCodecs;++ public final int codecId;++++ /** Expert: The fraction of terms in the "dictionary" which should be stored++ * in RAM. Smaller values use more memory, but make searching slightly++ * faster, while larger values use less memory and make searching slightly++ * slower. Searching is typically not dominated by dictionary lookup, so++ * tweaking this is rarely useful.*/++ public int termIndexInterval; // TODO: this should be private to the codec, not settable here or in IWC++++ public PerDocWriteState(PrintStream infoStream, Directory directory, String segmentName, FieldInfos fieldInfos, AtomicLong bytesUsed, int codecId) {++ this.infoStream = infoStream;++ this.directory = directory;++ this.segmentName = segmentName;++ this.fieldInfos = fieldInfos;++ this.segmentCodecs = fieldInfos.buildSegmentCodecs(false);++ this.codecId = codecId;++ this.bytesUsed = bytesUsed;++ }++++ public PerDocWriteState(SegmentWriteState state) {++ infoStream = state.infoStream;++ directory = state.directory;++ segmentCodecs = state.segmentCodecs;++ segmentName = state.segmentName;++ fieldInfos = state.fieldInfos;++ codecId = state.codecId;++ bytesUsed = new AtomicLong(0);++ }++++ public PerDocWriteState(PerDocWriteState state, int codecId) {++ this.infoStream = state.infoStream;++ this.directory = state.directory;++ this.segmentName = state.segmentName;++ this.fieldInfos = state.fieldInfos;++ this.segmentCodecs = state.segmentCodecs;++ this.codecId = codecId;++ this.bytesUsed = state.bytesUsed;++ }++++++ public String codecIdAsString() {++ return "" + codecId;++ }++}diff --cc lucene/src/java/org/apache/lucene/index/PerFieldCodecWrapper.javaindex d441aa4e5c3,4e0569858a3..d1acaf46a5e--- a/lucene/src/java/org/apache/lucene/index/PerFieldCodecWrapper.java+++ b/lucene/src/java/org/apache/lucene/index/PerFieldCodecWrapper.java@@@ -19,6 -19,6 +19,7 @@@ package org.apache.lucene.indeximport java.io.IOException;import java.util.ArrayList;++import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.Map;@@@ -28,9 -28,7 +29,11 @@@ import java.util.TreeSetimport org.apache.lucene.index.codecs.Codec;import org.apache.lucene.index.codecs.FieldsConsumer;import org.apache.lucene.index.codecs.FieldsProducer;++import org.apache.lucene.index.codecs.PerDocConsumer;++import org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.index.codecs.TermsConsumer;+import org.apache.lucene.index.codecs.docvalues.DocValuesConsumer;+import org.apache.lucene.index.values.DocValues;import org.apache.lucene.store.Directory;/**@@@ -113,7 -105,7 +110,7 @@@ final class PerFieldCodecWrapper extendboolean success = false;try {for (FieldInfo fi : fieldInfos) {- if (fi.isIndexed || fi.hasDocValues()) { // TODO this does not work for non-indexed fields- if (fi.isIndexed) { // TODO this does not work for non-indexed fields++ if (fi.isIndexed) {fields.add(fi.name);assert fi.getCodecId() != FieldInfo.UNASSIGNED_CODEC_ID;Codec codec = segmentCodecs.codecs[fi.getCodecId()];@@@ -188,13 -174,7 +180,7 @@@FieldsProducer fields = codecs.get(field);return fields == null ? null : fields.terms(field);}-+- @Override- public DocValues docValues(String field) throws IOException {- FieldsProducer fieldsProducer = codecs.get(field);- return fieldsProducer == null? null: fieldsProducer.docValues(field);- }-@Overridepublic void close() throws IOException {Iterator<FieldsProducer> it = codecs.values().iterator();@@@ -244,4 -224,4 +230,133 @@@codec.getExtensions(extensions);}}++++ @Override++ public PerDocConsumer docsConsumer(PerDocWriteState state) throws IOException {++ return new PerDocConsumers(state);++ }++++ @Override++ public PerDocValues docsProducer(SegmentReadState state) throws IOException {++ return new PerDocProducers(state.dir, state.fieldInfos, state.segmentInfo,++ state.readBufferSize, state.termsIndexDivisor);++ }++++ private final class PerDocProducers extends PerDocValues {++ private final Set<String> fields = new TreeSet<String>();++ private final Map<String, PerDocValues> codecs = new HashMap<String, PerDocValues>();++++ public PerDocProducers(Directory dir, FieldInfos fieldInfos, SegmentInfo si,++ int readBufferSize, int indexDivisor) throws IOException {++ final Map<Codec, PerDocValues> producers = new HashMap<Codec, PerDocValues>();++ boolean success = false;++ try {++ for (FieldInfo fi : fieldInfos) {++ if (fi.hasDocValues()) {++ fields.add(fi.name);++ assert fi.getCodecId() != FieldInfo.UNASSIGNED_CODEC_ID;++ Codec codec = segmentCodecs.codecs[fi.getCodecId()];++ if (!producers.containsKey(codec)) {++ producers.put(codec, codec.docsProducer(new SegmentReadState(dir,++ si, fieldInfos, readBufferSize, indexDivisor, fi.getCodecId())));++ }++ 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(PerDocValues producer : producers.values()) {++ try {++ producer.close();++ } catch (Throwable t) {++ // Suppress all exceptions here so we continue++ // to throw the original one++ }++ }++ }++ }++ }++ @Override++ public Collection<String> fields() {++ return fields;++ }++ @Override++ public DocValues docValues(String field) throws IOException {++ final PerDocValues perDocProducer = codecs.get(field);++ if (perDocProducer == null) {++ return null;++ }++ return perDocProducer.docValues(field);++ }++++ @Override++ public void close() throws IOException {++ final Iterator<PerDocValues> it = codecs.values().iterator();++ IOException err = null;++ while (it.hasNext()) {++ try {++ it.next().close();++ } catch (IOException ioe) {++ // keep first IOException we hit but keep++ // closing the rest++ if (err == null) {++ err = ioe;++ }++ }++ }++ if (err != null) {++ throw err;++ }++ }++ }++++ private final class PerDocConsumers extends PerDocConsumer {++ private final ArrayList<PerDocConsumer> consumers = new ArrayList<PerDocConsumer>();++++ public PerDocConsumers(PerDocWriteState state) throws IOException {++ assert segmentCodecs == state.segmentCodecs;++ final Codec[] codecs = segmentCodecs.codecs;++ for (int i = 0; i < codecs.length; i++) {++ consumers.add(codecs[i].docsConsumer(new PerDocWriteState(state, i)));++ }++ }++++ @Override++ public void close() throws IOException {++ Iterator<PerDocConsumer> it = consumers.iterator();++ IOException err = null;++ while (it.hasNext()) {++ try {++ PerDocConsumer next = it.next();++ if (next != null) {++ next.close();++ }++ } catch (IOException ioe) {++ // keep first IOException we hit but keep++ // closing the rest++ if (err == null) {++ err = ioe;++ }++ }++ }++ if (err != null) {++ throw err;++ }++ }++++ @Override++ public DocValuesConsumer addValuesField(FieldInfo field) throws IOException {++ assert field.getCodecId() != FieldInfo.UNASSIGNED_CODEC_ID;++ final PerDocConsumer perDoc = consumers.get(field.getCodecId());++ if (perDoc == null) {++ return null;++ }++ return perDoc.addValuesField(field);++ }++++ }}diff --cc lucene/src/java/org/apache/lucene/index/SegmentMerger.javaindex 2303207149c,67e279b3c15..46c050e3588--- a/lucene/src/java/org/apache/lucene/index/SegmentMerger.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentMerger.java@@@ -31,6 -30,6 +30,8 @@@ import org.apache.lucene.index.codecs.Cimport org.apache.lucene.index.codecs.CodecProvider;import org.apache.lucene.index.codecs.FieldsConsumer;import org.apache.lucene.index.codecs.MergeState;++import org.apache.lucene.index.codecs.PerDocConsumer;++import org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.store.Directory;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;@@@ -65,7 -64,8 +66,7 @@@ final class SegmentMerger/** Maximum number of contiguous documents to bulk-copywhen merging stored fields */private final static int MAX_RAW_MERGE_DOCS = 4192;-+- private final CodecProvider codecs;private Codec codec;private SegmentWriteState segmentWriteState;@@@ -473,9 -473,9 +473,16 @@@int docBase = 0;final List<Fields> fields = new ArrayList<Fields>();++final List<ReaderUtil.Slice> slices = new ArrayList<ReaderUtil.Slice>();final List<Bits> bits = new ArrayList<Bits>();final List<Integer> bitsStarts = new ArrayList<Integer>();++++ // TODO: move this into its own method - this merges currently only docvalues++ final List<PerDocValues> perDocProducers = new ArrayList<PerDocValues>();++ final List<ReaderUtil.Slice> perDocSlices = new ArrayList<ReaderUtil.Slice>();++ final List<Bits> perDocBits = new ArrayList<Bits>();++ final List<Integer> perDocBitsStarts = new ArrayList<Integer>();for(IndexReader r : readers) {final Fields f = r.fields();@@@ -486,10 -486,10 +493,18 @@@bits.add(r.getDeletedDocs());bitsStarts.add(docBase);}++ final PerDocValues producer = r.perDocValues();++ if (producer != null) {++ perDocSlices.add(new ReaderUtil.Slice(docBase, maxDoc, fields.size()));++ perDocProducers.add(producer);++ perDocBits.add(r.getDeletedDocs());++ perDocBitsStarts.add(docBase);++ }docBase += maxDoc;}bitsStarts.add(docBase);++ perDocBitsStarts.add(docBase);// we may gather more readers than mergeState.readerCountmergeState = new MergeState();@@@ -556,6 -556,6 +571,21 @@@} finally {consumer.close();}++ if (!perDocSlices.isEmpty()) {++ mergeState.multiDeletedDocs = new MultiBits(perDocBits, perDocBitsStarts);++ final PerDocConsumer docsConsumer = codec++ .docsConsumer(new PerDocWriteState(segmentWriteState));++ try {++ docsConsumer.merge(++ mergeState,++ new MultiPerDocValues(perDocProducers++ .toArray(PerDocValues.EMPTY_ARRAY), perDocSlices++ .toArray(ReaderUtil.Slice.EMPTY_ARRAY)));++ } finally {++ docsConsumer.close();++ }++ }++}private MergeState mergeState;diff --cc lucene/src/java/org/apache/lucene/index/SegmentReader.javaindex 90607888af6,aa97da86d47..0aa94487adf--- a/lucene/src/java/org/apache/lucene/index/SegmentReader.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentReader.java@@@ -28,20 -28,14 +28,16 @@@ import java.util.Setimport java.util.concurrent.atomic.AtomicInteger;import org.apache.lucene.document.Document;- import org.apache.lucene.document.Field;import org.apache.lucene.document.FieldSelector;import org.apache.lucene.index.codecs.FieldsProducer;++import org.apache.lucene.index.codecs.PerDocValues;import org.apache.lucene.store.BufferedIndexInput;import org.apache.lucene.store.Directory;import org.apache.lucene.store.IndexInput;import org.apache.lucene.store.IndexOutput;import org.apache.lucene.util.BitVector;import org.apache.lucene.util.Bits;- import org.apache.lucene.index.values.Bytes;- import org.apache.lucene.index.values.Ints;+import org.apache.lucene.index.values.DocValues;- import org.apache.lucene.index.values.Floats;- import org.apache.lucene.index.values.Type;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.CloseableThreadLocal;@@@ -91,6 -88,6 +90,7 @@@ public class SegmentReader extends Indefinal FieldInfos fieldInfos;final FieldsProducer fields;++ final PerDocValues perDocProducer;final Directory dir;final Directory cfsDir;@@@ -130,8 -127,9 +130,10 @@@this.termsIndexDivisor = termsIndexDivisor;// Ask codec for its Fields-- fields = segmentCodecs.codec().fieldsProducer(new SegmentReadState(cfsDir, si, fieldInfos, readBufferSize, termsIndexDivisor));++ final SegmentReadState segmentReadState = new SegmentReadState(cfsDir, si, fieldInfos, readBufferSize, termsIndexDivisor);++ fields = segmentCodecs.codec().fieldsProducer(segmentReadState);assert fields != null;-++ perDocProducer = segmentCodecs.codec().docsProducer(segmentReadState);success = true;} finally {if (!success) {@@@ -169,6 -166,7 +171,10 @@@if (fields != null) {fields.close();}++++ if (perDocProducer != null) {++ perDocProducer.close();++ }if (termVectorsReaderOrig != null) {termVectorsReaderOrig.close();@@@ -1208,9 -1204,4 +1215,14 @@@// longer used (all SegmentReaders sharing it have been// closed).}++ @Override+ public DocValues docValues(String field) throws IOException {- return core.fields.docValues(field);++ return core.perDocProducer.docValues(field);++ }++++ @Override++ public PerDocValues perDocValues() throws IOException {++ return core.perDocProducer;+ }}diff --cc lucene/src/java/org/apache/lucene/index/SegmentWriteState.javaindex 1b273f56cad,e44462cc72d..c29add9bd93--- a/lucene/src/java/org/apache/lucene/index/SegmentWriteState.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentWriteState.java@@@ -56,7 -54,7 +55,7 @@@ public class SegmentWriteStatepublic int termIndexInterval; // TODO: this should be private to the codec, not settable here or in IWCpublic SegmentWriteState(PrintStream infoStream, Directory directory, String segmentName, FieldInfos fieldInfos,- int numDocs, int termIndexInterval, SegmentCodecs segmentCodecs, BufferedDeletes segDeletes, AtomicLong bytesUsed) {- int numDocs, int termIndexInterval, SegmentCodecs segmentCodecs, BufferedDeletes segDeletes) {++ int numDocs, int termIndexInterval, SegmentCodecs segmentCodecs, BufferedDeletes segDeletes) {this.infoStream = infoStream;this.segDeletes = segDeletes;this.directory = directory;@@@ -65,8 -63,7 +64,7 @@@this.numDocs = numDocs;this.termIndexInterval = termIndexInterval;this.segmentCodecs = segmentCodecs;- codecId = "";+ codecId = -1;- this.bytesUsed = bytesUsed;}/**@@@ -82,10 -79,5 +80,9 @@@segmentCodecs = state.segmentCodecs;this.codecId = codecId;segDeletes = state.segDeletes;- bytesUsed = state.bytesUsed;}++ public String codecIdAsString() {+ return "" + codecId;+ }}diff --cc lucene/src/java/org/apache/lucene/index/SlowMultiReaderWrapper.javaindex 78c834f8008,78c834f8008..82e976098ff--- a/lucene/src/java/org/apache/lucene/index/SlowMultiReaderWrapper.java+++ b/lucene/src/java/org/apache/lucene/index/SlowMultiReaderWrapper.java@@@ -26,6 -26,6 +26,7 @@@ import org.apache.lucene.util.ReaderUtiimport org.apache.lucene.index.DirectoryReader; // javadocimport org.apache.lucene.index.MultiReader; // javadoc++import org.apache.lucene.index.codecs.PerDocValues;/*** This class forces a composite reader (eg a {@link@@@ -64,6 -64,6 +65,11 @@@ public final class SlowMultiReaderWrappreturn MultiFields.getFields(in);}++ @Override++ public PerDocValues perDocValues() throws IOException {++ return MultiPerDocValues.getPerDocs(in);++ }++@Overridepublic Bits getDeletedDocs() {return MultiFields.getDeletedDocs(in);diff --cc lucene/src/java/org/apache/lucene/index/codecs/Codec.javaindex 720ec737723,cb4a9f3bd87..464f736dc17--- a/lucene/src/java/org/apache/lucene/index/codecs/Codec.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/Codec.java@@@ -20,6 -20,6 +20,7 @@@ package org.apache.lucene.index.codecsimport java.io.IOException;import java.util.Set;++import org.apache.lucene.index.PerDocWriteState;import org.apache.lucene.index.SegmentInfo;import org.apache.lucene.index.SegmentWriteState;import org.apache.lucene.index.SegmentReadState;@@@ -50,6 -50,6 +51,14 @@@ public abstract class Codec* returns, it must hold open any files it will need to* use; else, those files may be deleted. */public abstract FieldsProducer fieldsProducer(SegmentReadState state) throws IOException;++++ public PerDocConsumer docsConsumer(PerDocWriteState state) throws IOException {++ return null;++ }++++ public PerDocValues docsProducer(SegmentReadState state) throws IOException {++ return null;++ }/*** Gathers files associated with this segmentdiff --cc lucene/src/java/org/apache/lucene/index/codecs/FieldsConsumer.javaindex 33fd19d732c,8389df02600..c042b7c99d6--- a/lucene/src/java/org/apache/lucene/index/codecs/FieldsConsumer.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/FieldsConsumer.java@@@ -20,9 -20,6 +20,7 @@@ package org.apache.lucene.index.codecsimport org.apache.lucene.index.FieldInfo;import org.apache.lucene.index.Fields;import org.apache.lucene.index.FieldsEnum;+import org.apache.lucene.index.TermsEnum;- import org.apache.lucene.index.codecs.docvalues.DocValuesConsumer;- import org.apache.lucene.index.values.DocValues;import java.io.IOException;import java.io.Closeable;@@@ -38,12 -35,7 +36,7 @@@ 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;@@@ -53,25 -45,8 +46,13 @@@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();- 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/codecs/FieldsProducer.javaindex a4ce963828b,a378680328e..d170699d72b--- a/lucene/src/java/org/apache/lucene/index/codecs/FieldsProducer.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/FieldsProducer.java@@@ -36,33 -33,4 +36,28 @@@ import org.apache.lucene.index.values.Dpublic abstract class FieldsProducer extends Fields implements Closeable {public abstract void close() throws IOException;public abstract void loadTermsIndex(int indexDivisor) throws IOException;+- @Override- public DocValues docValues(String field) throws IOException {- return null;- }-+ public static final FieldsProducer EMPTY = new FieldsProducer() {++ @Override+ public Terms terms(String field) throws IOException {+ return null;+ }++ @Override+ public FieldsEnum iterator() throws IOException {+ return FieldsEnum.EMPTY;+ }++ @Override+ public void loadTermsIndex(int indexDivisor) throws IOException {++ }++ @Override+ public void close() throws IOException {++ }+ };+}diff --cc lucene/src/java/org/apache/lucene/index/codecs/PerDocConsumer.javaindex 00000000000,00000000000..81c11af1a35new file mode 100644--- /dev/null+++ b/lucene/src/java/org/apache/lucene/index/codecs/PerDocConsumer.java@@@ -1,0 -1,0 +1,59 @@@++package org.apache.lucene.index.codecs;++/**++ * 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 org.apache.lucene.index.FieldInfo;++import org.apache.lucene.index.codecs.docvalues.DocValuesConsumer;++import org.apache.lucene.index.values.DocValues;++++/**++ * nocommit - javadoc++ * @experimental++ *++ */++public abstract class PerDocConsumer implements Closeable{++ /** Adds a new DocValuesField */++ public abstract DocValuesConsumer addValuesField(FieldInfo field)++ throws IOException;++++ public void merge(MergeState mergeState, PerDocValues producer)++ throws IOException {++ Iterable<String> fields = producer.fields();++ for (String field : fields) {++ mergeState.fieldInfo = mergeState.fieldInfos.fieldInfo(field);++ assert mergeState.fieldInfo != null : "FieldInfo for field is null: "++ + field;++ if (mergeState.fieldInfo.hasDocValues()) {++ final DocValues docValues = producer.docValues(field);++ 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/codecs/PerDocValues.javaindex c8bc1641f44,00000000000..cfeda8f40c9mode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/codecs/PerDocValues.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/PerDocValues.java@@@ -1,27 -1,0 +1,44 @@@- package org.apache.lucene.index;-++package org.apache.lucene.index.codecs;+/**+ * 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.Collection;++++import org.apache.lucene.index.values.DocValues;++++/**++ *++ * nocommit javadoc++ * @experimental++ */++public abstract class PerDocValues implements Closeable {++ /**++ * Returns {@link DocValues} for the current field.++ *++ * @param field++ * the field name++ * @return the {@link DocValues} for this field or <code>null</code> if not++ * applicable.++ * @throws IOException++ */++ public abstract DocValues docValues(String field) throws IOException;++++ public static final PerDocValues[] EMPTY_ARRAY = new PerDocValues[0];+- abstract class DocFieldConsumerPerThread {- abstract void startDocument() throws IOException;- abstract DocumentsWriter.DocWriter finishDocument() throws IOException;- abstract DocFieldConsumerPerField addField(FieldInfo fi);- abstract void abort();++ public abstract Collection<String> fields();+}diff --cc lucene/src/java/org/apache/lucene/index/codecs/VariableGapTermsIndexReader.javaindex 6980335aeea,77dc6eda6de..5f8d3aa2db6--- a/lucene/src/java/org/apache/lucene/index/codecs/VariableGapTermsIndexReader.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/VariableGapTermsIndexReader.java@@@ -52,11 -56,13 +56,12 @@@ public class VariableGapTermsIndexReade// start of the field info dataprotected long dirOffset;+ final String segment;-- public VariableGapTermsIndexReader(Directory dir, FieldInfos fieldInfos, String segment, int indexDivisor, String codecId)+ public VariableGapTermsIndexReader(Directory dir, FieldInfos fieldInfos, String segment, int indexDivisor, int codecId)throws IOException {- in = dir.openInput(IndexFileNames.segmentFileName(segment, codecId, VariableGapTermsIndexWriter.TERMS_INDEX_EXTENSION));+ in = dir.openInput(IndexFileNames.segmentFileName(segment, ""+codecId, VariableGapTermsIndexWriter.TERMS_INDEX_EXTENSION));-+ this.segment = segment;boolean success = false;try {@@@ -153,15 -159,15 +158,11 @@@private final class FieldIndexData {-- private final FieldInfo fieldInfo;private final long indexStart;--// Set only if terms index is loaded:private volatile FST<Long> fst;public FieldIndexData(FieldInfo fieldInfo, long indexStart) throws IOException {---- this.fieldInfo = fieldInfo;this.indexStart = indexStart;if (indexDivisor > 0) {diff --cc lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.javaindex 335b0d849f4,00000000000..60ddccaa52dmode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesCodec.java@@@ -1,326 -1,0 +1,151 @@@+package org.apache.lucene.index.codecs.docvalues;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import java.io.IOException;+import java.util.Comparator;- import java.util.Iterator;+import java.util.Set;- import java.util.Map.Entry;++import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.FieldInfos;- import org.apache.lucene.index.FieldsEnum;+import org.apache.lucene.index.IndexFileNames;++import org.apache.lucene.index.PerDocWriteState;+import org.apache.lucene.index.SegmentInfo;+import org.apache.lucene.index.SegmentReadState;+import org.apache.lucene.index.SegmentWriteState;- import org.apache.lucene.index.Terms;- import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.index.codecs.Codec;+import org.apache.lucene.index.codecs.FieldsConsumer;+import org.apache.lucene.index.codecs.FieldsProducer;- import org.apache.lucene.index.codecs.TermsConsumer;- import org.apache.lucene.index.values.DocValues;++import org.apache.lucene.index.codecs.PerDocConsumer;++import org.apache.lucene.index.codecs.PerDocValues;+import org.apache.lucene.index.values.Writer;+import org.apache.lucene.store.Directory;- import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;++/**+ * A codec that adds DocValues support to a given codec transparently.+ * @lucene.experimental+ */+public class DocValuesCodec extends Codec {+ private final Codec other;+ private final Comparator<BytesRef> comparator;++ public DocValuesCodec(Codec other, Comparator<BytesRef> comparator) {+ this.name = other.name;+ this.other = other;+ this.comparator = comparator;+ }++ public DocValuesCodec(Codec other) {+ this(other, null);+ }++ @Override- public FieldsConsumer fieldsConsumer(SegmentWriteState state)++ public PerDocConsumer docsConsumer(final PerDocWriteState state)+ throws IOException {- final WrappingFieldsConsumer consumer;- consumer = new WrappingFieldsConsumer(other, comparator, state);- // nocommit this is a hack and only necessary since- // we want to initialized the wrapped- // fieldsConsumer lazily with a SegmentWriteState created after the docvalue- // ones is. We should fix this in DocumentWriter I guess. See- // DocFieldProcessor too!- return consumer;- }-- private static class WrappingFieldsConsumer extends FieldsConsumer {- private final SegmentWriteState state;- private FieldsConsumer wrappedConsumer;- private final Codec other;- private final Comparator<BytesRef> comparator;++ return new PerDocConsumer() {+- public WrappingFieldsConsumer(Codec other, Comparator<BytesRef> comparator, SegmentWriteState state) {- this.other = other;- this.comparator = comparator;- this.state = state;- }++ @Override++ public void close() throws IOException {++ }+- @Override- public void close() throws IOException {- synchronized (this) {- if (wrappedConsumer != null) {- wrappedConsumer.close();- }++ @Override++ public DocValuesConsumer addValuesField(FieldInfo field)++ throws IOException {++ final DocValuesConsumer consumer = Writer.create(field.getDocValues(),++ docValuesId(state.segmentName, state.codecId, field.number),++ // TODO can we have a compound file per segment and codec for++ // docvalues?++ state.directory, comparator, state.bytesUsed);++ return consumer;+ }-- }++ };++ }+- @Override- public synchronized DocValuesConsumer addValuesField(FieldInfo field)- throws IOException {- final DocValuesConsumer consumer = Writer.create(field.getDocValues(), docValuesId(state.segmentName, state.codecId, field.number),- // TODO can we have a compound file per segment and codec for- // docvalues?- state.directory, comparator, state.bytesUsed);- return consumer;++ @Override++ public PerDocValues docsProducer(SegmentReadState state) throws IOException {++ try {++ return new DocValuesProducerBase(state.segmentInfo, state.dir, state.fieldInfos, state.codecId);++ }catch (IOException e) {++ return new DocValuesProducerBase(state.segmentInfo, state.dir, state.fieldInfos, state.codecId);+ }++ }+- @Override- public TermsConsumer addField(FieldInfo field) throws IOException {- synchronized (this) {- if (wrappedConsumer == null)- wrappedConsumer = other.fieldsConsumer(state);- }- return wrappedConsumer.addField(field);- }++ @Override++ public FieldsConsumer fieldsConsumer(SegmentWriteState state)++ throws IOException {++ return other.fieldsConsumer(state);+ }++ @Override+ public FieldsProducer fieldsProducer(SegmentReadState state)+ throws IOException {- final FieldInfos fieldInfos = state.fieldInfos;- boolean indexed = false;- boolean docValues = false;- for (FieldInfo fieldInfo : fieldInfos) {- if (fieldInfo.getCodecId() == state.codecId) {- indexed |= fieldInfo.isIndexed;- docValues |= fieldInfo.hasDocValues();- if (indexed && docValues)- break;- }- }- final FieldsProducer indexedProducer = indexed ? other.fieldsProducer(state) : FieldsProducer.EMPTY;- if (docValues) {- return new WrappingFielsdProducer(state, indexedProducer);- } else {- return FieldsProducer.EMPTY;- }++ return other.fieldsProducer(state);+ }++ static String docValuesId(String segmentsName, int codecID, int fieldId) {+ return segmentsName + "_" + codecID + "-" + fieldId;+ }++ @Override+ public void files(Directory dir, SegmentInfo segmentInfo, int codecId,+ Set<String> files) throws IOException {+ FieldInfos fieldInfos = segmentInfo.getFieldInfos();+ boolean indexed = false;+ for (FieldInfo fieldInfo : fieldInfos) {+ if (fieldInfo.getCodecId() == codecId) {+ indexed |= fieldInfo.isIndexed;+ if (fieldInfo.hasDocValues()) {+ String filename = docValuesId(segmentInfo.name, codecId, fieldInfo.number);+ switch (fieldInfo.getDocValues()) {+ case BYTES_FIXED_DEREF:+ case BYTES_VAR_DEREF:+ case BYTES_VAR_SORTED:+ case BYTES_FIXED_SORTED:+ case BYTES_VAR_STRAIGHT:+ files.add(IndexFileNames.segmentFileName(filename, "",+ Writer.INDEX_EXTENSION));+ assert dir.fileExists(IndexFileNames.segmentFileName(filename, "",+ Writer.INDEX_EXTENSION));+ case BYTES_FIXED_STRAIGHT:+ case FLOAT_32:+ case FLOAT_64:+ case INTS:+ files.add(IndexFileNames.segmentFileName(filename, "",+ Writer.DATA_EXTENSION));+ assert dir.fileExists(IndexFileNames.segmentFileName(filename, "",+ Writer.DATA_EXTENSION));+ break;+ default:+ assert false;+ }+ }++ }+ }+ if (indexed) {+ other.files(dir, segmentInfo, codecId, files);+ }+ }++ @Override+ public void getExtensions(Set<String> extensions) {+ other.getExtensions(extensions);+ extensions.add(Writer.DATA_EXTENSION);+ extensions.add(Writer.INDEX_EXTENSION);+ }-- static class WrappingFielsdProducer extends DocValuesProducerBase {-- private final FieldsProducer other;-- WrappingFielsdProducer(SegmentReadState state, FieldsProducer other)- throws IOException {- super(state.segmentInfo, state.dir, state.fieldInfos, state.codecId);- this.other = other;- }-- @Override- public void close() throws IOException {- try {- other.close();- } finally {- super.close();- }- }-- @Override- public void loadTermsIndex(int indexDivisor) throws IOException {- other.loadTermsIndex(indexDivisor);- }-- @Override- public FieldsEnum iterator() throws IOException {- return new WrappingFieldsEnum(other.iterator(), docValues.entrySet()- .iterator());- }-- @Override- public Terms terms(String field) throws IOException {- return other.terms(field);- }- }-- static abstract class NameValue<V> {- String name;- V value;-- NameValue<?> smaller(NameValue<?> other) throws IOException {- if (other.name == null) {- if (this.name == null) {- return null;- }- return this;- } else if (this.name == null) {- return other;- }- final int res = this.name.compareTo(other.name);- if (res < 0)- return this;- if (res == 0)- other.name = this.name;- return other;- }-- abstract NameValue<V> next() throws IOException;- }-- static class FieldsEnumNameValue extends NameValue<FieldsEnum> {- @Override- NameValue<FieldsEnum> next() throws IOException {- name = value.next();- return this;- }- }-- static class DocValueNameValue extends NameValue<DocValues> {- Iterator<Entry<String, DocValues>> iter;-- @Override- NameValue<DocValues> next() {- if (iter.hasNext()) {- Entry<String, DocValues> next = iter.next();- value = next.getValue();- name = next.getKey();- } else {- name = null;- }- return this;- }- }-- static class WrappingFieldsEnum extends FieldsEnum {- private final DocValueNameValue docValues = new DocValueNameValue();- private final NameValue<FieldsEnum> fieldsEnum = new FieldsEnumNameValue();- private NameValue<?> coordinator;-- @Override- public AttributeSource attributes() {- return fieldsEnum.value.attributes();- }-- public WrappingFieldsEnum(FieldsEnum wrapped,- Iterator<Entry<String, DocValues>> docValues) {- this.docValues.iter = docValues;- this.fieldsEnum.value = wrapped;- coordinator = null;- }-- @Override- public DocValues docValues() throws IOException {- if (docValues.name == coordinator.name)- return docValues.value;- return null;- }-- @Override- public String next() throws IOException {- if (coordinator == null) {- coordinator = fieldsEnum.next().smaller(docValues.next());- } else {- String current = coordinator.name;- if (current == docValues.name) {- docValues.next();- }- if (current == fieldsEnum.name) {- fieldsEnum.next();- }- coordinator = docValues.smaller(fieldsEnum);-- }- return coordinator == null ? null : coordinator.name;- }-- @Override- public TermsEnum terms() throws IOException {- if (fieldsEnum.name == coordinator.name) {- return fieldsEnum.value.terms();- }- return null;- }- }-+}diff --cc lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.javaindex 619027b4248,00000000000..bb6c8556a3amode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/docvalues/DocValuesProducerBase.java@@@ -1,148 -1,0 +1,153 @@@+package org.apache.lucene.index.codecs.docvalues;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import java.io.IOException;+import java.util.Collection;+import java.util.TreeMap;++import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.FieldInfos;+import org.apache.lucene.index.SegmentInfo;- import org.apache.lucene.index.codecs.FieldsProducer;++import org.apache.lucene.index.codecs.PerDocValues;+import org.apache.lucene.index.values.Bytes;+import org.apache.lucene.index.values.DocValues;+import org.apache.lucene.index.values.Floats;+import org.apache.lucene.index.values.Ints;+import org.apache.lucene.index.values.Type;+import org.apache.lucene.store.Directory;++/**+ * Abstract base class for FieldsProducer implementations supporting+ * {@link DocValues}.+ *+ * @lucene.experimental+ */- public abstract class DocValuesProducerBase extends FieldsProducer {++public class DocValuesProducerBase extends PerDocValues {++ protected final TreeMap<String, DocValues> docValues = new TreeMap<String, DocValues>();++ /**+ * Creates a new {@link DocValuesProducerBase} instance and loads all+ * {@link DocValues} instances for this segment and codec.+ *+ * @param si+ * the segment info to load the {@link DocValues} for.+ * @param dir+ * the directory to load the {@link DocValues} from.+ * @param fieldInfo+ * the {@link FieldInfos}+ * @param codecId+ * the codec ID+ * @throws IOException+ * if an {@link IOException} occurs+ */+ protected DocValuesProducerBase(SegmentInfo si, Directory dir,+ FieldInfos fieldInfo, int codecId) throws IOException {+ load(fieldInfo, si.name, si.docCount, dir, codecId);+ }++ /**+ * Returns a {@link DocValues} instance for the given field name or+ * <code>null</code> if this field has no {@link DocValues}.+ */+ @Override+ public DocValues docValues(String field) throws IOException {+ return docValues.get(field);+ }++ // Only opens files... doesn't actually load any values+ protected void load(FieldInfos fieldInfos, String segment, int docCount,+ Directory dir, int codecId) throws IOException {+ for (FieldInfo fieldInfo : fieldInfos) {+ if (codecId == fieldInfo.getCodecId() && fieldInfo.hasDocValues()) {+ final String field = fieldInfo.name;+ // TODO can we have a compound file per segment and codec for docvalues?+ final String id = DocValuesCodec.docValuesId(segment, codecId, fieldInfo.number);+ docValues.put(field, loadDocValues(docCount, dir, id, fieldInfo+ .getDocValues()));+ }+ }+ }+++ /**+ * Loads a {@link DocValues} instance depending on the given {@link Type}.+ * Codecs that use different implementations for a certain {@link Type} can+ * simply override this method and return their custom implementations.+ *+ * @param docCount+ * number of documents in the segment+ * @param dir+ * the {@link Directory} to load the {@link DocValues} from+ * @param id+ * the unique file ID within the segment+ * @param type+ * the type to load+ * @return a {@link DocValues} instance for the given type+ * @throws IOException+ * if an {@link IOException} occurs+ * @throws IllegalArgumentException+ * if the given {@link Type} is not supported+ */+ protected DocValues loadDocValues(int docCount, Directory dir, String id,+ Type type) throws IOException {+ switch (type) {+ case INTS:+ return Ints.getValues(dir, id, false);+ case FLOAT_32:+ return Floats.getValues(dir, id, docCount);+ case FLOAT_64:+ return Floats.getValues(dir, id, docCount);+ case BYTES_FIXED_STRAIGHT:+ return Bytes.getValues(dir, id, Bytes.Mode.STRAIGHT, true, docCount);+ case BYTES_FIXED_DEREF:+ return Bytes.getValues(dir, id, Bytes.Mode.DEREF, true, docCount);+ case BYTES_FIXED_SORTED:+ return Bytes.getValues(dir, id, Bytes.Mode.SORTED, true, docCount);+ case BYTES_VAR_STRAIGHT:+ return Bytes.getValues(dir, id, Bytes.Mode.STRAIGHT, false, docCount);+ case BYTES_VAR_DEREF:+ return Bytes.getValues(dir, id, Bytes.Mode.DEREF, false, docCount);+ case BYTES_VAR_SORTED:+ return Bytes.getValues(dir, id, Bytes.Mode.SORTED, false, docCount);+ default:+ throw new IllegalStateException("unrecognized index values mode " + type);+ }+ }++ @Override+ public void close() throws IOException {+ Collection<DocValues> values = docValues.values();+ IOException ex = null;+ for (DocValues docValues : values) {+ try {+ docValues.close();+ } catch (IOException e) {+ ex = e;+ }+ }+ if (ex != null) {+ throw ex;+ }+ }++++ @Override++ public Collection<String> fields() {++ return docValues.keySet();++ }+}diff --cc lucene/src/java/org/apache/lucene/index/codecs/sep/SepPostingsWriterImpl.javaindex e1485eb879f,989800b1b81..f14658cba45--- a/lucene/src/java/org/apache/lucene/index/codecs/sep/SepPostingsWriterImpl.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/sep/SepPostingsWriterImpl.java@@@ -102,9 -103,14 +103,15 @@@ public final class SepPostingsWriterImpprivate final RAMOutputStream indexBytesWriter = new RAMOutputStream();public SepPostingsWriterImpl(SegmentWriteState state, IntStreamFactory factory) throws IOException {+ this(state, factory, DEFAULT_SKIP_INTERVAL);+ }++ public SepPostingsWriterImpl(SegmentWriteState state, IntStreamFactory factory, int skipInterval) throws IOException {super();+ final String codecIdAsString = state.codecIdAsString();+ this.skipInterval = skipInterval;+ this.skipMinimum = skipInterval; /* set to the same for now */- final String docFileName = IndexFileNames.segmentFileName(state.segmentName, state.codecId, DOC_EXTENSION);+ final String docFileName = IndexFileNames.segmentFileName(state.segmentName, codecIdAsString, DOC_EXTENSION);docOut = factory.createOutput(state.directory, docFileName);docIndex = docOut.index();diff --cc lucene/src/java/org/apache/lucene/index/codecs/standard/StandardPostingsWriter.javaindex 662369a1e29,dbef01873b5..a0d1a8d076e--- a/lucene/src/java/org/apache/lucene/index/codecs/standard/StandardPostingsWriter.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/standard/StandardPostingsWriter.java@@@ -82,9 -83,14 +83,14 @@@ public final class StandardPostingsWritprivate RAMOutputStream bytesWriter = new RAMOutputStream();public StandardPostingsWriter(SegmentWriteState state) throws IOException {+ this(state, DEFAULT_SKIP_INTERVAL);+ }+ public StandardPostingsWriter(SegmentWriteState state, int skipInterval) throws IOException {super();+ this.skipInterval = skipInterval;+ this.skipMinimum = skipInterval; /* set to the same for now *///this.segment = state.segmentName;- String fileName = IndexFileNames.segmentFileName(state.segmentName, state.codecId, StandardCodec.FREQ_EXTENSION);+ String fileName = IndexFileNames.segmentFileName(state.segmentName, state.codecIdAsString(), StandardCodec.FREQ_EXTENSION);freqOut = state.directory.createOutput(fileName);if (state.fieldInfos.hasProx()) {diff --cc lucene/src/test/org/apache/lucene/index/TestDocTermOrds.javaindex 00000000000,6c50f3f4272..fa6c25f7714mode 000000,100644..100644--- a/lucene/src/test/org/apache/lucene/index/TestDocTermOrds.java+++ b/lucene/src/test/org/apache/lucene/index/TestDocTermOrds.java@@@ -1,0 -1,517 +1,517 @@@+ package org.apache.lucene.index;++ /**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++ import java.io.IOException;+ import java.util.Arrays;+ import java.util.List;+ import java.util.ArrayList;+ import java.util.HashSet;+ import java.util.Set;++ import org.apache.lucene.analysis.MockAnalyzer;+ import org.apache.lucene.document.Document;+ import org.apache.lucene.document.Field;+ import org.apache.lucene.document.NumericField;+ import org.apache.lucene.index.DocTermOrds.TermOrdsIterator;+ import org.apache.lucene.index.codecs.BlockTermsReader;+ import org.apache.lucene.index.codecs.BlockTermsWriter;+ import org.apache.lucene.index.codecs.Codec;+ import org.apache.lucene.index.codecs.CoreCodecProvider;+ import org.apache.lucene.index.codecs.FieldsConsumer;+ import org.apache.lucene.index.codecs.FieldsProducer;+ import org.apache.lucene.index.codecs.FixedGapTermsIndexReader;+ import org.apache.lucene.index.codecs.FixedGapTermsIndexWriter;+ import org.apache.lucene.index.codecs.PostingsReaderBase;+ import org.apache.lucene.index.codecs.PostingsWriterBase;+ import org.apache.lucene.index.codecs.TermsIndexReaderBase;+ import org.apache.lucene.index.codecs.TermsIndexWriterBase;+ import org.apache.lucene.index.codecs.standard.StandardPostingsReader;+ import org.apache.lucene.index.codecs.standard.StandardPostingsWriter;+ import org.apache.lucene.search.FieldCache;+ import org.apache.lucene.store.Directory;+ import org.apache.lucene.store.MockDirectoryWrapper;+ import org.apache.lucene.util.BytesRef;+ import org.apache.lucene.util.LuceneTestCase;+ import org.apache.lucene.util._TestUtil;++ // TODO:+ // - test w/ del docs+ // - test prefix+ // - test w/ cutoff+ // - crank docs way up so we get some merging sometimes++ public class TestDocTermOrds extends LuceneTestCase {++ public void testSimple() throws Exception {+ Directory dir = newDirectory();+ final RandomIndexWriter w = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));+ Document doc = new Document();+ Field field = newField("field", "", Field.Index.ANALYZED);+ doc.add(field);+ field.setValue("a b c");+ w.addDocument(doc);++ field.setValue("d e f");+ w.addDocument(doc);++ field.setValue("a f");+ w.addDocument(doc);++ final IndexReader r = w.getReader();+ w.close();++ final DocTermOrds dto = new DocTermOrds(r, "field");++ TermOrdsIterator iter = dto.lookup(0, null);+ final int[] buffer = new int[5];+ assertEquals(3, iter.read(buffer));+ assertEquals(0, buffer[0]);+ assertEquals(1, buffer[1]);+ assertEquals(2, buffer[2]);++ iter = dto.lookup(1, iter);+ assertEquals(3, iter.read(buffer));+ assertEquals(3, buffer[0]);+ assertEquals(4, buffer[1]);+ assertEquals(5, buffer[2]);++ iter = dto.lookup(2, iter);+ assertEquals(2, iter.read(buffer));+ assertEquals(0, buffer[0]);+ assertEquals(5, buffer[1]);++ r.close();+ dir.close();+ }++ private static class StandardCodecWithOrds extends Codec {+ public StandardCodecWithOrds() {+ name = "StandardOrds";+ }++ @Override+ public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {+ PostingsWriterBase docs = new StandardPostingsWriter(state);++ // TODO: should we make the terms index more easily+ // pluggable? Ie so that this codec would record which+ // index impl was used, and switch on loading?+ // Or... you must make a new Codec for this?+ TermsIndexWriterBase indexWriter;+ boolean success = false;+ try {+ indexWriter = new FixedGapTermsIndexWriter(state);+ success = true;+ } finally {+ if (!success) {+ docs.close();+ }+ }++ success = false;+ try {+ FieldsConsumer ret = new BlockTermsWriter(indexWriter, state, docs);+ success = true;+ return ret;+ } finally {+ if (!success) {+ try {+ docs.close();+ } finally {+ indexWriter.close();+ }+ }+ }+ }++ public final static int TERMS_CACHE_SIZE = 1024;++ @Override+ public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {+ PostingsReaderBase postings = new StandardPostingsReader(state.dir, state.segmentInfo, state.readBufferSize, state.codecId);+ TermsIndexReaderBase indexReader;++ boolean success = false;+ try {+ indexReader = new FixedGapTermsIndexReader(state.dir,+ state.fieldInfos,+ state.segmentInfo.name,+ state.termsIndexDivisor,+ BytesRef.getUTF8SortedAsUnicodeComparator(),+ state.codecId);+ success = true;+ } finally {+ if (!success) {+ postings.close();+ }+ }++ success = false;+ try {+ FieldsProducer ret = new BlockTermsReader(indexReader,+ state.dir,+ state.fieldInfos,+ state.segmentInfo.name,+ postings,+ state.readBufferSize,+ TERMS_CACHE_SIZE,+ state.codecId);+ success = true;+ return ret;+ } finally {+ if (!success) {+ try {+ postings.close();+ } finally {+ indexReader.close();+ }+ }+ }+ }++ /** Extension of freq postings file */+ static final String FREQ_EXTENSION = "frq";++ /** Extension of prox postings file */+ static final String PROX_EXTENSION = "prx";++ @Override- public void files(Directory dir, SegmentInfo segmentInfo, String id, Set<String> files) throws IOException {- StandardPostingsReader.files(dir, segmentInfo, id, files);- BlockTermsReader.files(dir, segmentInfo, id, files);- FixedGapTermsIndexReader.files(dir, segmentInfo, id, files);++ public void files(Directory dir, SegmentInfo segmentInfo, int id, Set<String> files) throws IOException {++ StandardPostingsReader.files(dir, segmentInfo, ""+id, files);++ BlockTermsReader.files(dir, segmentInfo, ""+id, files);++ FixedGapTermsIndexReader.files(dir, segmentInfo, ""+id, files);+ }++ @Override+ public void getExtensions(Set<String> extensions) {+ getStandardExtensions(extensions);+ }++ public static void getStandardExtensions(Set<String> extensions) {+ extensions.add(FREQ_EXTENSION);+ extensions.add(PROX_EXTENSION);+ BlockTermsReader.getExtensions(extensions);+ FixedGapTermsIndexReader.getIndexExtensions(extensions);+ }+ }++ public void testRandom() throws Exception {+ MockDirectoryWrapper dir = newDirectory();++ final int NUM_TERMS = 100 * RANDOM_MULTIPLIER;+ final Set<BytesRef> terms = new HashSet<BytesRef>();+ while(terms.size() < NUM_TERMS) {+ final String s = _TestUtil.randomRealisticUnicodeString(random);+ //final String s = _TestUtil.randomSimpleString(random);+ if (s.length() > 0) {+ terms.add(new BytesRef(s));+ }+ }+ final BytesRef[] termsArray = terms.toArray(new BytesRef[terms.size()]);+ Arrays.sort(termsArray);++ final int NUM_DOCS = 1000 * RANDOM_MULTIPLIER;++ IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random));++ // Sometimes swap in codec that impls ord():+ if (random.nextInt(10) == 7) {+ // Make sure terms index has ords:+ CoreCodecProvider cp = new CoreCodecProvider();+ cp.register(new StandardCodecWithOrds());+ cp.setDefaultFieldCodec("StandardOrds");++ // So checkIndex on close works+ dir.setCodecProvider(cp);+ conf.setCodecProvider(cp);+ }++ final RandomIndexWriter w = new RandomIndexWriter(random, dir, conf);++ final int[][] idToOrds = new int[NUM_DOCS][];+ final Set<Integer> ordsForDocSet = new HashSet<Integer>();++ for(int id=0;id<NUM_DOCS;id++) {+ Document doc = new Document();++ NumericField idField = new NumericField("id");+ doc.add(idField.setIntValue(id));++ final int termCount = _TestUtil.nextInt(random, 0, 20*RANDOM_MULTIPLIER);+ while(ordsForDocSet.size() < termCount) {+ ordsForDocSet.add(random.nextInt(termsArray.length));+ }+ final int[] ordsForDoc = new int[termCount];+ int upto = 0;+ if (VERBOSE) {+ System.out.println("TEST: doc id=" + id);+ }+ for(int ord : ordsForDocSet) {+ ordsForDoc[upto++] = ord;+ Field field = newField("field", termsArray[ord].utf8ToString(), Field.Index.NOT_ANALYZED);+ if (VERBOSE) {+ System.out.println(" f=" + termsArray[ord].utf8ToString());+ }+ doc.add(field);+ }+ ordsForDocSet.clear();+ Arrays.sort(ordsForDoc);+ idToOrds[id] = ordsForDoc;+ w.addDocument(doc);+ }++ final IndexReader r = w.getReader();+ w.close();++ if (VERBOSE) {+ System.out.println("TEST: reader=" + r);+ }++ for(IndexReader subR : r.getSequentialSubReaders()) {+ if (VERBOSE) {+ System.out.println("\nTEST: sub=" + subR);+ }+ verify(subR, idToOrds, termsArray, null);+ }++ // Also test top-level reader: its enum does not support+ // ord, so this forces the OrdWrapper to run:+ if (VERBOSE) {+ System.out.println("TEST: top reader");+ }+ verify(r, idToOrds, termsArray, null);++ FieldCache.DEFAULT.purge(r);++ r.close();+ dir.close();+ }++ public void testRandomWithPrefix() throws Exception {+ MockDirectoryWrapper dir = newDirectory();++ final Set<String> prefixes = new HashSet<String>();+ final int numPrefix = _TestUtil.nextInt(random, 2, 7);+ if (VERBOSE) {+ System.out.println("TEST: use " + numPrefix + " prefixes");+ }+ while(prefixes.size() < numPrefix) {+ prefixes.add(_TestUtil.randomRealisticUnicodeString(random));+ //prefixes.add(_TestUtil.randomSimpleString(random));+ }+ final String[] prefixesArray = prefixes.toArray(new String[prefixes.size()]);++ final int NUM_TERMS = 100 * RANDOM_MULTIPLIER;+ final Set<BytesRef> terms = new HashSet<BytesRef>();+ while(terms.size() < NUM_TERMS) {+ final String s = prefixesArray[random.nextInt(prefixesArray.length)] + _TestUtil.randomRealisticUnicodeString(random);+ //final String s = prefixesArray[random.nextInt(prefixesArray.length)] + _TestUtil.randomSimpleString(random);+ if (s.length() > 0) {+ terms.add(new BytesRef(s));+ }+ }+ final BytesRef[] termsArray = terms.toArray(new BytesRef[terms.size()]);+ Arrays.sort(termsArray);++ final int NUM_DOCS = 1000 * RANDOM_MULTIPLIER;++ IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random));++ // Sometimes swap in codec that impls ord():+ if (random.nextInt(10) == 7) {+ // Make sure terms index has ords:+ CoreCodecProvider cp = new CoreCodecProvider();+ cp.register(new StandardCodecWithOrds());+ cp.setDefaultFieldCodec("StandardOrds");++ // So checkIndex on close works+ dir.setCodecProvider(cp);+ conf.setCodecProvider(cp);+ }++ final RandomIndexWriter w = new RandomIndexWriter(random, dir, conf);++ final int[][] idToOrds = new int[NUM_DOCS][];+ final Set<Integer> ordsForDocSet = new HashSet<Integer>();++ for(int id=0;id<NUM_DOCS;id++) {+ Document doc = new Document();++ NumericField idField = new NumericField("id");+ doc.add(idField.setIntValue(id));++ final int termCount = _TestUtil.nextInt(random, 0, 20*RANDOM_MULTIPLIER);+ while(ordsForDocSet.size() < termCount) {+ ordsForDocSet.add(random.nextInt(termsArray.length));+ }+ final int[] ordsForDoc = new int[termCount];+ int upto = 0;+ if (VERBOSE) {+ System.out.println("TEST: doc id=" + id);+ }+ for(int ord : ordsForDocSet) {+ ordsForDoc[upto++] = ord;+ Field field = newField("field", termsArray[ord].utf8ToString(), Field.Index.NOT_ANALYZED);+ if (VERBOSE) {+ System.out.println(" f=" + termsArray[ord].utf8ToString());+ }+ doc.add(field);+ }+ ordsForDocSet.clear();+ Arrays.sort(ordsForDoc);+ idToOrds[id] = ordsForDoc;+ w.addDocument(doc);+ }++ final IndexReader r = w.getReader();+ w.close();++ if (VERBOSE) {+ System.out.println("TEST: reader=" + r);+ }++ for(String prefix : prefixesArray) {++ final BytesRef prefixRef = prefix == null ? null : new BytesRef(prefix);++ final int[][] idToOrdsPrefix = new int[NUM_DOCS][];+ for(int id=0;id<NUM_DOCS;id++) {+ final int[] docOrds = idToOrds[id];+ final List<Integer> newOrds = new ArrayList<Integer>();+ for(int ord : idToOrds[id]) {+ if (termsArray[ord].startsWith(prefixRef)) {+ newOrds.add(ord);+ }+ }+ final int[] newOrdsArray = new int[newOrds.size()];+ int upto = 0;+ for(int ord : newOrds) {+ newOrdsArray[upto++] = ord;+ }+ idToOrdsPrefix[id] = newOrdsArray;+ }++ for(IndexReader subR : r.getSequentialSubReaders()) {+ if (VERBOSE) {+ System.out.println("\nTEST: sub=" + subR);+ }+ verify(subR, idToOrdsPrefix, termsArray, prefixRef);+ }++ // Also test top-level reader: its enum does not support+ // ord, so this forces the OrdWrapper to run:+ if (VERBOSE) {+ System.out.println("TEST: top reader");+ }+ verify(r, idToOrdsPrefix, termsArray, prefixRef);+ }++ FieldCache.DEFAULT.purge(r);++ r.close();+ dir.close();+ }++ private void verify(IndexReader r, int[][] idToOrds, BytesRef[] termsArray, BytesRef prefixRef) throws Exception {++ final DocTermOrds dto = new DocTermOrds(r,+ "field",+ prefixRef,+ Integer.MAX_VALUE,+ _TestUtil.nextInt(random, 2, 10));+++ final int[] docIDToID = FieldCache.DEFAULT.getInts(r, "id");+ /*+ for(int docID=0;docID<subR.maxDoc();docID++) {+ System.out.println(" docID=" + docID + " id=" + docIDToID[docID]);+ }+ */++ if (VERBOSE) {+ System.out.println("TEST: verify prefix=" + prefixRef.utf8ToString());+ System.out.println("TEST: all TERMS:");+ TermsEnum allTE = MultiFields.getTerms(r, "field").iterator();+ int ord = 0;+ while(allTE.next() != null) {+ System.out.println(" ord=" + (ord++) + " term=" + allTE.term().utf8ToString());+ }+ }++ //final TermsEnum te = subR.fields().terms("field").iterator();+ final TermsEnum te = dto.getOrdTermsEnum(r);+ if (te == null) {+ if (prefixRef == null) {+ assertNull(r.fields().terms("field"));+ } else {+ Terms terms = r.fields().terms("field");+ if (terms != null) {+ TermsEnum termsEnum = terms.iterator();+ TermsEnum.SeekStatus result = termsEnum.seek(prefixRef, false);+ if (result != TermsEnum.SeekStatus.END) {+ assertFalse("term=" + termsEnum.term().utf8ToString() + " matches prefix=" + prefixRef.utf8ToString(), termsEnum.term().startsWith(prefixRef));+ } else {+ // ok+ }+ } else {+ // ok+ }+ }+ return;+ }++ if (VERBOSE) {+ System.out.println("TEST: TERMS:");+ te.seek(0);+ while(true) {+ System.out.println(" ord=" + te.ord() + " term=" + te.term().utf8ToString());+ if (te.next() == null) {+ break;+ }+ }+ }++ TermOrdsIterator iter = null;+ final int[] buffer = new int[5];+ for(int docID=0;docID<r.maxDoc();docID++) {+ if (VERBOSE) {+ System.out.println("TEST: docID=" + docID + " of " + r.maxDoc() + " (id=" + docIDToID[docID] + ")");+ }+ iter = dto.lookup(docID, iter);+ final int[] answers = idToOrds[docIDToID[docID]];+ int upto = 0;+ while(true) {+ final int chunk = iter.read(buffer);+ for(int idx=0;idx<chunk;idx++) {+ assertEquals(TermsEnum.SeekStatus.FOUND, te.seek((long) buffer[idx]));+ final BytesRef expected = termsArray[answers[upto++]];+ if (VERBOSE) {+ System.out.println(" exp=" + expected.utf8ToString() + " actual=" + te.term().utf8ToString());+ }+ assertEquals("expected=" + expected.utf8ToString() + " actual=" + te.term().utf8ToString() + " ord=" + buffer[idx], expected, te.term());+ }++ if (chunk < buffer.length) {+ assertEquals(answers.length, upto);+ break;+ }+ }+ }+ }+ }diff --cc lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.javaindex fe784a53b47,00000000000..9ca0e86d35dmode 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,601 -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.DocValuesField;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;- import org.apache.lucene.document.DocValuesField;+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.MultiPerDocValues;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.codecs.CodecProvider;++import org.apache.lucene.index.codecs.PerDocValues;+import org.apache.lucene.index.codecs.docvalues.DocValuesCodecProvider;+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.store.MockDirectoryWrapper;+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:+ * - DocValues+ * - 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 CodecProvider provider;++ @Before+ public void setUp() throws Exception {+ super.setUp();+ provider = new DocValuesCodecProvider();+ provider.copyFrom(CodecProvider.getDefault());+ }++ private Directory newDirectory2() throws IOException {+ MockDirectoryWrapper newDirectory = newDirectory();+ newDirectory.setCheckIndexOnClose(false);+ return newDirectory;+ }++ /*+ * Simple test case to show how to use the API+ */+ public void testDocValuesSimple() throws CorruptIndexException, IOException,+ ParseException {+ Directory dir = newDirectory2();+ IndexWriter writer = new IndexWriter(dir, writerConfig(false));+ for (int i = 0; i < 5; i++) {+ Document doc = new Document();+ DocValuesField valuesField = new DocValuesField("docId");+ valuesField.setInt(i);+ doc.add(valuesField);+ doc.add(new Field("docId", "" + i, Store.NO, Index.ANALYZED));+ writer.addDocument(doc);+ }+ writer.commit();++ for (int i = 0; i < 5; i++) {++ Document doc = new Document();++ DocValuesField valuesField = new DocValuesField("docId1");++ valuesField.setFloat(i);++ doc.add(valuesField);++ doc.add(new Field("docId1", "" + i, Store.NO, Index.ANALYZED));++ writer.addDocument(doc);++ }++ writer.commit();+ writer.optimize(true);++ 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());++ new MockAnalyzer(random));+ 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");++ DocValues docValues = MultiPerDocValues.getPerDocs(reader).docValues("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 = newDirectory2();+ 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 = newDirectory2();+ 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 = newDirectory2();+ IndexWriter w = new IndexWriter(target, writerConfig(random.nextBoolean()));+ IndexReader r_1 = IndexReader.open(w_1, true);+ IndexReader r_2 = IndexReader.open(w_2, true);+ if (random.nextBoolean()) {+ w.addIndexes(d_1, d_2);+ } else {+ w.addIndexes(r_1, r_2);+ }+ w.optimize(true);+ w.commit();++ _TestUtil.checkIndex(target, w.getConfig().getCodecProvider());+ assertEquals(valuesPerIndex * 2, w.maxDoc());++ // check values++ IndexReader merged = IndexReader.open(w, true);+ 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(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());++ new MockAnalyzer(random));+ cfg.setMergePolicy(newLogMergePolicy(random));- MergePolicy mergePolicy = cfg.getMergePolicy();- if (mergePolicy instanceof LogMergePolicy) {- LogMergePolicy policy = ((LogMergePolicy) mergePolicy);- policy.setUseCompoundFile(useCompoundFile);- policy.setRequireContiguousMerge(true);- } else if (useCompoundFile) {- LogMergePolicy policy = new LogDocMergePolicy();- policy.setUseCompoundFile(useCompoundFile);- policy.setRequireContiguousMerge(true);- cfg.setMergePolicy(policy);- }++ LogMergePolicy policy = new LogDocMergePolicy();++ cfg.setMergePolicy(policy);++ policy.setUseCompoundFile(useCompoundFile);+ cfg.setCodecProvider(provider);+ return cfg;+ }++ public void runTestNumerics(IndexWriterConfig cfg, boolean withDeletions)+ throws IOException {+ Directory d = newDirectory2();+ 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, true);+ final int numRemainingValues = (int) (numValues - deleted.cardinality());+ final int base = r.numDocs() - numRemainingValues;+ switch (val) {+ case 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 FLOAT_32:+ case FLOAT_64: {+ 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 = newDirectory2();+ 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, withDeletions);+ 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();- Fields fields = optimized ? reader.getSequentialSubReaders()[0].fields()- : MultiFields.getFields(reader);++ PerDocValues perDoc = optimized ? reader.getSequentialSubReaders()[0].perDocValues()++ : MultiPerDocValues.getPerDocs(reader);+ switch (random.nextInt(optimized ? 3 : 2)) { // case 2 only if optimized+ case 0:- return fields.docValues(field);++ return perDoc.docValues(field);+ case 1:- FieldsEnum iterator = fields.iterator();- String name;- while ((name = iterator.next()) != null) {- if (name.equals(field))- return iterator.docValues();++ DocValues docValues = perDoc.docValues(field);++ if (docValues != null) {++ return 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.INTS,+ Type.FLOAT_32, Type.FLOAT_64);++ 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 DocValuesField(value.name())+ : newField(value.name(), _TestUtil.randomRealisticUnicodeString(random,+ 10), idx == Index.NO ? Store.YES : Store.NO, idx);+ doc.add(field);+ DocValuesField valField = new DocValuesField("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 INTS:+ valField.setInt(i);+ break;+ case FLOAT_32:+ case FLOAT_64:+ valField.setFloat(2.0f * i);+ break;+ default:+ fail("unexpected value " + value);+ }+ } else {+ for (int j = 0; j < b.length; j++) {+ b[j] = upto++;+ }+ if (bytesRef != null) {+ 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(true);+ return deleted;+ }+}