Apache Lucene open-source search software
merged with trunk
Simon Willnauerc70f8cc7a6a6
diff --cc lucene/contrib/instantiated/src/java/org/apache/lucene/store/instantiated/InstantiatedIndexReader.javaindex 96d9198146d,301ff986fc2..742e101ce93--- 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@@@ -31,7 -32,7 +32,8 @@@ 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.store.Directory;import org.apache.lucene.util.BitVector;import org.apache.lucene.util.BytesRef;@@@ -428,13 -433,13 +439,18 @@@ public class InstantiatedIndexReader ex}};}++ @Override+ public DocValues docValues(String field) throws IOException {+ return null;+ }};}++ @Override+ public ReaderContext getTopReaderContext() {+ return context;+ }@Overridepublic TermFreqVector[] getTermFreqVectors(int docNumber) throws IOException {diff --cc lucene/contrib/memory/src/java/org/apache/lucene/index/memory/MemoryIndex.javaindex 6b4dc526a06,437d313b9c9..e5a96711a63--- 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@@@ -48,7 -52,7 +52,8 @@@ import org.apache.lucene.index.TermFreqimport org.apache.lucene.index.TermPositionVector;import 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.search.Collector;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriter.javaindex 999fdb117e9,bb5304371fc..2462803f94d--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java@@@ -581,8 -586,22 +586,20 @@@ final class DocumentsWritermessage("flush postings as segment " + segment + " numDocs=" + numDocs);}- final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,- numDocs, writer.getConfig().getTermIndexInterval(),- SegmentCodecs.build(fieldInfos, writer.codecs),- pendingDeletes);+ final SegmentWriteState flushState = segWriteState();++ // 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(numDocs);+ for(int delDocID : pendingDeletes.docIDs) {+ flushState.deletedDocs.set(delDocID);+ }+ pendingDeletes.bytesUsed.addAndGet(-pendingDeletes.docIDs.size() * BufferedDeletes.BYTES_PER_DEL_DOCID);+ pendingDeletes.docIDs.clear();+ }+newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false);Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>();@@@ -646,12 -696,6 +694,12 @@@return newSegment;}++ SegmentWriteState segWriteState() {+ return new SegmentWriteState(infoStream, directory, segment, fieldInfos,+ numDocs, writer.getConfig().getTermIndexInterval(),- SegmentCodecs.build(fieldInfos, writer.codecs), bytesUsed);++ SegmentCodecs.build(fieldInfos, writer.codecs), pendingDeletes, bytesUsed);+ }synchronized void close() {closed = true;diff --cc lucene/src/java/org/apache/lucene/index/Fields.javaindex f3fe6542775,d7b0bba997f..20e7176f4ec--- a/lucene/src/java/org/apache/lucene/index/Fields.java+++ b/lucene/src/java/org/apache/lucene/index/Fields.java@@@ -30,19 -28,9 +30,19 @@@ public abstract class Fields* names. This will not return null. */public abstract FieldsEnum iterator() throws IOException;- /** Get the {@link Terms} for this field. This may return+ /** 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/FilterIndexReader.javaindex 3393a71fdfb,d922a48da7e..4dc7cfee89e--- a/lucene/src/java/org/apache/lucene/index/FilterIndexReader.java+++ b/lucene/src/java/org/apache/lucene/index/FilterIndexReader.java@@@ -19,12 -19,11 +19,13 @@@ 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.store.Directory;import org.apache.lucene.util.Bits;- import org.apache.lucene.search.FieldCache; // not great (circular); used only to purge FieldCache entry on closeimport org.apache.lucene.util.BytesRef;+ import org.apache.lucene.util.MapBackedSet;import java.io.IOException;import java.util.Collection;diff --cc lucene/src/java/org/apache/lucene/index/ParallelReader.javaindex f3562549501,004066c4daa..57476e2cd94--- a/lucene/src/java/org/apache/lucene/index/ParallelReader.java+++ b/lucene/src/java/org/apache/lucene/index/ParallelReader.java@@@ -21,12 -21,9 +21,11 @@@ 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.util.Bits;+import org.apache.lucene.util.Pair;- import org.apache.lucene.search.FieldCache; // not great (circular); used only to purge FieldCache entry on close- import org.apache.lucene.search.Similarity;import org.apache.lucene.util.BytesRef;+ import org.apache.lucene.util.MapBackedSet;import java.io.IOException;import java.util.*;diff --cc lucene/src/java/org/apache/lucene/index/SegmentMerger.javaindex 5aec216579b,a708c93ffcf..da76904f011--- a/lucene/src/java/org/apache/lucene/index/SegmentMerger.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentMerger.java@@@ -19,9 -19,9 +19,10 @@@ package org.apache.lucene.indeximport java.io.IOException;import java.util.ArrayList;+ import java.util.Arrays;import java.util.Collection;import java.util.List;+import java.util.concurrent.atomic.AtomicLong;import org.apache.lucene.document.Document;import org.apache.lucene.index.IndexReader.FieldOption;@@@ -266,7 -266,7 +267,7 @@@ final class SegmentMerger// details.throw new RuntimeException("mergeFields produced an invalid result: docCount is " + docCount + " but fdx file size is " + fdxFileLength + " file=" + fileName + " file exists?=" + directory.fileExists(fileName) + "; now aborting this merge to prevent index corruption");- segmentWriteState = new SegmentWriteState(null, directory, segment, fieldInfos, docCount, termIndexInterval, codecInfo, new AtomicLong(0));- segmentWriteState = new SegmentWriteState(null, directory, segment, fieldInfos, docCount, termIndexInterval, codecInfo, null);++ segmentWriteState = new SegmentWriteState(null, directory, segment, fieldInfos, docCount, termIndexInterval, codecInfo, null, new AtomicLong(0));return docCount;}diff --cc lucene/src/java/org/apache/lucene/index/SegmentReader.javaindex fe4a7bfee4e,ac36827bfc6..f8a0598f72d--- a/lucene/src/java/org/apache/lucene/index/SegmentReader.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentReader.java@@@ -30,9 -29,7 +29,8 @@@ 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.search.Similarity;import org.apache.lucene.store.BufferedIndexInput;import org.apache.lucene.store.Directory;import org.apache.lucene.store.IndexInput;@@@ -41,12 -38,6 +39,11 @@@ import org.apache.lucene.util.BitVectorimport org.apache.lucene.util.Bits;import org.apache.lucene.util.CloseableThreadLocal;import org.apache.lucene.index.codecs.FieldsProducer;+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.search.FieldCache; // not great (circular); used only to purge FieldCache entry on closeimport org.apache.lucene.util.BytesRef;/**@@@ -1253,9 -1199,14 +1207,19 @@@ public class SegmentReader extends Indepublic int getTermInfosIndexDivisor() {return core.termsIndexDivisor;}-- @Override+++ @Override+ protected void readerFinished() {+ // Do nothing here -- we have more careful control on+ // when to notify that a SegmentReader has finished,+ // because a given core is shared across many cloned+ // SegmentReaders. We only notify once that core is no+ // longer used (all SegmentReaders sharing it have been+ // closed).+ }+++ @Override+ public DocValues docValues(String field) throws IOException {+ return core.fields.docValues(field);+ }}diff --cc lucene/src/java/org/apache/lucene/index/SegmentWriteState.javaindex 3ef036f4aba,288c75097a0..98cfdb4edf3--- a/lucene/src/java/org/apache/lucene/index/SegmentWriteState.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentWriteState.java@@@ -18,11 -18,9 +18,12 @@@ package org.apache.lucene.index*/import java.io.PrintStream;+import java.util.Collection;+import java.util.HashSet;+import java.util.concurrent.atomic.AtomicLong;import org.apache.lucene.store.Directory;+ import org.apache.lucene.util.BitVector;/*** @lucene.experimental@@@ -34,9 -32,17 +35,19 @@@ public class SegmentWriteStatepublic final FieldInfos fieldInfos;public final int numDocs;public boolean hasVectors;+ public final Collection<String> flushedFiles;+ public final AtomicLong bytesUsed;+ // Deletes to apply while we are flushing the segment. A+ // Term is enrolled in here if it was deleted at one+ // point, and it's mapped to the docIDUpto, meaning any+ // docID < docIDUpto containing this term should be+ // deleted.+ public final BufferedDeletes segDeletes;++ // Lazily created:+ public BitVector deletedDocs;+final SegmentCodecs segmentCodecs;public final String codecId;@@@ -62,8 -68,9 +73,9 @@@public SegmentWriteState(PrintStream infoStream, Directory directory, String segmentName, FieldInfos fieldInfos,- int numDocs, int termIndexInterval, SegmentCodecs segmentCodecs, AtomicLong bytesUsed) {- int numDocs, int termIndexInterval, SegmentCodecs segmentCodecs, BufferedDeletes segDeletes) {++ int numDocs, int termIndexInterval, SegmentCodecs segmentCodecs, BufferedDeletes segDeletes, AtomicLong bytesUsed) {this.infoStream = infoStream;+ this.segDeletes = segDeletes;this.directory = directory;this.segmentName = segmentName;this.fieldInfos = fieldInfos;@@@ -86,8 -91,7 +98,9 @@@numDocs = state.numDocs;termIndexInterval = state.termIndexInterval;segmentCodecs = state.segmentCodecs;+ flushedFiles = state.flushedFiles;this.codecId = codecId;+ segDeletes = state.segDeletes;+ bytesUsed = state.bytesUsed;}}diff --cc lucene/src/java/org/apache/lucene/index/codecs/BlockTermsReader.javaindex 00000000000,2e0e9cd3959..93882869c26mode 000000,100644..100644--- a/lucene/src/java/org/apache/lucene/index/codecs/BlockTermsReader.java+++ b/lucene/src/java/org/apache/lucene/index/codecs/BlockTermsReader.java@@@ -1,0 -1,742 +1,748 @@@+ 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 java.util.Comparator;+ import java.util.Iterator;+ import java.util.TreeMap;++ import org.apache.lucene.index.DocsAndPositionsEnum;+ import org.apache.lucene.index.DocsEnum;+ 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.SegmentInfo;+ import org.apache.lucene.index.TermState;+ import org.apache.lucene.index.Terms;+ import org.apache.lucene.index.TermsEnum;+ import org.apache.lucene.index.codecs.standard.StandardPostingsReader; // javadocs++import org.apache.lucene.index.values.DocValues;+ import org.apache.lucene.store.ByteArrayDataInput;+ import org.apache.lucene.store.Directory;+ import org.apache.lucene.store.IndexInput;+ import org.apache.lucene.util.ArrayUtil;+ import org.apache.lucene.util.Bits;+ import org.apache.lucene.util.BytesRef;+ import org.apache.lucene.util.CodecUtil;+ import org.apache.lucene.util.DoubleBarrelLRUCache;++ /** Handles a terms dict, but decouples all details of+ * doc/freqs/positions reading to an instance of {@link+ * PostingsReaderBase}. This class is reusable for+ * codecs that use a different format for+ * docs/freqs/positions (though codecs are also free to+ * make their own terms dict impl).+ *+ * <p>This class also interacts with an instance of {@link+ * TermsIndexReaderBase}, to abstract away the specific+ * implementation of the terms dict index.+ * @lucene.experimental */++ public class BlockTermsReader extends FieldsProducer {+ // Open input to the main terms dict file (_X.tis)+ private final IndexInput in;++ // Reads the terms dict entries, to gather state to+ // produce DocsEnum on demand+ private final PostingsReaderBase postingsReader;++ private final TreeMap<String,FieldReader> fields = new TreeMap<String,FieldReader>();++ // Comparator that orders our terms+ private final Comparator<BytesRef> termComp;++ // Caches the most recently looked-up field + terms:+ private final DoubleBarrelLRUCache<FieldAndTerm,BlockTermState> termsCache;++ // Reads the terms index+ private TermsIndexReaderBase indexReader;++ // keeps the dirStart offset+ protected long dirOffset;++ // Used as key for the terms cache+ private static class FieldAndTerm extends DoubleBarrelLRUCache.CloneableKey {+ String field;+ BytesRef term;++ public FieldAndTerm() {+ }++ public FieldAndTerm(FieldAndTerm other) {+ field = other.field;+ term = new BytesRef(other.term);+ }++ @Override+ public boolean equals(Object _other) {+ FieldAndTerm other = (FieldAndTerm) _other;+ return other.field == field && term.bytesEquals(other.term);+ }++ @Override+ public Object clone() {+ return new FieldAndTerm(this);+ }++ @Override+ public int hashCode() {+ return field.hashCode() * 31 + term.hashCode();+ }+ }++ //private String segment;++ public BlockTermsReader(TermsIndexReaderBase indexReader, Directory dir, FieldInfos fieldInfos, String segment, PostingsReaderBase postingsReader, int readBufferSize,+ Comparator<BytesRef> termComp, int termsCacheSize, String codecId)+ throws IOException {++ this.postingsReader = postingsReader;+ termsCache = new DoubleBarrelLRUCache<FieldAndTerm,BlockTermState>(termsCacheSize);++ this.termComp = termComp;+ //this.segment = segment;+ in = dir.openInput(IndexFileNames.segmentFileName(segment, codecId, BlockTermsWriter.TERMS_EXTENSION),+ readBufferSize);++ boolean success = false;+ try {+ readHeader(in);++ // Have PostingsReader init itself+ postingsReader.init(in);++ // Read per-field details+ seekDir(in, dirOffset);++ final int numFields = in.readVInt();++ for(int i=0;i<numFields;i++) {+ final int field = in.readVInt();+ final long numTerms = in.readVLong();+ assert numTerms >= 0;+ final long termsStartPointer = in.readVLong();+ final FieldInfo fieldInfo = fieldInfos.fieldInfo(field);+ final long sumTotalTermFreq = fieldInfo.omitTermFreqAndPositions ? -1 : in.readVLong();+ assert !fields.containsKey(fieldInfo.name);+ fields.put(fieldInfo.name, new FieldReader(fieldInfo, numTerms, termsStartPointer, sumTotalTermFreq));+ }+ success = true;+ } finally {+ if (!success) {+ in.close();+ }+ }++ this.indexReader = indexReader;+ }++ protected void readHeader(IndexInput input) throws IOException {+ CodecUtil.checkHeader(in, BlockTermsWriter.CODEC_NAME,+ BlockTermsWriter.VERSION_START,+ BlockTermsWriter.VERSION_CURRENT);+ dirOffset = in.readLong();+ }++ protected void seekDir(IndexInput input, long dirOffset)+ throws IOException {+ input.seek(dirOffset);+ }++ @Override+ public void loadTermsIndex(int indexDivisor) throws IOException {+ indexReader.loadTermsIndex(indexDivisor);+ }++ @Override+ public void close() throws IOException {+ try {+ try {+ if (indexReader != null) {+ indexReader.close();+ }+ } finally {+ // null so if an app hangs on to us (ie, we are not+ // GCable, despite being closed) we still free most+ // ram+ indexReader = null;+ if (in != null) {+ in.close();+ }+ }+ } finally {+ try {+ if (postingsReader != null) {+ postingsReader.close();+ }+ } finally {+ for(FieldReader field : fields.values()) {+ field.close();+ }+ }+ }+ }++ public static void files(Directory dir, SegmentInfo segmentInfo, String id, Collection<String> files) {+ files.add(IndexFileNames.segmentFileName(segmentInfo.name, id, BlockTermsWriter.TERMS_EXTENSION));+ }++ public static void getExtensions(Collection<String> extensions) {+ extensions.add(BlockTermsWriter.TERMS_EXTENSION);+ }++ @Override+ public FieldsEnum iterator() {+ return new TermFieldsEnum();+ }++ @Override+ public Terms terms(String field) throws IOException {+ return fields.get(field);+ }++ // Iterates through all fields+ private class TermFieldsEnum extends FieldsEnum {+ final Iterator<FieldReader> it;+ FieldReader current;++ TermFieldsEnum() {+ it = fields.values().iterator();+ }++ @Override+ public String next() {+ if (it.hasNext()) {+ current = it.next();+ return current.fieldInfo.name;+ } else {+ current = null;+ return null;+ }+ }++ @Override+ public TermsEnum terms() throws IOException {+ return current.iterator();+ }++++ @Override++ public DocValues docValues() throws IOException {++ return null;++ }+ }++ private class FieldReader extends Terms implements Closeable {+ final long numTerms;+ final FieldInfo fieldInfo;+ final long termsStartPointer;+ final long sumTotalTermFreq;++ FieldReader(FieldInfo fieldInfo, long numTerms, long termsStartPointer, long sumTotalTermFreq) {+ assert numTerms > 0;+ this.fieldInfo = fieldInfo;+ this.numTerms = numTerms;+ this.termsStartPointer = termsStartPointer;+ this.sumTotalTermFreq = sumTotalTermFreq;+ }++ @Override+ public Comparator<BytesRef> getComparator() {+ return termComp;+ }++ @Override+ public void close() {+ super.close();+ }++ @Override+ public TermsEnum iterator() throws IOException {+ return new SegmentTermsEnum();+ }++ @Override+ public long getUniqueTermCount() {+ return numTerms;+ }++ @Override+ public long getSumTotalTermFreq() {+ return sumTotalTermFreq;+ }++ // Iterates through terms in this field+ private final class SegmentTermsEnum extends TermsEnum {+ private final IndexInput in;+ private final BlockTermState state;+ private final boolean doOrd;+ private final FieldAndTerm fieldTerm = new FieldAndTerm();+ private final TermsIndexReaderBase.FieldIndexEnum indexEnum;+ private final BytesRef term = new BytesRef();++ /* This is true if indexEnum is "still" seek'd to the index term+ for the current term. We set it to true on seeking, and then it+ remains valid until next() is called enough times to load another+ terms block: */+ private boolean indexIsCurrent;++ /* True if we've already called .next() on the indexEnum, to "bracket"+ the current block of terms: */+ private boolean didIndexNext;++ /* Next index term, bracketing the current block of terms; this is+ only valid if didIndexNext is true: */+ private BytesRef nextIndexTerm;++ /* True after seek(TermState), do defer seeking. If the app then+ calls next() (which is not "typical"), then we'll do the real seek */+ private boolean seekPending;++ /* How many blocks we've read since last seek. Once this+ is >= indexEnum.getDivisor() we set indexIsCurrent to false (since+ the index can no long bracket seek-within-block). */+ private int blocksSinceSeek;++ private byte[] termSuffixes;+ private ByteArrayDataInput termSuffixesReader = new ByteArrayDataInput(null);++ /* Common prefix used for all terms in this block. */+ private int termBlockPrefix;++ private byte[] docFreqBytes;+ private final ByteArrayDataInput freqReader = new ByteArrayDataInput(null);+ private int metaDataUpto;++ public SegmentTermsEnum() throws IOException {+ in = (IndexInput) BlockTermsReader.this.in.clone();+ in.seek(termsStartPointer);+ indexEnum = indexReader.getFieldEnum(fieldInfo);+ doOrd = indexReader.supportsOrd();+ fieldTerm.field = fieldInfo.name;+ state = postingsReader.newTermState();+ state.totalTermFreq = -1;+ state.ord = -1;++ termSuffixes = new byte[128];+ docFreqBytes = new byte[64];+ //System.out.println("BTR.enum init this=" + this + " postingsReader=" + postingsReader);+ }++ @Override+ public Comparator<BytesRef> getComparator() {+ return termComp;+ }++ @Override+ public SeekStatus seek(final BytesRef target, final boolean useCache) throws IOException {++ if (indexEnum == null) {+ throw new IllegalStateException("terms index was not loaded");+ }++ //System.out.println("BTR.seek seg=" + segment + " target=" + fieldInfo.name + ":" + target.utf8ToString() + " " + target + " current=" + term().utf8ToString() + " " + term() + " useCache=" + useCache + " indexIsCurrent=" + indexIsCurrent + " didIndexNext=" + didIndexNext + " seekPending=" + seekPending + " divisor=" + indexReader.getDivisor() + " this=" + this);+ /*+ if (didIndexNext) {+ if (nextIndexTerm == null) {+ //System.out.println(" nextIndexTerm=null");+ } else {+ //System.out.println(" nextIndexTerm=" + nextIndexTerm.utf8ToString());+ }+ }+ */++ // Check cache+ if (useCache) {+ fieldTerm.term = target;+ // TODO: should we differentiate "frozen"+ // TermState (ie one that was cloned and+ // cached/returned by termState()) from the+ // malleable (primary) one?+ final TermState cachedState = termsCache.get(fieldTerm);+ if (cachedState != null) {+ seekPending = true;+ //System.out.println(" cached!");+ seek(target, cachedState);+ //System.out.println(" term=" + term.utf8ToString());+ return SeekStatus.FOUND;+ }+ }++ boolean doSeek = true;++ // See if we can avoid seeking, because target term+ // is after current term but before next index term:+ if (indexIsCurrent) {++ final int cmp = termComp.compare(term, target);++ if (cmp == 0) {+ // Already at the requested term+ return SeekStatus.FOUND;+ } else if (cmp < 0) {++ // Target term is after current term+ if (!didIndexNext) {+ if (indexEnum.next() == -1) {+ nextIndexTerm = null;+ } else {+ nextIndexTerm = indexEnum.term();+ }+ //System.out.println(" now do index next() nextIndexTerm=" + (nextIndexTerm == null ? "null" : nextIndexTerm.utf8ToString()));+ didIndexNext = true;+ }++ if (nextIndexTerm == null || termComp.compare(target, nextIndexTerm) < 0) {+ // Optimization: requested term is within the+ // same term block we are now in; skip seeking+ // (but do scanning):+ doSeek = false;+ //System.out.println(" skip seek: nextIndexTerm=" + (nextIndexTerm == null ? "null" : nextIndexTerm.utf8ToString()));+ }+ }+ }++ if (doSeek) {+ //System.out.println(" seek");++ // Ask terms index to find biggest indexed term (=+ // first term in a block) that's <= our text:+ in.seek(indexEnum.seek(target));+ boolean result = nextBlock();++ // Block must exist since, at least, the indexed term+ // is in the block:+ assert result;++ indexIsCurrent = true;+ didIndexNext = false;+ blocksSinceSeek = 0;++ if (doOrd) {+ state.ord = indexEnum.ord()-1;+ }++ // NOTE: the first _next() after an index seek is+ // a bit wasteful, since it redundantly reads some+ // suffix bytes into the buffer. We could avoid storing+ // those bytes in the primary file, but then when+ // next()ing over an index term we'd have to+ // special case it:+ term.copy(indexEnum.term());+ //System.out.println(" seek: term=" + term.utf8ToString());+ } else {+ ////System.out.println(" skip seek");+ }++ seekPending = false;++ // Now scan:+ while (_next() != null) {+ final int cmp = termComp.compare(term, target);+ if (cmp == 0) {+ // Match!+ if (useCache) {+ // Store in cache+ decodeMetaData();+ termsCache.put(new FieldAndTerm(fieldTerm), (BlockTermState) state.clone());+ }+ //System.out.println(" FOUND");+ return SeekStatus.FOUND;+ } else if (cmp > 0) {+ //System.out.println(" NOT_FOUND term=" + term.utf8ToString());+ return SeekStatus.NOT_FOUND;+ }++ // The purpose of the terms dict index is to seek+ // the enum to the closest index term before the+ // term we are looking for. So, we should never+ // cross another index term (besides the first+ // one) while we are scanning:+ assert indexIsCurrent;+ }++ indexIsCurrent = false;+ //System.out.println(" END");+ return SeekStatus.END;+ }++ @Override+ public BytesRef next() throws IOException {+ //System.out.println("BTR.next() seekPending=" + seekPending + " pendingSeekCount=" + state.termCount);++ // If seek was previously called and the term was cached,+ // usually caller is just going to pull a D/&PEnum or get+ // docFreq, etc. But, if they then call next(),+ // this method catches up all internal state so next()+ // works properly:+ if (seekPending) {+ assert !indexIsCurrent;+ in.seek(state.blockFilePointer);+ final int pendingSeekCount = state.termCount;+ boolean result = nextBlock();++ final long savOrd = state.ord;++ // Block must exist since seek(TermState) was called w/ a+ // TermState previously returned by this enum when positioned+ // on a real term:+ assert result;++ while(state.termCount < pendingSeekCount) {+ BytesRef nextResult = _next();+ assert nextResult != null;+ }+ seekPending = false;+ state.ord = savOrd;+ }+ return _next();+ }++ /* Decodes only the term bytes of the next term. If caller then asks for+ metadata, ie docFreq, totalTermFreq or pulls a D/&PEnum, we then (lazily)+ decode all metadata up to the current term. */+ private BytesRef _next() throws IOException {+ //System.out.println("BTR._next seg=" + segment + " this=" + this + " termCount=" + state.termCount + " (vs " + state.blockTermCount + ")");+ if (state.termCount == state.blockTermCount) {+ if (!nextBlock()) {+ //System.out.println(" eof");+ indexIsCurrent = false;+ return null;+ }+ }++ // TODO: cutover to something better for these ints! simple64?+ final int suffix = termSuffixesReader.readVInt();+ //System.out.println(" suffix=" + suffix);++ term.length = termBlockPrefix + suffix;+ if (term.bytes.length < term.length) {+ term.grow(term.length);+ }+ termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);+ state.termCount++;++ // NOTE: meaningless in the non-ord case+ state.ord++;++ //System.out.println(" return term=" + fieldInfo.name + ":" + term.utf8ToString() + " " + term);+ return term;+ }++ @Override+ public BytesRef term() {+ return term;+ }++ @Override+ public int docFreq() throws IOException {+ //System.out.println("BTR.docFreq");+ decodeMetaData();+ //System.out.println(" return " + state.docFreq);+ return state.docFreq;+ }++ @Override+ public long totalTermFreq() throws IOException {+ decodeMetaData();+ return state.totalTermFreq;+ }++ @Override+ public DocsEnum docs(Bits skipDocs, DocsEnum reuse) throws IOException {+ //System.out.println("BTR.docs this=" + this);+ decodeMetaData();+ //System.out.println(" state.docFreq=" + state.docFreq);+ final DocsEnum docsEnum = postingsReader.docs(fieldInfo, state, skipDocs, reuse);+ assert docsEnum != null;+ return docsEnum;+ }++ @Override+ public DocsAndPositionsEnum docsAndPositions(Bits skipDocs, DocsAndPositionsEnum reuse) throws IOException {+ //System.out.println("BTR.d&p this=" + this);+ decodeMetaData();+ if (fieldInfo.omitTermFreqAndPositions) {+ return null;+ } else {+ DocsAndPositionsEnum dpe = postingsReader.docsAndPositions(fieldInfo, state, skipDocs, reuse);+ //System.out.println(" return d&pe=" + dpe);+ return dpe;+ }+ }++ @Override+ public void seek(BytesRef target, TermState otherState) throws IOException {+ //System.out.println("BTR.seek termState target=" + target.utf8ToString() + " " + target + " this=" + this);+ assert otherState != null && otherState instanceof BlockTermState;+ assert !doOrd || ((BlockTermState) otherState).ord < numTerms;+ state.copyFrom(otherState);+ seekPending = true;+ indexIsCurrent = false;+ term.copy(target);+ }++ @Override+ public TermState termState() throws IOException {+ //System.out.println("BTR.termState this=" + this);+ decodeMetaData();+ TermState ts = (TermState) state.clone();+ //System.out.println(" return ts=" + ts);+ return ts;+ }++ @Override+ public SeekStatus seek(long ord) throws IOException {+ //System.out.println("BTR.seek by ord ord=" + ord);+ if (indexEnum == null) {+ throw new IllegalStateException("terms index was not loaded");+ }++ if (ord >= numTerms) {+ state.ord = numTerms-1;+ return SeekStatus.END;+ }++ // TODO: if ord is in same terms block and+ // after current ord, we should avoid this seek just+ // like we do in the seek(BytesRef) case+ in.seek(indexEnum.seek(ord));+ boolean result = nextBlock();++ // Block must exist since ord < numTerms:+ assert result;++ indexIsCurrent = true;+ didIndexNext = false;+ blocksSinceSeek = 0;+ seekPending = false;++ state.ord = indexEnum.ord()-1;+ assert state.ord >= -1: "ord=" + state.ord;+ term.copy(indexEnum.term());++ // Now, scan:+ int left = (int) (ord - state.ord);+ while(left > 0) {+ final BytesRef term = _next();+ assert term != null;+ left--;+ assert indexIsCurrent;+ }++ // always found+ return SeekStatus.FOUND;+ }++ @Override+ public long ord() {+ if (!doOrd) {+ throw new UnsupportedOperationException();+ }+ return state.ord;+ }++ private void doPendingSeek() {+ }++ /* Does initial decode of next block of terms; this+ doesn't actually decode the docFreq, totalTermFreq,+ postings details (frq/prx offset, etc.) metadata;+ it just loads them as byte[] blobs which are then+ decoded on-demand if the metadata is ever requested+ for any term in this block. This enables terms-only+ intensive consumes (eg certain MTQs, respelling) to+ not pay the price of decoding metadata they won't+ use. */+ private boolean nextBlock() throws IOException {++ // TODO: we still lazy-decode the byte[] for each+ // term (the suffix), but, if we decoded+ // all N terms up front then seeking could do a fast+ // bsearch w/in the block...++ //System.out.println("BTR.nextBlock() fp=" + in.getFilePointer() + " this=" + this);+ state.blockFilePointer = in.getFilePointer();+ state.blockTermCount = in.readVInt();+ //System.out.println(" blockTermCount=" + state.blockTermCount);+ if (state.blockTermCount == 0) {+ return false;+ }+ termBlockPrefix = in.readVInt();++ // term suffixes:+ int len = in.readVInt();+ if (termSuffixes.length < len) {+ termSuffixes = new byte[ArrayUtil.oversize(len, 1)];+ }+ //System.out.println(" termSuffixes len=" + len);+ in.readBytes(termSuffixes, 0, len);+ termSuffixesReader.reset(termSuffixes);++ // docFreq, totalTermFreq+ len = in.readVInt();+ if (docFreqBytes.length < len) {+ docFreqBytes = new byte[ArrayUtil.oversize(len, 1)];+ }+ //System.out.println(" freq bytes len=" + len);+ in.readBytes(docFreqBytes, 0, len);+ freqReader.reset(docFreqBytes);+ metaDataUpto = 0;++ state.termCount = 0;++ postingsReader.readTermsBlock(in, fieldInfo, state);++ blocksSinceSeek++;+ indexIsCurrent &= (blocksSinceSeek < indexReader.getDivisor());+ //System.out.println(" indexIsCurrent=" + indexIsCurrent);++ return true;+ }++ private void decodeMetaData() throws IOException {+ //System.out.println("BTR.decodeMetadata mdUpto=" + metaDataUpto + " vs termCount=" + state.termCount + " state=" + state);+ if (!seekPending) {+ // lazily catch up on metadata decode:+ final int limit = state.termCount;+ state.termCount = metaDataUpto;+ while (metaDataUpto < limit) {+ //System.out.println(" decode");+ // TODO: we could make "tiers" of metadata, ie,+ // decode docFreq/totalTF but don't decode postings+ // metadata; this way caller could get+ // docFreq/totalTF w/o paying decode cost for+ // postings+ state.docFreq = freqReader.readVInt();+ if (!fieldInfo.omitTermFreqAndPositions) {+ state.totalTermFreq = state.docFreq + freqReader.readVLong();+ }+ postingsReader.nextTerm(fieldInfo, state);+ metaDataUpto++;+ state.termCount++;+ }+ } else {+ //System.out.println(" skip! seekPending");+ }+ }+ }+ }+ }diff --cc lucene/src/java/org/apache/lucene/search/FieldComparator.javaindex 27d10aecd41,1b2fc61c4ae..1f237babb3f--- a/lucene/src/java/org/apache/lucene/search/FieldComparator.java+++ b/lucene/src/java/org/apache/lucene/search/FieldComparator.java@@@ -21,10 -21,9 +21,10 @@@ import java.io.IOExceptionimport java.text.Collator;import java.util.Locale;- import org.apache.lucene.index.IndexReader;+ import org.apache.lucene.index.IndexReader.AtomicReaderContext;-import org.apache.lucene.search.FieldCache.DocTermsIndex;+import org.apache.lucene.index.values.DocValues.Source;import org.apache.lucene.search.FieldCache.DocTerms;+import org.apache.lucene.search.FieldCache.DocTermsIndex;import org.apache.lucene.search.cache.ByteValuesCreator;import org.apache.lucene.search.cache.CachedArray;import org.apache.lucene.search.cache.CachedArrayCreator;@@@ -161,8 -159,9 +160,8 @@@ public abstract class FieldComparator* comparators can just return "this" to reuse the same* comparator across segments* @throws IOException- * @throws IOException*/- public abstract FieldComparator setNextReader(IndexReader reader, int docBase) throws IOException;+ public abstract FieldComparator setNextReader(AtomicReaderContext context) throws IOException;/** Sets the Scorer to use in case a document's score is* needed.@@@ -331,65 -330,6 +330,65 @@@}}+ /** Uses float index values to sort by ascending value */+ public static final class FloatDocValuesComparator extends FieldComparator {+ private final double[] values;+ private Source currentReaderValues;+ private final String field;+ private double bottom;++ FloatDocValuesComparator(int numHits, String field) {+ values = new double[numHits];+ this.field = field;+ }++ @Override+ public int compare(int slot1, int slot2) {+ final double v1 = values[slot1];+ final double v2 = values[slot2];+ if (v1 > v2) {+ return 1;+ } else if (v1 < v2) {+ return -1;+ } else {+ return 0;+ }+ }++ @Override+ public int compareBottom(int doc) {+ final double v2 = currentReaderValues.getFloat(doc);+ if (bottom > v2) {+ return 1;+ } else if (bottom < v2) {+ return -1;+ } else {+ return 0;+ }+ }++ @Override+ public void copy(int slot, int doc) {+ values[slot] = currentReaderValues.getFloat(doc);+ }++ @Override- public FieldComparator setNextReader(IndexReader reader, int docBase) throws IOException {- currentReaderValues = reader.docValues(field).getSource();++ public FieldComparator setNextReader(AtomicReaderContext context) throws IOException {++ currentReaderValues = context.reader.docValues(field).getSource();+ return this;+ }++ @Override+ public void setBottom(final int bottom) {+ this.bottom = values[bottom];+ }++ @Override+ public Comparable<Double> value(int slot) {+ return Double.valueOf(values[slot]);+ }+ }+/** Parses field's values as float (using {@link* FieldCache#getFloats} and sorts by ascending value */public static final class FloatComparator extends NumericComparator<FloatValues> {@@@ -598,69 -538,6 +597,69 @@@}}+ /** Loads int index values and sorts by ascending value. */+ public static final class IntDocValuesComparator extends FieldComparator {+ private final long[] values;+ private Source currentReaderValues;+ private final String field;+ private long bottom;++ IntDocValuesComparator(int numHits, String field) {+ values = new long[numHits];+ this.field = field;+ }++ @Override+ public int compare(int slot1, int slot2) {+ // TODO: there are sneaky non-branch ways to compute+ // -1/+1/0 sign+ final long v1 = values[slot1];+ final long v2 = values[slot2];+ if (v1 > v2) {+ return 1;+ } else if (v1 < v2) {+ return -1;+ } else {+ return 0;+ }+ }++ @Override+ public int compareBottom(int doc) {+ // TODO: there are sneaky non-branch ways to compute+ // -1/+1/0 sign+ final long v2 = currentReaderValues.getInt(doc);+ if (bottom > v2) {+ return 1;+ } else if (bottom < v2) {+ return -1;+ } else {+ return 0;+ }+ }++ @Override+ public void copy(int slot, int doc) {+ values[slot] = currentReaderValues.getInt(doc);+ }++ @Override- public FieldComparator setNextReader(IndexReader reader, int docBase) throws IOException {- currentReaderValues = reader.docValues(field).getSource();++ public FieldComparator setNextReader(AtomicReaderContext context) throws IOException {++ currentReaderValues = context.reader.docValues(field).getSource();+ return this;+ }++ @Override+ public void setBottom(final int bottom) {+ this.bottom = values[bottom];+ }++ @Override+ public Comparable<Long> value(int slot) {+ return Long.valueOf(values[slot]);+ }+ }+/** Parses field's values as long (using {@link* FieldCache#getLongs} and sorts by ascending value */public static final class LongComparator extends NumericComparator<LongValues> {diff --cc lucene/src/java/org/apache/lucene/search/SortField.javaindex a5bfc761cef,663261ebd59..0875ccfa287--- a/lucene/src/java/org/apache/lucene/search/SortField.java+++ b/lucene/src/java/org/apache/lucene/search/SortField.java@@@ -90,10 -84,7 +90,10 @@@ implements Serializable* uses ordinals to do the sorting. */public static final int STRING_VAL = 11;+ /** Sort use byte[] index values. */+ public static final int BYTES = 12;+- /** Represents sorting by document score (relevancy). */+ /** Represents sorting by document score (relevance). */public static final SortField FIELD_SCORE = new SortField (null, SCORE);/** Represents sorting by document number (index order). */diff --cc lucene/src/test-framework/org/apache/lucene/util/_TestUtil.javaindex 64ed7e64bba,1ad038040a2..ad34c887147--- a/lucene/src/test-framework/org/apache/lucene/util/_TestUtil.java+++ b/lucene/src/test-framework/org/apache/lucene/util/_TestUtil.java@@@ -222,6 -245,6 +245,37 @@@ public class _TestUtilsb.appendCodePoint(nextInt(r, blockStarts[block], blockEnds[block]));return sb.toString();}++++ public static String randomUnicodeString(Random r, int minLength, int maxLength) {++ if(minLength > maxLength)++ throw new IllegalArgumentException("minLength must be >= maxLength");++ final boolean lenEqual = minLength==maxLength;++ final int end = lenEqual?minLength:minLength + r.nextInt(maxLength-minLength+1);++ if (end == 0) {++ // allow 0 length++ return "";++ }++++ // TODO(simonw): check this++ final int fixedPlane = 5;//minLength % 5;++ final char[] buffer = new char[end];++ for (int i = 0; i < end; i++) {++ int t = lenEqual? fixedPlane: r.nextInt(5);++ //buffer[i] = (char) (97 + r.nextInt(26));++ if (0 == t && i < end - 1 && !lenEqual) {++ // Make a surrogate pair++ // High surrogate++ buffer[i++] = (char) nextInt(r, 0xd800, 0xdbff);++ // Low surrogate++ buffer[i] = (char) nextInt(r, 0xdc00, 0xdfff);++ }++ else if (t <= 1) buffer[i] = (char) r.nextInt(0x80);++ else if (2 == t) buffer[i] = (char) nextInt(r, 0x80, 0x800);++ else if (3 == t) buffer[i] = (char) nextInt(r, 0x800, 0xd7ff);++ else if (4 == t) buffer[i] = (char) nextInt(r, 0xe000, 0xffff);++ }++ return new String(buffer, 0, end);++ }public static CodecProvider alwaysCodec(final Codec c) {CodecProvider p = new CodecProvider() {diff --cc lucene/src/test/org/apache/lucene/index/TestCodecs.javaindex c138a3203ae,8bd12c906aa..72ecbc88f88--- a/lucene/src/test/org/apache/lucene/index/TestCodecs.java+++ b/lucene/src/test/org/apache/lucene/index/TestCodecs.java@@@ -584,7 -589,8 +590,8 @@@ public class TestCodecs extends LuceneTfinal int termIndexInterval = _TestUtil.nextInt(random, 13, 27);final SegmentCodecs codecInfo = SegmentCodecs.build(fieldInfos, CodecProvider.getDefault());- final SegmentWriteState state = new SegmentWriteState(null, dir, SEGMENT, fieldInfos, 10000, termIndexInterval, codecInfo, new AtomicLong());- final SegmentWriteState state = new SegmentWriteState(null, dir, SEGMENT, fieldInfos, 10000, termIndexInterval, codecInfo, null);++ final SegmentWriteState state = new SegmentWriteState(null, dir, SEGMENT, fieldInfos, 10000, termIndexInterval, codecInfo, null, new AtomicLong(0));+final FieldsConsumer consumer = state.segmentCodecs.codec().fieldsConsumer(state);Arrays.sort(fields);for (final FieldData field : fields) {diff --cc lucene/src/test/org/apache/lucene/index/values/TestDocValuesIndexing.javaindex 1883958eb03,00000000000..fe784a53b47mode 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,591 -1,0 +1,601 @@@+package org.apache.lucene.index.values;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import java.io.Closeable;+import java.io.IOException;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.EnumSet;+import java.util.List;++import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.document.AbstractField;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.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.Term;+import org.apache.lucene.index.codecs.CodecProvider;+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 = newDirectory();++ 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();+ 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());+ TopDocs search = searcher.search(parser.parse("0 OR 1 OR 2 OR 3 OR 4"), 10);+ assertEquals(5, search.totalHits);+ ScoreDoc[] scoreDocs = search.scoreDocs;+ DocValues docValues = MultiFields.getDocValues(reader, "docId");+ Source source = docValues.getSource();+ for (int i = 0; i < scoreDocs.length; i++) {+ assertEquals(i, scoreDocs[i].doc);+ assertEquals(i, source.getInt(scoreDocs[i].doc));+ }+ reader.close();+ dir.close();+ }++ /**+ * Tests complete indexing of {@link Type} including deletions, merging and+ * sparse value fields on Compound-File+ */+ public void testIndexBytesNoDeletesCFS() throws IOException {+ runTestIndexBytes(writerConfig(true), false);+ }++ public void testIndexBytesDeletesCFS() throws IOException {+ runTestIndexBytes(writerConfig(true), true);+ }++ public void testIndexNumericsNoDeletesCFS() throws IOException {+ runTestNumerics(writerConfig(true), false);+ }++ public void testIndexNumericsDeletesCFS() throws IOException {+ runTestNumerics(writerConfig(true), true);+ }++ /**+ * Tests complete indexing of {@link Type} including deletions, merging and+ * sparse value fields on None-Compound-File+ */+ public void testIndexBytesNoDeletes() throws IOException {+ runTestIndexBytes(writerConfig(false), false);+ }++ public void testIndexBytesDeletes() throws IOException {+ runTestIndexBytes(writerConfig(false), true);+ }++ public void testIndexNumericsNoDeletes() throws IOException {+ runTestNumerics(writerConfig(false), false);+ }++ public void testIndexNumericsDeletes() throws IOException {+ runTestNumerics(writerConfig(false), true);+ }++ public void testAddIndexes() throws IOException {+ int valuesPerIndex = 10;+ List<Type> values = Arrays.asList(Type.values());+ Collections.shuffle(values, random);+ Type first = values.get(0);+ Type second = values.get(1);+ String msg = "[first=" + first.name() + ", second=" + second.name() + "]";+ // index first index- Directory d_1 = newDirectory();++ 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 = newDirectory();++ 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 = newDirectory();++ Directory target = newDirectory2();+ IndexWriter w = new IndexWriter(target, writerConfig(random.nextBoolean()));- IndexReader r_1 = IndexReader.open(w_1);- IndexReader r_2 = IndexReader.open(w_2);++ 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);++ 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());++ cfg.setMergePolicy(newLogMergePolicy(random));+ MergePolicy mergePolicy = cfg.getMergePolicy();+ if (mergePolicy instanceof LogMergePolicy) {- ((LogMergePolicy) mergePolicy).setUseCompoundFile(useCompoundFile);++ 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);+ }+ cfg.setCodecProvider(provider);+ return cfg;+ }++ public void runTestNumerics(IndexWriterConfig cfg, boolean withDeletions)+ throws IOException {- Directory d = newDirectory();++ 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);++ 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 = newDirectory();++ 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);++ 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();- reader.isCurrent();+ Fields fields = optimized ? reader.getSequentialSubReaders()[0].fields()+ : MultiFields.getFields(reader);+ switch (random.nextInt(optimized ? 3 : 2)) { // case 2 only if optimized+ case 0:+ return fields.docValues(field);+ case 1:+ FieldsEnum iterator = fields.iterator();+ String name;+ while ((name = iterator.next()) != null) {+ if (name.equals(field))+ return iterator.docValues();+ }+ throw new RuntimeException("no such field " + field);+ case 2:// this only works if we are on an optimized index!+ return reader.getSequentialSubReaders()[0].docValues(field);+ }+ throw new RuntimeException();+ }++ private Source getSource(DocValues values) throws IOException {+ Source source;+ if (random.nextInt(10) == 0) {+ source = values.load();+ } else {+ // getSource uses cache internally+ source = values.getSource();+ }+ assertNotNull(source);+ return source;+ }++ private DocValuesEnum getValuesEnum(DocValues values) throws IOException {+ DocValuesEnum valuesEnum;+ if (!(values instanceof MultiDocValues) && random.nextInt(10) == 0) {+ // TODO not supported by MultiDocValues yet!+ valuesEnum = getSource(values).getEnum();+ } else {+ valuesEnum = values.getEnum();++ }+ assertNotNull(valuesEnum);+ return valuesEnum;+ }++ private static EnumSet<Type> BYTES = EnumSet.of(Type.BYTES_FIXED_DEREF,+ Type.BYTES_FIXED_SORTED, Type.BYTES_FIXED_STRAIGHT, Type.BYTES_VAR_DEREF,+ Type.BYTES_VAR_SORTED, Type.BYTES_VAR_STRAIGHT);++ private static EnumSet<Type> NUMERICS = EnumSet.of(Type.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;+ }+}