Skip to content

Apache Lucene open-source search software

merge trunk into realtime branch

Michael Busch502e971a78db
diff --cc lucene/src/java/org/apache/lucene/index/BufferedDeletes.java
index 00000000000,3b144aada2c..1b894c4e436
mode 000000,100644..100644
--- a/lucene/src/java/org/apache/lucene/index/BufferedDeletes.java
+++ b/lucene/src/java/org/apache/lucene/index/BufferedDeletes.java
@@@ -1,0 -1,451 +1,451 @@@
+ 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.io.PrintStream;
+ import java.util.HashMap;
+ import java.util.Date;
+ import java.util.Map.Entry;
+ import java.util.Map;
+ import java.util.concurrent.atomic.AtomicInteger;
+ import java.util.concurrent.atomic.AtomicLong;
+
+ import org.apache.lucene.search.IndexSearcher;
+ import org.apache.lucene.search.Query;
+ import org.apache.lucene.search.Scorer;
+ import org.apache.lucene.search.Weight;
+
+ /** Holds a {@link SegmentDeletes} for each segment in the
+ * index. */
+
+ class BufferedDeletes {
+
+ // Deletes for all flushed/merged segments:
+ private final Map<SegmentInfo,SegmentDeletes> deletesMap = new HashMap<SegmentInfo,SegmentDeletes>();
+
+ // used only by assert
+ private Term lastDeleteTerm;
-
++
+ private PrintStream infoStream;
+ private final AtomicLong bytesUsed = new AtomicLong();
+ private final AtomicInteger numTerms = new AtomicInteger();
+ private final int messageID;
+
+ public BufferedDeletes(int messageID) {
+ this.messageID = messageID;
+ }
+
+ private synchronized void message(String message) {
+ if (infoStream != null) {
+ infoStream.println("BD " + messageID + " [" + new Date() + "; " + Thread.currentThread().getName() + "]: BD " + message);
+ }
+ }
-
++
+ public synchronized void setInfoStream(PrintStream infoStream) {
+ this.infoStream = infoStream;
+ }
+
+ public synchronized void pushDeletes(SegmentDeletes newDeletes, SegmentInfo info) {
+ pushDeletes(newDeletes, info, false);
+ }
+
+ // Moves all pending deletes onto the provided segment,
+ // then clears the pending deletes
+ public synchronized void pushDeletes(SegmentDeletes newDeletes, SegmentInfo info, boolean noLimit) {
+ assert newDeletes.any();
+ numTerms.addAndGet(newDeletes.numTermDeletes.get());
+
+ if (!noLimit) {
+ assert !deletesMap.containsKey(info);
+ assert info != null;
+ deletesMap.put(info, newDeletes);
+ bytesUsed.addAndGet(newDeletes.bytesUsed.get());
+ } else {
+ final SegmentDeletes deletes = getDeletes(info);
+ bytesUsed.addAndGet(-deletes.bytesUsed.get());
+ deletes.update(newDeletes, noLimit);
+ bytesUsed.addAndGet(deletes.bytesUsed.get());
- }
++ }
+ if (infoStream != null) {
+ message("push deletes seg=" + info + " dels=" + getDeletes(info));
+ }
- assert checkDeleteStats();
++ assert checkDeleteStats();
+ }
+
+ public synchronized void clear() {
+ deletesMap.clear();
+ numTerms.set(0);
+ bytesUsed.set(0);
+ }
+
+ synchronized boolean any() {
+ return bytesUsed.get() != 0;
+ }
+
+ public int numTerms() {
+ return numTerms.get();
+ }
+
+ public long bytesUsed() {
+ return bytesUsed.get();
+ }
+
+ // IW calls this on finishing a merge. While the merge
+ // was running, it's possible new deletes were pushed onto
+ // our last (and only our last) segment. In this case we
+ // must carry forward those deletes onto the merged
+ // segment.
+ synchronized void commitMerge(MergePolicy.OneMerge merge) {
+ assert checkDeleteStats();
+ if (infoStream != null) {
+ message("commitMerge merge.info=" + merge.info + " merge.segments=" + merge.segments);
+ }
+ final SegmentInfo lastInfo = merge.segments.lastElement();
+ final SegmentDeletes lastDeletes = deletesMap.get(lastInfo);
+ if (lastDeletes != null) {
+ deletesMap.remove(lastInfo);
+ assert !deletesMap.containsKey(merge.info);
+ deletesMap.put(merge.info, lastDeletes);
+ // don't need to update numTerms/bytesUsed since we
+ // are just moving the deletes from one info to
+ // another
+ if (infoStream != null) {
+ message("commitMerge done: new deletions=" + lastDeletes);
+ }
+ } else if (infoStream != null) {
+ message("commitMerge done: no new deletions");
+ }
+ assert !anyDeletes(merge.segments.range(0, merge.segments.size()-1));
+ assert checkDeleteStats();
+ }
+
+ synchronized void clear(SegmentDeletes deletes) {
+ deletes.clear();
+ }
-
++
+ public synchronized boolean applyDeletes(IndexWriter.ReaderPool readerPool, SegmentInfos segmentInfos, SegmentInfos applyInfos) throws IOException {
+ if (!any()) {
+ return false;
+ }
+ final long t0 = System.currentTimeMillis();
+
+ if (infoStream != null) {
+ message("applyDeletes: applyInfos=" + applyInfos + "; index=" + segmentInfos);
+ }
+
+ assert checkDeleteStats();
+
+ assert applyInfos.size() > 0;
+
+ boolean any = false;
-
++
+ final SegmentInfo lastApplyInfo = applyInfos.lastElement();
+ final int lastIdx = segmentInfos.indexOf(lastApplyInfo);
-
++
+ final SegmentInfo firstInfo = applyInfos.firstElement();
+ final int firstIdx = segmentInfos.indexOf(firstInfo);
+
+ // applyInfos must be a slice of segmentInfos
+ assert lastIdx - firstIdx + 1 == applyInfos.size();
-
++
+ // iterate over all segment infos backwards
- // coalesceing deletes along the way
- // when we're at or below the last of the
++ // coalesceing deletes along the way
++ // when we're at or below the last of the
+ // segments to apply to, start applying the deletes
+ // we traverse up to the first apply infos
+ SegmentDeletes coalescedDeletes = null;
+ boolean hasDeletes = false;
+ for (int segIdx=segmentInfos.size()-1; segIdx >= firstIdx; segIdx--) {
+ final SegmentInfo info = segmentInfos.info(segIdx);
+ final SegmentDeletes deletes = deletesMap.get(info);
+ assert deletes == null || deletes.any();
+
+ if (deletes == null && coalescedDeletes == null) {
+ continue;
+ }
+
+ if (infoStream != null) {
+ message("applyDeletes: seg=" + info + " segment's deletes=[" + (deletes == null ? "null" : deletes) + "]; coalesced deletes=[" + (coalescedDeletes == null ? "null" : coalescedDeletes) + "]");
+ }
+
+ hasDeletes |= deletes != null;
+
+ if (segIdx <= lastIdx && hasDeletes) {
+
+ final long delCountInc = applyDeletes(readerPool, info, coalescedDeletes, deletes);
+
+ if (delCountInc != 0) {
+ any = true;
+ }
+ if (infoStream != null) {
+ message("deletes touched " + delCountInc + " docIDs");
+ }
-
++
+ if (deletes != null) {
+ // we've applied doc ids, and they're only applied
+ // on the current segment
+ bytesUsed.addAndGet(-deletes.docIDs.size() * SegmentDeletes.BYTES_PER_DEL_DOCID);
+ deletes.clearDocIDs();
+ }
+ }
-
++
+ // now coalesce at the max limit
+ if (deletes != null) {
+ if (coalescedDeletes == null) {
+ coalescedDeletes = new SegmentDeletes();
+ }
+ // TODO: we could make this single pass (coalesce as
+ // we apply the deletes
+ coalescedDeletes.update(deletes, true);
+ }
+ }
+
+ // move all deletes to segment just before our merge.
+ if (firstIdx > 0) {
+
+ SegmentDeletes mergedDeletes = null;
+ // TODO: we could also make this single pass
+ for (SegmentInfo info : applyInfos) {
+ final SegmentDeletes deletes = deletesMap.get(info);
+ if (deletes != null) {
+ assert deletes.any();
+ if (mergedDeletes == null) {
+ mergedDeletes = getDeletes(segmentInfos.info(firstIdx-1));
+ numTerms.addAndGet(-mergedDeletes.numTermDeletes.get());
+ bytesUsed.addAndGet(-mergedDeletes.bytesUsed.get());
+ }
+
+ mergedDeletes.update(deletes, true);
+ }
+ }
+
+ if (mergedDeletes != null) {
+ numTerms.addAndGet(mergedDeletes.numTermDeletes.get());
+ bytesUsed.addAndGet(mergedDeletes.bytesUsed.get());
+ }
+
+ if (infoStream != null) {
+ if (mergedDeletes != null) {
+ message("applyDeletes: merge all deletes into seg=" + segmentInfos.info(firstIdx-1) + ": " + mergedDeletes);
+ } else {
+ message("applyDeletes: no deletes to merge");
+ }
+ }
+ } else {
+ // We drop the deletes in this case, because we've
+ // applied them to segment infos starting w/ the first
+ // segment. There are no prior segments so there's no
+ // reason to keep them around. When the applyInfos ==
+ // segmentInfos this means all deletes have been
+ // removed:
+ }
+ remove(applyInfos);
+
+ assert checkDeleteStats();
+ assert applyInfos != segmentInfos || !any();
-
++
+ if (infoStream != null) {
+ message("applyDeletes took " + (System.currentTimeMillis()-t0) + " msec");
+ }
+ return any;
+ }
-
++
+ private synchronized long applyDeletes(IndexWriter.ReaderPool readerPool,
- SegmentInfo info,
++ SegmentInfo info,
+ SegmentDeletes coalescedDeletes,
- SegmentDeletes segmentDeletes) throws IOException {
++ SegmentDeletes segmentDeletes) throws IOException {
+ assert readerPool.infoIsLive(info);
-
++
+ assert coalescedDeletes == null || coalescedDeletes.docIDs.size() == 0;
-
++
+ long delCount = 0;
+
+ // Lock order: IW -> BD -> RP
+ SegmentReader reader = readerPool.get(info, false);
+ try {
+ if (coalescedDeletes != null) {
+ delCount += applyDeletes(coalescedDeletes, reader);
+ }
+ if (segmentDeletes != null) {
+ delCount += applyDeletes(segmentDeletes, reader);
+ }
+ } finally {
+ readerPool.release(reader);
+ }
+ return delCount;
+ }
-
++
+ private synchronized long applyDeletes(SegmentDeletes deletes, SegmentReader reader) throws IOException {
+
+ long delCount = 0;
+
+ assert checkDeleteTerm(null);
-
++
+ if (deletes.terms.size() > 0) {
+ Fields fields = reader.fields();
+ if (fields == null) {
+ // This reader has no postings
+ return 0;
+ }
+
+ TermsEnum termsEnum = null;
-
++
+ String currentField = null;
+ DocsEnum docs = null;
-
++
+ for (Entry<Term,Integer> entry: deletes.terms.entrySet()) {
+ Term term = entry.getKey();
+ // Since we visit terms sorted, we gain performance
+ // by re-using the same TermsEnum and seeking only
+ // forwards
+ if (term.field() != currentField) {
+ assert currentField == null || currentField.compareTo(term.field()) < 0;
+ currentField = term.field();
+ Terms terms = fields.terms(currentField);
+ if (terms != null) {
+ termsEnum = terms.iterator();
+ } else {
+ termsEnum = null;
+ }
+ }
-
++
+ if (termsEnum == null) {
+ continue;
+ }
+ assert checkDeleteTerm(term);
-
++
+ if (termsEnum.seek(term.bytes(), false) == TermsEnum.SeekStatus.FOUND) {
+ DocsEnum docsEnum = termsEnum.docs(reader.getDeletedDocs(), docs);
-
++
+ if (docsEnum != null) {
+ docs = docsEnum;
+ final int limit = entry.getValue();
+ while (true) {
+ final int docID = docs.nextDoc();
+ if (docID == DocsEnum.NO_MORE_DOCS || docID >= limit) {
+ break;
+ }
+ reader.deleteDocument(docID);
+ // TODO: we could/should change
+ // reader.deleteDocument to return boolean
+ // true if it did in fact delete, because here
+ // we could be deleting an already-deleted doc
+ // which makes this an upper bound:
+ delCount++;
+ }
+ }
+ }
+ }
+ }
+
+ // Delete by docID
+ for (Integer docIdInt : deletes.docIDs) {
+ int docID = docIdInt.intValue();
+ reader.deleteDocument(docID);
+ delCount++;
+ }
+
+ // Delete by query
+ if (deletes.queries.size() > 0) {
+ IndexSearcher searcher = new IndexSearcher(reader);
+ try {
+ for (Entry<Query, Integer> entry : deletes.queries.entrySet()) {
+ Query query = entry.getKey();
+ int limit = entry.getValue().intValue();
+ Weight weight = query.weight(searcher);
+ Scorer scorer = weight.scorer(reader, true, false);
+ if (scorer != null) {
+ while(true) {
+ int doc = scorer.nextDoc();
+ if (doc >= limit)
+ break;
+
+ reader.deleteDocument(doc);
+ // TODO: we could/should change
+ // reader.deleteDocument to return boolean
+ // true if it did in fact delete, because here
+ // we could be deleting an already-deleted doc
+ // which makes this an upper bound:
+ delCount++;
+ }
+ }
+ }
+ } finally {
+ searcher.close();
+ }
+ }
+
+ return delCount;
+ }
-
++
+ public synchronized SegmentDeletes getDeletes(SegmentInfo info) {
+ SegmentDeletes deletes = deletesMap.get(info);
+ if (deletes == null) {
+ deletes = new SegmentDeletes();
+ deletesMap.put(info, deletes);
+ }
+ return deletes;
+ }
-
++
+ public synchronized void remove(SegmentInfos infos) {
+ assert infos.size() > 0;
+ for (SegmentInfo info : infos) {
+ SegmentDeletes deletes = deletesMap.get(info);
+ if (deletes != null) {
+ bytesUsed.addAndGet(-deletes.bytesUsed.get());
+ assert bytesUsed.get() >= 0: "bytesUsed=" + bytesUsed;
+ numTerms.addAndGet(-deletes.numTermDeletes.get());
+ assert numTerms.get() >= 0: "numTerms=" + numTerms;
+ deletesMap.remove(info);
+ }
+ }
+ }
+
+ // used only by assert
+ private boolean anyDeletes(SegmentInfos infos) {
+ for(SegmentInfo info : infos) {
+ if (deletesMap.containsKey(info)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // used only by assert
+ private boolean checkDeleteTerm(Term term) {
+ if (term != null) {
+ assert lastDeleteTerm == null || term.compareTo(lastDeleteTerm) > 0: "lastTerm=" + lastDeleteTerm + " vs term=" + term;
+ }
+ lastDeleteTerm = term;
+ return true;
+ }
-
++
+ // only for assert
+ private boolean checkDeleteStats() {
+ int numTerms2 = 0;
+ long bytesUsed2 = 0;
+ for(SegmentDeletes deletes : deletesMap.values()) {
+ numTerms2 += deletes.numTermDeletes.get();
+ bytesUsed2 += deletes.bytesUsed.get();
+ }
+ assert numTerms2 == numTerms.get(): "numTerms2=" + numTerms2 + " vs " + numTerms.get();
+ assert bytesUsed2 == bytesUsed.get(): "bytesUsed2=" + bytesUsed2 + " vs " + bytesUsed;
+ return true;
+ }
+ }
diff --cc lucene/src/java/org/apache/lucene/index/ByteSliceWriter.java
index ea0a8fd7d88,5355dee4f83..5c8b921f087
--- a/lucene/src/java/org/apache/lucene/index/ByteSliceWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/ByteSliceWriter.java
@@@ -80,6 -81,6 +81,6 @@@ final class ByteSliceWriter extends Dat
}
public int getAddress() {
- return upto + (offset0 & DocumentsWriterRAMAllocator.BYTE_BLOCK_NOT_MASK);
- return upto + (offset0 & DocumentsWriter.BYTE_BLOCK_NOT_MASK);
++ return upto + (offset0 & DocumentsWriterPerThread.BYTE_BLOCK_NOT_MASK);
}
}
diff --cc lucene/src/java/org/apache/lucene/index/DocFieldConsumer.java
index f9951d381e0,d1b17dcacc2..b938207acaa
--- a/lucene/src/java/org/apache/lucene/index/DocFieldConsumer.java
+++ b/lucene/src/java/org/apache/lucene/index/DocFieldConsumer.java
@@@ -26,8 -27,8 +26,8 @@@ abstract class DocFieldConsumer
/** Called when DocumentsWriter decides to create a new
* segment */
- abstract void flush(Map<DocFieldConsumerPerThread,Collection<DocFieldConsumerPerField>> threadsAndFields, SegmentWriteState state) throws IOException;
+ abstract void flush(Map<FieldInfo, DocFieldConsumerPerField> fieldsToFlush, SegmentWriteState state) throws IOException;
-
+
/** Called when an aborting exception is hit */
abstract void abort();
@@@ -35,13 -39,7 +35,13 @@@
* The consumer should free RAM, if possible, returning
* true if any RAM was in fact freed. */
abstract boolean freeRAM();
-
+
+ abstract void startDocument() throws IOException;
+
+ abstract DocFieldConsumerPerField addField(FieldInfo fi);
-
++
+ abstract void finishDocument() throws IOException;
-
++
void setFieldInfos(FieldInfos fieldInfos) {
this.fieldInfos = fieldInfos;
}
diff --cc lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java
index 50a357414e6,65a2d4d5368..7b5aa2dc4f2
--- a/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java
+++ b/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java
@@@ -38,28 -33,15 +38,29 @@@ import org.apache.lucene.document.Field
final class DocFieldProcessor extends DocConsumer {
- final FieldInfos fieldInfos = new FieldInfos();
- final DocumentsWriter docWriter;
+ final FieldInfos fieldInfos;
final DocFieldConsumer consumer;
final StoredFieldsWriter fieldsWriter;
- public DocFieldProcessor(DocumentsWriter docWriter, DocFieldConsumer consumer) {
- this.docWriter = docWriter;
+ // Holds all fields seen in current doc
+ DocFieldProcessorPerField[] fields = new DocFieldProcessorPerField[1];
+ int fieldCount;
+
+ // Hash table for all fields ever seen
+ DocFieldProcessorPerField[] fieldHash = new DocFieldProcessorPerField[2];
+ int hashMask = 1;
+ int totalFieldCount;
+
-
++
+ float docBoost;
+ int fieldGen;
+ final DocumentsWriterPerThread.DocState docState;
+
+
+ public DocFieldProcessor(DocumentsWriterPerThread docWriter, DocFieldConsumer consumer) {
+ this.docState = docWriter.docState;
this.consumer = consumer;
+ fieldInfos = docWriter.getFieldInfos();
consumer.setFieldInfos(fieldInfos);
fieldsWriter = new StoredFieldsWriter(docWriter, fieldInfos);
}
@@@ -108,245 -77,9 +109,245 @@@
public boolean freeRAM() {
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;
+ }
+
+ /** If there are fields we've seen but did not see again
+ * in the last run, then free them up. */
+
+ void trimFields(SegmentWriteState state) {
+
+ for(int i=0;i<fieldHash.length;i++) {
+ DocFieldProcessorPerField perField = fieldHash[i];
+ DocFieldProcessorPerField lastPerField = null;
+
+ while (perField != null) {
+
+ if (perField.lastGen == -1) {
+
+ // This field was not seen since the previous
+ // flush, so, free up its resources now
+
+ // Unhash
+ if (lastPerField == null)
+ fieldHash[i] = perField.next;
+ else
+ lastPerField.next = perField.next;
+
+ if (state.infoStream != null) {
+ state.infoStream.println(" purge field=" + perField.fieldInfo.name);
+ }
+
+ totalFieldCount--;
+
+ } else {
+ // Reset
+ perField.lastGen = -1;
+ lastPerField = perField;
+ }
+
+ perField = perField.next;
+ }
+ }
+ }
+
+ 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 DocConsumerPerThread addThread(DocumentsWriterThreadState threadState) throws IOException {
- return new DocFieldProcessorPerThread(threadState, this);
+ public void processDocument() 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.add(fieldName, field.isIndexed(), field.isTermVectorStored(),
+ field.isStorePositionWithTermVector(), field.isStoreOffsetWithTermVector(),
+ field.getOmitNorms(), false, field.getOmitTermFreqAndPositions());
+
+ fp = new DocFieldProcessorPerField(this, fi);
+ fp.next = fieldHash[hashPos];
+ fieldHash[hashPos] = fp;
+ totalFieldCount++;
+
+ if (totalFieldCount >= fieldHash.length/2)
+ rehash();
+ } else {
+ fp.fieldInfo.update(field.isIndexed(), field.isTermVectorStored(),
+ field.isStorePositionWithTermVector(), field.isStoreOffsetWithTermVector(),
+ field.getOmitNorms(), false, field.getOmitTermFreqAndPositions());
+ }
-
++
+ 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 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 " + DocumentsWriterRAMAllocator.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.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
+ 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);
}
}
diff --cc lucene/src/java/org/apache/lucene/index/DocFieldProcessorPerField.java
index 2413d032baa,8fb1da45280..36b1908f6d3
--- a/lucene/src/java/org/apache/lucene/index/DocFieldProcessorPerField.java
+++ b/lucene/src/java/org/apache/lucene/index/DocFieldProcessorPerField.java
@@@ -41,17 -39,6 +41,17 @@@ final class DocFieldProcessorPerField
this.fieldInfo = fieldInfo;
}
+ public void addField(Fieldable field) {
+ if (fieldCount == fields.length) {
- int newSize = ArrayUtil.oversize(fieldCount + 1, RamUsageEstimator.NUM_BYTES_OBJ_REF);
++ int newSize = ArrayUtil.oversize(fieldCount + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF);
+ Fieldable[] newArray = new Fieldable[newSize];
+ System.arraycopy(fields, 0, newArray, 0, fieldCount);
+ fields = newArray;
+ }
+
+ fields[fieldCount++] = field;
+ }
-
++
public void abort() {
consumer.abort();
}
diff --cc lucene/src/java/org/apache/lucene/index/DocInverter.java
index e6f3109750b,61f2c4fe3ae..5877bb6c62c
--- a/lucene/src/java/org/apache/lucene/index/DocInverter.java
+++ b/lucene/src/java/org/apache/lucene/index/DocInverter.java
@@@ -35,32 -34,7 +35,32 @@@ final class DocInverter extends DocFiel
final InvertedDocConsumer consumer;
final InvertedDocEndConsumer endConsumer;
- public DocInverter(InvertedDocConsumer consumer, InvertedDocEndConsumer endConsumer) {
+ final DocumentsWriterPerThread.DocState docState;
+
+ final FieldInvertState fieldState = new FieldInvertState();
+
+ final SingleTokenAttributeSource singleToken = new SingleTokenAttributeSource();
-
++
+ static class SingleTokenAttributeSource extends AttributeSource {
+ final CharTermAttribute termAttribute;
+ final OffsetAttribute offsetAttribute;
-
++
+ private SingleTokenAttributeSource() {
+ termAttribute = addAttribute(CharTermAttribute.class);
+ offsetAttribute = addAttribute(OffsetAttribute.class);
+ }
-
++
+ public void reinit(String stringValue, int startOffset, int endOffset) {
+ termAttribute.setEmpty().append(stringValue);
+ offsetAttribute.setOffset(startOffset, endOffset);
+ }
+ }
-
++
+ // Used to read a string value for a field
+ final ReusableStringReader stringReader = new ReusableStringReader();
+
+ public DocInverter(DocumentsWriterPerThread.DocState docState, InvertedDocConsumer consumer, InvertedDocEndConsumer endConsumer) {
+ this.docState = docState;
this.consumer = consumer;
this.endConsumer = endConsumer;
}
@@@ -73,33 -47,30 +73,32 @@@
}
@Override
- void flush(Map<DocFieldConsumerPerThread, Collection<DocFieldConsumerPerField>> threadsAndFields, SegmentWriteState state) throws IOException {
-
- Map<InvertedDocConsumerPerThread,Collection<InvertedDocConsumerPerField>> childThreadsAndFields = new HashMap<InvertedDocConsumerPerThread,Collection<InvertedDocConsumerPerField>>();
- Map<InvertedDocEndConsumerPerThread,Collection<InvertedDocEndConsumerPerField>> endChildThreadsAndFields = new HashMap<InvertedDocEndConsumerPerThread,Collection<InvertedDocEndConsumerPerField>>();
+ void flush(Map<FieldInfo, DocFieldConsumerPerField> fieldsToFlush, SegmentWriteState state) throws IOException {
- for (Map.Entry<DocFieldConsumerPerThread,Collection<DocFieldConsumerPerField>> entry : threadsAndFields.entrySet() ) {
+ Map<FieldInfo, InvertedDocConsumerPerField> childFieldsToFlush = new HashMap<FieldInfo, InvertedDocConsumerPerField>();
+ Map<FieldInfo, InvertedDocEndConsumerPerField> endChildFieldsToFlush = new HashMap<FieldInfo, InvertedDocEndConsumerPerField>();
+ for (Map.Entry<FieldInfo, DocFieldConsumerPerField> fieldToFlush : fieldsToFlush.entrySet()) {
+ DocInverterPerField perField = (DocInverterPerField) fieldToFlush.getValue();
+ childFieldsToFlush.put(fieldToFlush.getKey(), perField.consumer);
+ endChildFieldsToFlush.put(fieldToFlush.getKey(), perField.endConsumer);
+ }
-
+
- DocInverterPerThread perThread = (DocInverterPerThread) entry.getKey();
+ consumer.flush(childFieldsToFlush, state);
+ endConsumer.flush(endChildFieldsToFlush, state);
+ }
-
+
- Collection<InvertedDocConsumerPerField> childFields = new HashSet<InvertedDocConsumerPerField>();
- Collection<InvertedDocEndConsumerPerField> endChildFields = new HashSet<InvertedDocEndConsumerPerField>();
- for (final DocFieldConsumerPerField field: entry.getValue() ) {
- DocInverterPerField perField = (DocInverterPerField) field;
- childFields.add(perField.consumer);
- endChildFields.add(perField.endConsumer);
- }
+ @Override
+ public void startDocument() throws IOException {
+ consumer.startDocument();
+ endConsumer.startDocument();
+ }
- @Override
- childThreadsAndFields.put(perThread.consumer, childFields);
- endChildThreadsAndFields.put(perThread.endConsumer, endChildFields);
- }
-
- consumer.flush(childThreadsAndFields, state);
- endConsumer.flush(endChildThreadsAndFields, state);
+ public void finishDocument() throws IOException {
+ // TODO: allow endConsumer.finishDocument to also return
+ // a DocWriter
+ endConsumer.finishDocument();
+ consumer.finishDocument();
}
@Override
@@@ -115,10 -83,9 +114,10 @@@
public boolean freeRAM() {
return consumer.freeRAM();
}
-
+
@Override
- public DocFieldConsumerPerThread addThread(DocFieldProcessorPerThread docFieldProcessorPerThread) {
- return new DocInverterPerThread(docFieldProcessorPerThread, this);
+ public DocFieldConsumerPerField addField(FieldInfo fi) {
+ return new DocInverterPerField(this, fi);
}
+
}
diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
index bcc2d4ed20a,7461ce52fa9..d0edac225c0
--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
@@@ -1,683 -1,1161 +1,617 @@@
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.io.PrintStream;
-import java.text.NumberFormat;
-import java.util.ArrayList;
import java.util.Collection;
--import java.util.HashMap;
--import java.util.HashSet;
+import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
- import java.util.SortedMap;
- import java.util.TreeMap;
+ import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
- import org.apache.lucene.search.IndexSearcher;
++import org.apache.lucene.index.DocumentsWriterPerThread.IndexingChain;
import org.apache.lucene.search.Query;
- import org.apache.lucene.search.Scorer;
- import org.apache.lucene.search.Weight;
+ import org.apache.lucene.search.Similarity;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
- import org.apache.lucene.store.FilterDirectory;
- import org.apache.lucene.store.IndexOutput;
- import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.store.RAMFile;
-import org.apache.lucene.util.ArrayUtil;
-import org.apache.lucene.util.RecyclingByteBlockAllocator;
-import org.apache.lucene.util.ThreadInterruptedException;
-import org.apache.lucene.util.RamUsageEstimator;
-import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_MASK;
-import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE;
/**
- * 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.
+ * This class accepts multiple added documents and directly
+ * writes a single segment file. It does this more
+ * efficiently than creating a single segment per document
+ * (with DocumentWriter) and doing standard merges on those
+ * segments.
+ *
+ * Each added document is passed to the {@link DocConsumer},
+ * which in turn processes the document and interacts with
+ * other consumers in the indexing chain. Certain
+ * consumers, like {@link StoredFieldsWriter} and {@link
+ * TermVectorsTermsWriter}, digest a document and
+ * immediately write bytes to the "doc store" files (ie,
+ * they do not consume RAM per document, except while they
+ * are processing the document).
+ *
+ * Other consumers, eg {@link FreqProxTermsWriter} and
+ * {@link NormsWriter}, buffer bytes in RAM and flush only
+ * when a new segment is produced.
+
+ * Once we have used our allowed RAM buffer, or the number
+ * of added docs is large enough (in the case we are
+ * flushing by doc count instead of RAM usage), we create a
+ * real segment and flush it to the Directory.
+ *
+ * Threads:
+ *
+ * Multiple threads are allowed into addDocument at once.
+ * There is an initial synchronized call to getThreadState
+ * which allocates a ThreadState for this thread. The same
+ * thread will get the same ThreadState over time (thread
+ * affinity) so that if there are consistent patterns (for
+ * example each thread is indexing a different content
+ * source) then we make better use of RAM. Then
+ * processDocument is called on that ThreadState without
+ * synchronization (most of the "heavy lifting" is in this
+ * call). Finally the synchronized "finishDocument" is
+ * called to flush changes to the directory.
+ *
+ * When flush is called by IndexWriter we forcefully idle
+ * all threads and flush only once they are all idle. This
+ * means you can call flush with a given thread even while
+ * other threads are actively adding/deleting documents.
+ *
+ *
+ * Exceptions:
+ *
+ * Because this class directly updates in-memory posting
+ * lists, and flushes stored fields and term vectors
+ * directly to files in the directory, there are certain
+ * limited times when an exception can corrupt this state.
+ * For example, a disk full while flushing stored fields
+ * leaves this file in a corrupt state. Or, an OOM
+ * exception while appending to the in-memory posting lists
+ * can corrupt that posting list. We call such exceptions
+ * "aborting exceptions". In these cases we must call
+ * abort() to discard all docs added since the last flush.
+ *
+ * All other exceptions ("non-aborting exceptions") can
+ * still partially update the index structures. These
+ * updates are consistent, but, they represent only a part
+ * of the document seen up until the exception was hit.
+ * When this happens, we immediately mark the document as
+ * deleted so that the document is always atomically ("all
+ * or none") added to the index.
*/
final class DocumentsWriter {
- private long sequenceID;
- private int numDocumentsWriterPerThreads;
+ final AtomicLong bytesUsed = new AtomicLong(0);
- IndexWriter writer;
+ Directory directory;
- private final BufferedDeletesInRAM deletesInRAM = new BufferedDeletesInRAM();
- private final DocumentsWriterThreadPool threadPool;
- private final Lock sequenceIDLock = new ReentrantLock();
- String segment; // Current segment we are working on
-
- private int nextDocID; // Next docID to be added
- private int numDocs; // # of docs added, but not yet flushed
-
- // Max # ThreadState instances; if there are more threads
- // than this they share ThreadStates
- private DocumentsWriterThreadState[] threadStates = new DocumentsWriterThreadState[0];
- private final HashMap<Thread,DocumentsWriterThreadState> threadBindings = new HashMap<Thread,DocumentsWriterThreadState>();
++ int numDocsInStore; // # docs written to doc stores
- private final Directory openFilesTrackingDirectory;
- final IndexWriter indexWriter;
- final IndexWriterConfig config;
+ boolean bufferIsFull; // True when it's time to write segment
- private boolean aborting; // True if an abort is pending
++ private boolean closed;
- private int maxBufferedDocs;
- private double maxBufferSizeMB;
- private int maxBufferedDeleteTerms;
+ PrintStream infoStream;
+ int maxFieldLength = IndexWriterConfig.UNLIMITED_FIELD_LENGTH;
+ Similarity similarity;
+
- // max # simultaneous threads; if there are more than
- // this, they wait for others to finish first
- private final int maxThreadStates;
++ List<String> newFiles;
++
++ private final DocumentsWriterThreadPool threadPool;
++ final IndexWriter indexWriter;
++ private final Lock sequenceIDLock = new ReentrantLock();
+
- private boolean closed;
+ private AtomicInteger numDocsInRAM = new AtomicInteger(0);
+ private AtomicLong ramUsed = new AtomicLong(0);
++ private int numDocumentsWriterPerThreads;
+
- // Deletes for our still-in-RAM (to be flushed next) segment
- private SegmentDeletes pendingDeletes = new SegmentDeletes();
-
+ static class DocState {
+ DocumentsWriter docWriter;
+ Analyzer analyzer;
+ int maxFieldLength;
+ PrintStream infoStream;
+ Similarity similarity;
+ int docID;
+ Document doc;
+ String maxTermPrefix;
+
+ // Only called by asserts
+ public boolean testPoint(String name) {
- return docWriter.writer.testPoint(name);
++ return docWriter.indexWriter.testPoint(name);
+ }
- private long flushedSequenceID = -1;
- private final PrintStream infoStream;
+ public void clear() {
+ // don't hold onto doc nor analyzer, in case it is
+ // largish:
+ doc = null;
+ analyzer = null;
+ }
+ }
- private Map<DocumentsWriterPerThread, Long> minSequenceIDsPerThread = new HashMap<DocumentsWriterPerThread, Long>();
- /** Consumer returns this on each doc. This holds any
- * state that must be flushed synchronized "in docID
- * order". We gather these and flush them in order. */
- abstract static class DocWriter {
- DocWriter next;
- int docID;
- abstract void finish() throws IOException;
- abstract void abort();
- abstract long sizeInBytes();
-
- void setNext(DocWriter next) {
- this.next = next;
- }
- }
-
- /**
- * Create and return a new DocWriterBuffer.
- */
- PerDocBuffer newPerDocBuffer() {
- return new PerDocBuffer();
- }
-
- /**
- * RAMFile buffer for DocWriters.
- */
- @SuppressWarnings("serial")
- class PerDocBuffer extends RAMFile {
-
- /**
- * Allocate bytes used from shared pool.
- */
- protected byte[] newBuffer(int size) {
- assert size == PER_DOC_BLOCK_SIZE;
- return perDocAllocator.getByteBlock();
- }
-
- /**
- * Recycle the bytes used.
- */
- synchronized void recycle() {
- if (buffers.size() > 0) {
- setLength(0);
-
- // Recycle the blocks
- perDocAllocator.recycleByteBlocks(buffers);
- buffers.clear();
- sizeInBytes = 0;
-
- assert numBuffers() == 0;
- }
- }
- }
-
- /**
- * 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(DocumentsWriter documentsWriter);
- }
-
- static final IndexingChain defaultIndexingChain = new IndexingChain() {
-
- @Override
- DocConsumer getChain(DocumentsWriter documentsWriter) {
- /*
- 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(documentsWriter);
- final TermsHashConsumer freqProxWriter = new FreqProxTermsWriter();
- /*
- * nesting TermsHash instances here to allow the secondary (TermVectors) share the interned postings
- * via a shared ByteBlockPool. See TermsHashPerField for details.
- */
- final TermsHash termVectorsTermHash = new TermsHash(documentsWriter, false, termVectorsWriter, null);
- final InvertedDocConsumer termsHash = new TermsHash(documentsWriter, true, freqProxWriter, termVectorsTermHash);
- final NormsWriter normsWriter = new NormsWriter();
- final DocInverter docInverter = new DocInverter(termsHash, normsWriter);
- return new DocFieldProcessor(documentsWriter, docInverter);
- }
- };
-
- final DocConsumer consumer;
-
+ // How much RAM we can use before flushing. This is 0 if
+ // we are flushing by doc count instead.
+ private long ramBufferSize = (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024);
- private long waitQueuePauseBytes = (long) (ramBufferSize*0.1);
- private long waitQueueResumeBytes = (long) (ramBufferSize*0.05);
- public DocumentsWriter(Directory directory, IndexWriter indexWriter, IndexWriterConfig config) {
- this.openFilesTrackingDirectory = new FilterDirectory(directory) {
- @Override public IndexOutput createOutput(final String name) throws IOException {
- addOpenFile(name);
- return super.createOutput(name);
- }
- };
+ // If we've allocated 5% over our RAM budget, we then
+ // free down to 95%
+ private long freeLevel = (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024*0.95);
+
+ // Flush @ this number of docs. If ramBufferSize is
+ // non-zero we will flush by RAM usage instead.
+ private int maxBufferedDocs = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS;
+
- private boolean closed;
+ private final FieldInfos fieldInfos;
+
- private final BufferedDeletes bufferedDeletes;
++ final BufferedDeletes bufferedDeletes;
+ private final IndexWriter.FlushControl flushControl;
++ private final IndexingChain chain;
+
- DocumentsWriter(Directory directory, IndexWriter writer, IndexingChain indexingChain, int maxThreadStates, FieldInfos fieldInfos, BufferedDeletes bufferedDeletes) throws IOException {
++ DocumentsWriter(Directory directory, IndexWriter writer, IndexingChain chain, DocumentsWriterThreadPool indexerThreadPool, FieldInfos fieldInfos, BufferedDeletes bufferedDeletes) throws IOException {
+ this.directory = directory;
- this.writer = writer;
++ this.indexWriter = writer;
+ this.similarity = writer.getConfig().getSimilarity();
- this.maxThreadStates = maxThreadStates;
+ this.fieldInfos = fieldInfos;
+ this.bufferedDeletes = bufferedDeletes;
++ this.threadPool = indexerThreadPool;
++ this.chain = chain;
+ flushControl = writer.flushControl;
-
- consumer = indexingChain.getChain(this);
+ }
+
- // Buffer a specific docID for deletion. Currently only
- // used when we hit a exception when adding a document
- synchronized 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).
- }
-
+ boolean deleteQueries(Query... queries) {
+ final boolean doFlush = flushControl.waitUpdate(0, queries.length);
- synchronized(this) {
- for (Query query : queries) {
- pendingDeletes.addQuery(query, numDocs);
- }
++ Iterator<DocumentsWriterPerThread> it = threadPool.getPerThreadIterator();
++ while (it.hasNext()) {
++ it.next().deleteQueries(queries);
+ }
+ return doFlush;
+ }
-
- boolean deleteQuery(Query query) {
++
++ boolean deleteQuery(Query query) {
+ final boolean doFlush = flushControl.waitUpdate(0, 1);
- synchronized(this) {
- pendingDeletes.addQuery(query, numDocs);
++ Iterator<DocumentsWriterPerThread> it = threadPool.getPerThreadIterator();
++ while (it.hasNext()) {
++ it.next().deleteQuery(query);
+ }
+ return doFlush;
+ }
-
++
+ boolean deleteTerms(Term... terms) {
+ final boolean doFlush = flushControl.waitUpdate(0, terms.length);
- synchronized(this) {
- for (Term term : terms) {
- pendingDeletes.addTerm(term, numDocs);
- }
++ Iterator<DocumentsWriterPerThread> it = threadPool.getPerThreadIterator();
++ while (it.hasNext()) {
++ it.next().deleteTerms(terms);
+ }
+ return doFlush;
+ }
+
+ boolean deleteTerm(Term term, boolean skipWait) {
+ final boolean doFlush = flushControl.waitUpdate(0, 1, skipWait);
- synchronized(this) {
- pendingDeletes.addTerm(term, numDocs);
++ Iterator<DocumentsWriterPerThread> it = threadPool.getPerThreadIterator();
++ while (it.hasNext()) {
++ it.next().deleteTerm(term);
+ }
+ return doFlush;
+ }
+
+ public FieldInfos getFieldInfos() {
+ return fieldInfos;
+ }
+
++ /** Returns true if any of the fields in the current
++ * buffered docs have omitTermFreqAndPositions==false */
++ boolean hasProx() {
++ return fieldInfos.hasProx();
++ }
++
+ /** If non-null, various details of indexing are printed
+ * here. */
+ synchronized void setInfoStream(PrintStream infoStream) {
+ this.infoStream = infoStream;
- for(int i=0;i<threadStates.length;i++) {
- threadStates[i].docState.infoStream = infoStream;
++ Iterator<DocumentsWriterPerThread> it = threadPool.getPerThreadIterator();
++ while (it.hasNext()) {
++ it.next().docState.infoStream = infoStream;
+ }
+ }
+
+ synchronized void setMaxFieldLength(int maxFieldLength) {
+ this.maxFieldLength = maxFieldLength;
- for(int i=0;i<threadStates.length;i++) {
- threadStates[i].docState.maxFieldLength = maxFieldLength;
++ Iterator<DocumentsWriterPerThread> it = threadPool.getPerThreadIterator();
++ while (it.hasNext()) {
++ it.next().docState.maxFieldLength = maxFieldLength;
+ }
+ }
+
+ synchronized void setSimilarity(Similarity similarity) {
+ this.similarity = similarity;
- for(int i=0;i<threadStates.length;i++) {
- threadStates[i].docState.similarity = similarity;
++ Iterator<DocumentsWriterPerThread> it = threadPool.getPerThreadIterator();
++ while (it.hasNext()) {
++ it.next().docState.similarity = similarity;
+ }
+ }
+
+ /** Set how much RAM we can use before flushing. */
+ synchronized void setRAMBufferSizeMB(double mb) {
+ if (mb == IndexWriterConfig.DISABLE_AUTO_FLUSH) {
+ ramBufferSize = IndexWriterConfig.DISABLE_AUTO_FLUSH;
- waitQueuePauseBytes = 4*1024*1024;
- waitQueueResumeBytes = 2*1024*1024;
+ } else {
+ ramBufferSize = (long) (mb*1024*1024);
- waitQueuePauseBytes = (long) (ramBufferSize*0.1);
- waitQueueResumeBytes = (long) (ramBufferSize*0.05);
+ freeLevel = (long) (0.95 * ramBufferSize);
+ }
+ }
- //this.openFilesTrackingDirectory = directory;
- this.indexWriter = indexWriter;
- this.config = config;
- this.maxBufferedDocs = config.getMaxBufferedDocs();
- this.threadPool = config.getIndexerThreadPool();
- this.infoStream = indexWriter.getInfoStream();
+ synchronized double getRAMBufferSizeMB() {
+ if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH) {
+ return ramBufferSize;
+ } else {
+ return ramBufferSize/1024./1024.;
+ }
}
- public int getMaxBufferedDocs() {
+ /** Set max buffered docs, which means we will flush by
+ * doc count instead of by RAM usage. */
+ void setMaxBufferedDocs(int count) {
+ maxBufferedDocs = count;
+ }
+
+ int getMaxBufferedDocs() {
return maxBufferedDocs;
}
- public void setMaxBufferedDocs(int max) {
- this.maxBufferedDocs = max;
- /** Get current segment name we are writing. */
- synchronized String getSegment() {
- return segment;
++ /** Returns how many docs are currently buffered in RAM. */
++ int getNumDocs() {
++ return numDocsInRAM.get();
}
++ private Collection<String> abortedFiles; // List of files that were written before last abort()
- public double getRAMBufferSizeMB() {
- return maxBufferSizeMB;
- /** Returns how many docs are currently buffered in RAM. */
- synchronized int getNumDocs() {
- return numDocs;
++ Collection<String> abortedFiles() {
++ return abortedFiles;
}
- public void setRAMBufferSizeMB(double mb) {
- this.maxBufferSizeMB = mb;
+ void message(String message) {
- if (infoStream != null) {
- writer.message("DW: " + message);
- }
++ if (infoStream != null)
++ indexWriter.message("DW: " + message);
}
- public int getMaxBufferedDeleteTerms() {
- return maxBufferedDeleteTerms;
- synchronized void setAborting() {
- if (infoStream != null) {
- message("setAborting");
++ private void ensureOpen() throws AlreadyClosedException {
++ if (closed) {
++ throw new AlreadyClosedException("this IndexWriter is closed");
+ }
- aborting = true;
}
- public void setMaxBufferedDeleteTerms(int max) {
- this.maxBufferedDeleteTerms = max;
+ /** 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. */
+ synchronized void abort() throws IOException {
+ if (infoStream != null) {
+ message("docWriter: abort");
+ }
+
+ boolean success = false;
-
+ try {
+
- // Forcefully remove waiting ThreadStates from line
- waitQueue.abort();
-
- // Wait for all other threads to finish with
- // DocumentsWriter:
- waitIdle();
-
- if (infoStream != null) {
- message("docWriter: abort waitIdle done");
- }
-
- assert 0 == waitQueue.numWaiting: "waitQueue.numWaiting=" + waitQueue.numWaiting;
-
- waitQueue.waitingBytes = 0;
-
- pendingDeletes.clear();
-
- for (DocumentsWriterThreadState threadState : threadStates)
- try {
- threadState.consumer.abort();
- } catch (Throwable t) {
- }
-
- try {
- consumer.abort();
- } catch (Throwable t) {
- }
-
- // Reset all postings data
- doAfterFlush();
++ threadPool.abort();
+ success = true;
+ } finally {
- aborting = false;
+ notifyAll();
+ if (infoStream != null) {
- message("docWriter: done abort; success=" + success);
- }
- }
- }
-
- /** Reset after a flush */
- private void doAfterFlush() throws IOException {
- // All ThreadStates should be idle when we are called
- assert allThreadsIdle();
- threadBindings.clear();
- waitQueue.reset();
- segment = null;
- numDocs = 0;
- nextDocID = 0;
- bufferIsFull = false;
- for(int i=0;i<threadStates.length;i++) {
- threadStates[i].doAfterFlush();
- }
- }
-
- private synchronized boolean allThreadsIdle() {
- for(int i=0;i<threadStates.length;i++) {
- if (!threadStates[i].isIdle) {
- return false;
++ message("docWriter: done abort; abortedFiles=" + abortedFiles + " success=" + success);
+ }
+ }
- return true;
}
- private final long nextSequenceID() {
- return sequenceID++;
+ synchronized boolean anyChanges() {
- return numDocs != 0 || pendingDeletes.any();
++ // nocommit
++ return numDocsInRAM.get() != 0;
++ //return numDocsInRAM.get() != 0 || pendingDeletes.any();
}
-
- boolean anyChanges() {
- return numDocsInRAM.get() != 0 ||
- deletesInRAM.hasDeletes();
+
+ // for testing
+ public SegmentDeletes getPendingDeletes() {
- return pendingDeletes;
- }
-
- private void pushDeletes(SegmentInfo newSegment, SegmentInfos segmentInfos) {
- // Lock order: DW -> BD
- if (pendingDeletes.any()) {
- if (newSegment != null) {
- if (infoStream != null) {
- message("flush: push buffered deletes to newSegment");
- }
- bufferedDeletes.pushDeletes(pendingDeletes, newSegment);
- } else if (segmentInfos.size() > 0) {
- if (infoStream != null) {
- message("flush: push buffered deletes to previously flushed segment " + segmentInfos.lastElement());
- }
- bufferedDeletes.pushDeletes(pendingDeletes, segmentInfos.lastElement(), true);
- } else {
- if (infoStream != null) {
- message("flush: drop buffered deletes: no segments");
- }
- // We can safely discard these deletes: since
- // there are no segments, the deletions cannot
- // affect anything.
- }
- pendingDeletes = new SegmentDeletes();
- }
++ return null;
++ // nocommit
++ //return pendingDeletes;
+ }
+
+ public boolean anyDeletions() {
- return pendingDeletes.any();
- }
-
- /** Flush all pending docs to a new segment */
- // Lock order: IW -> DW
- synchronized SegmentInfo flush(IndexWriter writer, IndexFileDeleter deleter, MergePolicy mergePolicy, SegmentInfos segmentInfos) throws IOException {
-
- // We change writer's segmentInfos:
- assert Thread.holdsLock(writer);
-
- waitIdle();
-
- if (numDocs == 0) {
- // nothing to do!
- if (infoStream != null) {
- message("flush: no docs; skipping");
- }
- // Lock order: IW -> DW -> BD
- pushDeletes(null, segmentInfos);
- return null;
- }
-
- if (aborting) {
- if (infoStream != null) {
- message("flush: skip because aborting is set");
- }
- return null;
- }
-
- boolean success = false;
-
- SegmentInfo newSegment;
-
- try {
- assert nextDocID == numDocs;
- assert waitQueue.numWaiting == 0;
- assert waitQueue.waitingBytes == 0;
-
- if (infoStream != null) {
- message("flush postings as segment " + segment + " numDocs=" + numDocs);
- }
-
- final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,
- numDocs, writer.getConfig().getTermIndexInterval(),
- SegmentCodecs.build(fieldInfos, writer.codecs));
-
- newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false);
-
- Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>();
- for (DocumentsWriterThreadState threadState : threadStates) {
- threads.add(threadState.consumer);
- }
-
- double startMBUsed = bytesUsed()/1024./1024.;
-
- consumer.flush(threads, flushState);
- newSegment.setHasVectors(flushState.hasVectors);
-
- if (infoStream != null) {
- message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors"));
- message("flushedFiles=" + flushState.flushedFiles);
- message("flushed codecs=" + newSegment.getSegmentCodecs());
- }
-
- if (mergePolicy.useCompoundFile(segmentInfos, newSegment)) {
- final String cfsFileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION);
-
- if (infoStream != null) {
- message("flush: create compound file \"" + cfsFileName + "\"");
- }
-
- CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, cfsFileName);
- for(String fileName : flushState.flushedFiles) {
- cfsWriter.addFile(fileName);
- }
- cfsWriter.close();
- deleter.deleteNewFiles(flushState.flushedFiles);
-
- newSegment.setUseCompoundFile(true);
- }
-
- if (infoStream != null) {
- message("flush: segment=" + newSegment);
- final double newSegmentSizeNoStore = newSegment.sizeInBytes(false)/1024./1024.;
- final double newSegmentSize = newSegment.sizeInBytes(true)/1024./1024.;
- message(" ramUsed=" + nf.format(startMBUsed) + " MB" +
- " newFlushedSize=" + nf.format(newSegmentSize) + " MB" +
- " (" + nf.format(newSegmentSizeNoStore) + " MB w/o doc stores)" +
- " docs/MB=" + nf.format(numDocs / newSegmentSize) +
- " new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startMBUsed) + "%");
- }
-
- success = true;
- } finally {
- notifyAll();
- if (!success) {
- if (segment != null) {
- deleter.refresh(segment);
- }
- abort();
- }
- }
-
- doAfterFlush();
-
- // Lock order: IW -> DW -> BD
- pushDeletes(newSegment, segmentInfos);
-
- return newSegment;
++ // nocommit
++ return true;
++ //return pendingDeletes.any();
+ }
+
+ synchronized void close() {
+ closed = true;
+ notifyAll();
}
- /** Returns a free (idle) ThreadState that may be used for
- * indexing this one document. This call also pauses if a
- * flush is pending. If delTerm is non-null then we
- * buffer this deleted term after the thread state has
- * been acquired. */
- synchronized DocumentsWriterThreadState getThreadState(Document doc, Term delTerm) throws IOException {
-
- final Thread currentThread = Thread.currentThread();
- assert !Thread.holdsLock(writer);
-
- // First, find a thread state. If this thread already
- // has affinity to a specific ThreadState, use that one
- // again.
- DocumentsWriterThreadState state = threadBindings.get(currentThread);
- if (state == null) {
-
- // First time this thread has called us since last
- // flush. Find the least loaded thread state:
- DocumentsWriterThreadState minThreadState = null;
- for(int i=0;i<threadStates.length;i++) {
- DocumentsWriterThreadState ts = threadStates[i];
- if (minThreadState == null || ts.numThreads < minThreadState.numThreads) {
- minThreadState = ts;
- }
- }
- if (minThreadState != null && (minThreadState.numThreads == 0 || threadStates.length >= maxThreadStates)) {
- state = minThreadState;
- state.numThreads++;
- } else {
- // Just create a new "private" thread state
- DocumentsWriterThreadState[] newArray = new DocumentsWriterThreadState[1+threadStates.length];
- if (threadStates.length > 0) {
- System.arraycopy(threadStates, 0, newArray, 0, threadStates.length);
- }
- state = newArray[threadStates.length] = new DocumentsWriterThreadState(this);
- threadStates = newArray;
- }
- threadBindings.put(currentThread, state);
- }
-
- // Next, wait until my thread state is idle (in case
- // it's shared with other threads), and no flush/abort
- // pending
- waitReady(state);
-
- // Allocate segment name if this is the first doc since
- // last flush:
- if (segment == null) {
- segment = writer.newSegmentName();
- assert numDocs == 0;
- }
-
- state.docState.docID = nextDocID++;
-
- if (delTerm != null) {
- pendingDeletes.addTerm(delTerm, state.docState.docID);
- }
-
- numDocs++;
- state.isIdle = false;
- return state;
- }
-
- boolean addDocument(Document doc, Analyzer analyzer) throws CorruptIndexException, IOException {
- return updateDocument(doc, analyzer, null);
- }
-
- boolean updateDocument(Document doc, Analyzer analyzer, Term delTerm)
- throws CorruptIndexException, IOException {
-
- // Possibly trigger a flush, or wait until any running flush completes:
- boolean doFlush = flushControl.waitUpdate(1, delTerm != null ? 1 : 0);
-
- // This call is synchronized but fast
- final DocumentsWriterThreadState state = getThreadState(doc, delTerm);
-
- final DocState docState = state.docState;
- docState.doc = doc;
- docState.analyzer = analyzer;
-
- boolean success = false;
+ DocumentsWriterPerThread newDocumentsWriterPerThread() {
- DocumentsWriterPerThread perThread = new DocumentsWriterPerThread(openFilesTrackingDirectory, this, config
- .getIndexingChain());
++ DocumentsWriterPerThread perThread = new DocumentsWriterPerThread(directory, this, chain);
+ sequenceIDLock.lock();
try {
- // This call is not synchronized and does all the
- // work
- final DocWriter perDoc;
- try {
- perDoc = state.consumer.processDocument();
- } finally {
- docState.clear();
- }
-
- // This call is synchronized but fast
- finishDocument(state, perDoc);
-
- success = true;
+ numDocumentsWriterPerThreads++;
+ return perThread;
} finally {
- if (!success) {
-
- // If this thread state had decided to flush, we
- // must clear it so another thread can flush
- if (doFlush) {
- flushControl.clearFlushPending();
- }
+ sequenceIDLock.unlock();
+ }
+ }
- long addDocument(final Document doc, final Analyzer analyzer)
- if (infoStream != null) {
- message("exception in updateDocument aborting=" + aborting);
- }
++ boolean updateDocument(final Document doc, final Analyzer analyzer, final Term delTerm)
+ throws CorruptIndexException, IOException {
- return updateDocument(null, doc, analyzer);
- }
- private final static class UpdateResult {
- long sequenceID;
- boolean flushed;
-
- UpdateResult(long sequenceID) {
- this.sequenceID = sequenceID;
- flushed = false;
- }
- }
-
- long updateDocument(final Term delTerm, final Document doc, final Analyzer analyzer)
- throws CorruptIndexException, IOException {
-
- UpdateResult result = threadPool.executePerThread(this, doc,
- new DocumentsWriterThreadPool.PerThreadTask<UpdateResult>() {
- synchronized(this) {
++ boolean flushed = threadPool.executePerThread(this, doc,
++ new DocumentsWriterThreadPool.PerThreadTask<Boolean>() {
+ @Override
- public UpdateResult process(final DocumentsWriterPerThread perThread) throws IOException {
- long perThreadRAMUsedBeforeAdd = perThread.numBytesUsed;
++ public Boolean process(final DocumentsWriterPerThread perThread) throws IOException {
++ long perThreadRAMUsedBeforeAdd = perThread.bytesUsed();
+ perThread.addDocument(doc, analyzer);
- final long sequenceID;
- state.isIdle = true;
- notifyAll();
-
- if (aborting) {
- abort();
- } else {
- skipDocWriter.docID = docState.docID;
- boolean success2 = false;
+ sequenceIDLock.lock();
try {
- waitQueue.add(skipDocWriter);
- success2 = true;
- } finally {
- if (!success2) {
- abort();
- return false;
+ ensureOpen();
- sequenceID = nextSequenceID();
+ if (delTerm != null) {
- deletesInRAM.addDeleteTerm(delTerm, sequenceID, numDocumentsWriterPerThreads);
- }
- perThread.commitDocument(sequenceID);
- if (!minSequenceIDsPerThread.containsKey(perThread)) {
- minSequenceIDsPerThread.put(perThread, sequenceID);
++ deleteTerm(delTerm, true);
}
++ perThread.commitDocument();
+ numDocsInRAM.incrementAndGet();
+ } finally {
+ sequenceIDLock.unlock();
}
- UpdateResult result = new UpdateResult(sequenceID);
- // Immediately mark this document as deleted
- // since likely it was partially added. This
- // keeps indexing as "all or none" (atomic) when
- // adding a document:
- deleteDocID(state.docState.docID);
+ if (finishAddDocument(perThread, perThreadRAMUsedBeforeAdd)) {
- result.flushed = true;
+ super.clearThreadBindings();
++ return true;
+ }
- return result;
++ return false;
}
- }
- }
- }
+ });
-
- if (result == null) {
- return -1;
- }
-
- if (result.flushed) {
+
- doFlush |= flushControl.flushByRAMUsage("new document");
++ if (flushed) {
+ indexWriter.maybeMerge();
++ return true;
+ }
- return result.sequenceID;
+
- return doFlush;
++ return false;
}
- public synchronized void waitIdle() {
- while (!allThreadsIdle()) {
- try {
- wait();
- } catch (InterruptedException ie) {
- throw new ThreadInterruptedException(ie);
+ private final boolean finishAddDocument(DocumentsWriterPerThread perThread,
+ long perThreadRAMUsedBeforeAdd) throws IOException {
+ int numDocsPerThread = perThread.getNumDocsInRAM();
+ boolean flushed = maybeFlushPerThread(perThread);
+ if (flushed) {
+ int oldValue = numDocsInRAM.get();
+ while (!numDocsInRAM.compareAndSet(oldValue, oldValue - numDocsPerThread)) {
+ oldValue = numDocsInRAM.get();
}
-
- sequenceIDLock.lock();
- try {
- minSequenceIDsPerThread.remove(perThread);
- updateFlushedSequenceID();
- } finally {
- sequenceIDLock.unlock();
- }
}
- }
- long deltaRAM = perThread.numBytesUsed - perThreadRAMUsedBeforeAdd;
- synchronized void waitReady(DocumentsWriterThreadState state) {
- while (!closed && (!state.isIdle || aborting)) {
- try {
- wait();
- } catch (InterruptedException ie) {
- throw new ThreadInterruptedException(ie);
- }
++ long deltaRAM = perThread.bytesUsed() - perThreadRAMUsedBeforeAdd;
+ long oldValue = ramUsed.get();
+ while (!ramUsed.compareAndSet(oldValue, oldValue + deltaRAM)) {
+ oldValue = ramUsed.get();
}
- if (closed) {
- throw new AlreadyClosedException("this IndexWriter is closed");
- }
+ return flushed;
}
- long bufferDeleteTerms(final Term[] terms) throws IOException {
- sequenceIDLock.lock();
- try {
- ensureOpen();
- final long sequenceID = nextSequenceID();
- deletesInRAM.addDeleteTerms(terms, sequenceID, numDocumentsWriterPerThreads);
- return sequenceID;
- } finally {
- sequenceIDLock.unlock();
- /** Does the synchronized work to finish/flush the
- * inverted document. */
- private void finishDocument(DocumentsWriterThreadState perThread, DocWriter docWriter) throws IOException {
-
- // Must call this w/o holding synchronized(this) else
- // we'll hit deadlock:
- balanceRAM();
-
- synchronized(this) {
-
- assert docWriter == null || docWriter.docID == perThread.docState.docID;
-
- if (aborting) {
-
- // We are currently aborting, and another thread is
- // waiting for me to become idle. We just forcefully
- // idle this threadState; it will be fully reset by
- // abort()
- if (docWriter != null) {
- try {
- docWriter.abort();
- } catch (Throwable t) {
- }
- }
-
- perThread.isIdle = true;
-
- // wakes up any threads waiting on the wait queue
- notifyAll();
-
- return;
- }
-
- final boolean doPause;
-
- if (docWriter != null) {
- doPause = waitQueue.add(docWriter);
- } else {
- skipDocWriter.docID = perThread.docState.docID;
- doPause = waitQueue.add(skipDocWriter);
- }
-
- if (doPause) {
- waitForWaitQueue();
- }
-
- perThread.isIdle = true;
-
- // wakes up any threads waiting on the wait queue
- notifyAll();
++ private boolean flushSegment(DocumentsWriterPerThread perThread) throws IOException {
++ if (perThread.getNumDocsInRAM() == 0) {
++ return false;
}
-- }
- long bufferDeleteTerm(final Term term) throws IOException {
- sequenceIDLock.lock();
- try {
- ensureOpen();
- final long sequenceID = nextSequenceID();
- deletesInRAM.addDeleteTerm(term, sequenceID, numDocumentsWriterPerThreads);
- return sequenceID;
- } finally {
- sequenceIDLock.unlock();
- }
- synchronized void waitForWaitQueue() {
- do {
- try {
- wait();
- } catch (InterruptedException ie) {
- throw new ThreadInterruptedException(ie);
- }
- } while (!waitQueue.doResume());
-- }
++ SegmentInfo newSegment = perThread.flush();
++ newSegment.dir = indexWriter.getDirectory();
- long bufferDeleteQueries(final Query[] queries) throws IOException {
- sequenceIDLock.lock();
- try {
- ensureOpen();
- final long sequenceID = nextSequenceID();
- for (Query q : queries) {
- deletesInRAM.addDeleteQuery(q, sequenceID, numDocumentsWriterPerThreads);
- }
- return sequenceID;
- } finally {
- sequenceIDLock.unlock();
- private static class SkipDocWriter extends DocWriter {
- @Override
- void finish() {
- }
- @Override
- void abort() {
- }
- @Override
- long sizeInBytes() {
- return 0;
-- }
++ finishFlushedSegment(newSegment, perThread);
++ return true;
}
- final SkipDocWriter skipDocWriter = new SkipDocWriter();
-
- NumberFormat nf = NumberFormat.getInstance();
-
- /* Initial chunks size of the shared byte[] blocks used to
- store postings data */
- final static int BYTE_BLOCK_NOT_MASK = ~BYTE_BLOCK_MASK;
- long bufferDeleteQuery(final Query query) throws IOException {
- sequenceIDLock.lock();
- try {
- ensureOpen();
- final long sequenceID = nextSequenceID();
- deletesInRAM.addDeleteQuery(query, sequenceID, numDocumentsWriterPerThreads);
- return sequenceID;
- } finally {
- sequenceIDLock.unlock();
- }
- }
- /* 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;
++ private final boolean maybeFlushPerThread(DocumentsWriterPerThread perThread) throws IOException {
++ if (perThread.getNumDocsInRAM() == maxBufferedDocs) {
++ flushSegment(perThread);
++ assert perThread.getNumDocsInRAM() == 0;
- private final void updateFlushedSequenceID() {
- long newFlushedID = Long.MAX_VALUE;
- for (long minSeqIDPerThread : minSequenceIDsPerThread.values()) {
- if (minSeqIDPerThread < newFlushedID) {
- newFlushedID = minSeqIDPerThread;
- }
- /* 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;
-
- private List<int[]> freeIntBlocks = new ArrayList<int[]>();
-
- /* Allocate another int[] from the shared pool */
- synchronized int[] getIntBlock() {
- final int size = freeIntBlocks.size();
- final int[] b;
- if (0 == size) {
- b = new int[INT_BLOCK_SIZE];
- bytesUsed.addAndGet(INT_BLOCK_SIZE*RamUsageEstimator.NUM_BYTES_INT);
- } else {
- b = freeIntBlocks.remove(size-1);
++ return true;
}
- return b;
- }
- this.flushedSequenceID = newFlushedID;
- long bytesUsed() {
- return bytesUsed.get() + pendingDeletes.bytesUsed.get();
++ return false;
}
- /* Return int[]s to the pool */
- synchronized void recycleIntBlocks(int[][] blocks, int start, int end) {
- for(int i=start;i<end;i++) {
- freeIntBlocks.add(blocks[i]);
- blocks[i] = null;
- }
- }
+ final boolean flushAllThreads(final boolean flushDeletes)
- throws IOException {
-
++ throws IOException {
+
- final RecyclingByteBlockAllocator byteBlockAllocator = new RecyclingByteBlockAllocator(BYTE_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);
+ return threadPool.executeAllThreads(this, new DocumentsWriterThreadPool.AllThreadsTask<Boolean>() {
+ @Override
+ public Boolean process(Iterator<DocumentsWriterPerThread> threadsIterator) throws IOException {
+ boolean anythingFlushed = false;
-
+
- final static int PER_DOC_BLOCK_SIZE = 1024;
+ while (threadsIterator.hasNext()) {
+ DocumentsWriterPerThread perThread = threadsIterator.next();
+ final int numDocs = perThread.getNumDocsInRAM();
-
+
- final RecyclingByteBlockAllocator perDocAllocator = new RecyclingByteBlockAllocator(PER_DOC_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);
+ // Always flush docs if there are any
+ boolean flushDocs = numDocs > 0;
-
+
- String toMB(long v) {
- return nf.format(v/1024./1024.);
- }
+ String segment = perThread.getSegment();
- /* We have three pools of RAM: Postings, byte blocks
- * (holds freq/prox posting data) and per-doc buffers
- * (stored fields/term vectors). Different docs require
- * varying amount of storage from these classes. For
- * example, docs with many unique single-occurrence short
- * terms will use up the Postings RAM and hardly any of
- * the other two. Whereas docs with very large terms will
- * use alot of byte blocks RAM. This method just frees
- * allocations from the pools once we are over-budget,
- * which balances the pools to match the current docs. */
- void balanceRAM() {
-
- final boolean doBalance;
- final long deletesRAMUsed;
-
- deletesRAMUsed = bufferedDeletes.bytesUsed();
-
- synchronized(this) {
- if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH || bufferIsFull) {
- return;
- }
-
- doBalance = bytesUsed() + deletesRAMUsed >= ramBufferSize;
- }
+ // If we are flushing docs, segment must not be null:
+ assert segment != null || !flushDocs;
-
+
- if (doBalance) {
+ if (flushDocs) {
+ SegmentInfo newSegment = perThread.flush();
+ newSegment.dir = indexWriter.getDirectory();
-
+
- if (infoStream != null) {
- message(" RAM: balance allocations: usedMB=" + toMB(bytesUsed()) +
- " vs trigger=" + toMB(ramBufferSize) +
- " deletesMB=" + toMB(deletesRAMUsed) +
- " byteBlockFree=" + toMB(byteBlockAllocator.bytesUsed()) +
- " perDocFree=" + toMB(perDocAllocator.bytesUsed()));
- }
+ if (newSegment != null) {
+ anythingFlushed = true;
-
+
- final long startBytesUsed = bytesUsed() + deletesRAMUsed;
-
- int iter = 0;
-
- // We free equally from each pool in 32 KB
- // chunks until we are below our threshold
- // (freeLevel)
-
- boolean any = true;
-
- while(bytesUsed()+deletesRAMUsed > freeLevel) {
-
- synchronized(this) {
- if (0 == perDocAllocator.numBufferedBlocks() &&
- 0 == byteBlockAllocator.numBufferedBlocks() &&
- 0 == freeIntBlocks.size() && !any) {
- // Nothing else to free -- must flush now.
- bufferIsFull = bytesUsed()+deletesRAMUsed > ramBufferSize;
- if (infoStream != null) {
- if (bytesUsed()+deletesRAMUsed > ramBufferSize) {
- message(" nothing to free; set bufferIsFull");
- } else {
- message(" nothing to free");
- }
+ IndexWriter.setDiagnostics(newSegment, "flush");
+ finishFlushedSegment(newSegment, perThread);
}
- break;
- }
-
- if ((0 == iter % 4) && byteBlockAllocator.numBufferedBlocks() > 0) {
- byteBlockAllocator.freeBlocks(1);
- }
- if ((1 == iter % 4) && freeIntBlocks.size() > 0) {
- freeIntBlocks.remove(freeIntBlocks.size()-1);
- bytesUsed.addAndGet(-INT_BLOCK_SIZE * RamUsageEstimator.NUM_BYTES_INT);
- }
- if ((2 == iter % 4) && perDocAllocator.numBufferedBlocks() > 0) {
- perDocAllocator.freeBlocks(32); // Remove upwards of 32 blocks (each block is 1K)
++ } else if (flushDeletes) {
++ perThread.pushDeletes(null, indexWriter.segmentInfos);
}
}
- if ((3 == iter % 4) && any) {
- // Ask consumer to free any recycled state
- any = consumer.freeRAM();
+ if (anythingFlushed) {
+ clearThreadBindings();
-
- sequenceIDLock.lock();
- try {
- flushedSequenceID = sequenceID;
- } finally {
- sequenceIDLock.unlock();
- }
+ numDocsInRAM.set(0);
}
-
- if (flushDeletes) {
- deletesInRAM.clear();
- }
-
- iter++;
- }
-
- if (infoStream != null) {
- message(" after free: freedMB=" + nf.format((startBytesUsed-bytesUsed()-deletesRAMUsed)/1024./1024.) + " usedMB=" + nf.format((bytesUsed()+deletesRAMUsed)/1024./1024.));
+ return anythingFlushed;
}
- }
+ });
}
- final WaitQueue waitQueue = new WaitQueue();
-
- private class WaitQueue {
- DocWriter[] waiting;
- int nextWriteDocID;
- int nextWriteLoc;
- int numWaiting;
- long waitingBytes;
-
- public WaitQueue() {
- waiting = new DocWriter[10];
+ /** Build compound file for the segment we just flushed */
+ void createCompoundFile(String compoundFileName, DocumentsWriterPerThread perThread) throws IOException {
- CompoundFileWriter cfsWriter = new CompoundFileWriter(openFilesTrackingDirectory, compoundFileName);
++ CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, compoundFileName);
+ for(String fileName : perThread.flushState.flushedFiles) {
+ cfsWriter.addFile(fileName);
}
-
+
- synchronized void reset() {
- // NOTE: nextWriteLoc doesn't need to be reset
- assert numWaiting == 0;
- assert waitingBytes == 0;
- nextWriteDocID = 0;
- }
+ // Perform the merge
+ cfsWriter.close();
+ }
- synchronized boolean doResume() {
- return waitingBytes <= waitQueueResumeBytes;
- }
+ void finishFlushedSegment(SegmentInfo newSegment, DocumentsWriterPerThread perThread) throws IOException {
- SegmentReader reader = indexWriter.readerPool.get(newSegment, false);
- try {
- applyDeletes(reader, newSegment.getMinSequenceID(), newSegment.getMaxSequenceID(), perThread.sequenceIDs);
- } finally {
- indexWriter.readerPool.release(reader);
- }
-
++ perThread.pushDeletes(newSegment, indexWriter.segmentInfos);
+
- synchronized boolean doPause() {
- return waitingBytes > waitQueuePauseBytes;
- }
-
- synchronized void abort() {
- int count = 0;
- for(int i=0;i<waiting.length;i++) {
- final DocWriter doc = waiting[i];
- if (doc != null) {
- doc.abort();
- waiting[i] = null;
- count++;
- }
- }
- waitingBytes = 0;
- assert count == numWaiting;
- numWaiting = 0;
- }
-
- private void writeDocument(DocWriter doc) throws IOException {
- assert doc == skipDocWriter || nextWriteDocID == doc.docID;
+ if (indexWriter.useCompoundFile(newSegment)) {
+ String compoundFileName = IndexFileNames.segmentFileName(newSegment.name, "", IndexFileNames.COMPOUND_FILE_EXTENSION);
+ message("creating compound file " + compoundFileName);
+ // Now build compound file
boolean success = false;
try {
- doc.finish();
- nextWriteDocID++;
- nextWriteLoc++;
- assert nextWriteLoc <= waiting.length;
- if (nextWriteLoc == waiting.length) {
- nextWriteLoc = 0;
- }
+ createCompoundFile(compoundFileName, perThread);
success = true;
} finally {
if (!success) {
- setAborting();
- }
- }
- }
+ if (infoStream != null) {
+ message("hit exception " +
- "reating compound file for newly flushed segment " + newSegment.name);
++ "reating compound file for newly flushed segment " + newSegment.name);
+ }
- indexWriter.getIndexFileDeleter().deleteFile(IndexFileNames.segmentFileName(newSegment.name, "",
+
- synchronized public boolean add(DocWriter doc) throws IOException {
-
- assert doc.docID >= nextWriteDocID;
-
- if (doc.docID == nextWriteDocID) {
- writeDocument(doc);
- while(true) {
- doc = waiting[nextWriteLoc];
- if (doc != null) {
- numWaiting--;
- waiting[nextWriteLoc] = null;
- waitingBytes -= doc.sizeInBytes();
- writeDocument(doc);
- } else {
- break;
++ indexWriter.deleter.deleteFile(IndexFileNames.segmentFileName(newSegment.name, "",
+ IndexFileNames.COMPOUND_FILE_EXTENSION));
+ for (String file : perThread.flushState.flushedFiles) {
- indexWriter.getIndexFileDeleter().deleteFile(file);
++ indexWriter.deleter.deleteFile(file);
}
- }
- } else {
-
- // I finished before documents that were added
- // before me. This can easily happen when I am a
- // small doc and the docs before me were large, or,
- // just due to luck in the thread scheduling. Just
- // add myself to the queue and when that large doc
- // finishes, it will flush me:
- int gap = doc.docID - nextWriteDocID;
- if (gap >= waiting.length) {
- // Grow queue
- DocWriter[] newArray = new DocWriter[ArrayUtil.oversize(gap, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
- assert nextWriteLoc >= 0;
- System.arraycopy(waiting, nextWriteLoc, newArray, 0, waiting.length-nextWriteLoc);
- System.arraycopy(waiting, 0, newArray, waiting.length-nextWriteLoc, nextWriteLoc);
- nextWriteLoc = 0;
- waiting = newArray;
- gap = doc.docID - nextWriteDocID;
- }
- int loc = nextWriteLoc + gap;
- if (loc >= waiting.length) {
- loc -= waiting.length;
}
-
- // We should only wrap one time
- assert loc < waiting.length;
-
- // Nobody should be in my spot!
- assert waiting[loc] == null;
- waiting[loc] = doc;
- numWaiting++;
- waitingBytes += doc.sizeInBytes();
}
--
- return doPause();
- }
- }
++
+ for (String file : perThread.flushState.flushedFiles) {
- indexWriter.getIndexFileDeleter().deleteFile(file);
++ indexWriter.deleter.deleteFile(file);
+ }
+
+ newSegment.setUseCompoundFile(true);
-
- synchronized(openFiles) {
- openFiles.remove(compoundFileName);
- }
- }
-
- synchronized(openFiles) {
- openFiles.removeAll(perThread.flushState.flushedFiles);
- }
-
- indexWriter.addNewSegment(newSegment);
- }
-
- // Returns true if an abort is in progress
- void pauseAllThreads() {
- threadPool.pauseAllThreads();
- }
-
- void resumeAllThreads() {
- threadPool.resumeAllThreads();
- }
-
- void close() {
- sequenceIDLock.lock();
- try {
- closed = true;
- } finally {
- sequenceIDLock.unlock();
- }
- }
-
- private void ensureOpen() throws AlreadyClosedException {
- if (closed) {
- throw new AlreadyClosedException("this IndexWriter is closed");
- }
- }
+
- private final boolean maybeFlushPerThread(DocumentsWriterPerThread perThread) throws IOException {
- if (perThread.getNumDocsInRAM() == maxBufferedDocs) {
- flushSegment(perThread);
- assert perThread.getNumDocsInRAM() == 0;
-
- return true;
+ }
+
- return false;
- }
-
- private boolean flushSegment(DocumentsWriterPerThread perThread)
- throws IOException {
- if (perThread.getNumDocsInRAM() == 0) {
- return false;
- }
-
- SegmentInfo newSegment = perThread.flush();
- newSegment.dir = indexWriter.getDirectory();
-
- finishFlushedSegment(newSegment, perThread);
- return true;
- }
-
- void abort() throws IOException {
- threadPool.abort(new DocumentsWriterThreadPool.AbortTask() {
-
- @Override
- void abort() throws IOException {
- try {
- abortedFiles = openFiles();
- } catch (Throwable t) {
- abortedFiles = null;
- }
-
- deletesInRAM.clear();
- // nocommit
- // deletesFlushed.clear();
-
- openFiles.clear();
- deletesInRAM.clear();
- }
- });
- }
-
- final Set<String> openFiles = new HashSet<String>();
- private Collection<String> abortedFiles; // List of files that were written before last abort()
- /*
- * Returns Collection of files in use by this instance,
- * including any flushed segments.
- */
- @SuppressWarnings("unchecked")
- private Collection<String> openFiles() {
- synchronized(openFiles) {
- return (Set<String>) ((HashSet<String>) openFiles).clone();
- }
- }
-
- void addOpenFile(String file) {
- synchronized(openFiles) {
- openFiles.add(file);
- }
- }
-
- void removeOpenFile(String file) {
- synchronized(openFiles) {
- openFiles.remove(file);
- }
- }
-
- Collection<String> abortedFiles() {
- return abortedFiles;
- }
-
- boolean hasDeletes() {
- return deletesInRAM.hasDeletes();
- }
-
- // nocommit
- int getNumDocsInRAM() {
- return numDocsInRAM.get();
- }
-
- // nocommit
- long getRAMUsed() {
- return ramUsed.get();
- }
-
- // nocommit
- // long getRAMUsed() {
- // return numBytesUsed + deletesInRAM.bytesUsed + deletesFlushed.bytesUsed;
- // }
-
- boolean applyDeletes(SegmentInfos infos) throws IOException {
- if (!hasDeletes())
- return false;
-
- final long t0 = System.currentTimeMillis();
-
- if (infoStream != null) {
- message("apply " + deletesInRAM.getNumDeletes() + " buffered deletes on " +
- +infos.size() + " segments.");
- }
-
- final int infosEnd = infos.size();
-
- boolean any = false;
- for (int i = 0; i < infosEnd; i++) {
-
- // Make sure we never attempt to apply deletes to
- // segment in external dir
- assert infos.info(i).dir == indexWriter.getDirectory();
-
- SegmentInfo si = infos.info(i);
- // we have to synchronize here, because we need a write lock on
- // the segment in order to apply deletes
- synchronized (indexWriter) {
- SegmentReader reader = indexWriter.readerPool.get(si, false);
- try {
- any |= applyDeletes(reader, si.getMinSequenceID(), si.getMaxSequenceID(), null);
- } finally {
- indexWriter.readerPool.release(reader);
- }
- }
- }
-
- if (infoStream != null) {
- message("apply deletes took " + (System.currentTimeMillis() - t0) + " msec");
- }
-
- return any;
- }
-
- // Apply buffered delete terms, queries and docIDs to the
- // provided reader
- final boolean applyDeletes(IndexReader reader, long minSequenceID, long maxSequenceID, long[] sequenceIDs)
- throws CorruptIndexException, IOException {
-
- assert sequenceIDs == null || sequenceIDs.length >= reader.maxDoc() : "reader.maxDoc="
- + reader.maxDoc() + ",sequenceIDs.length=" + sequenceIDs.length;
-
- boolean any = false;
-
- // first: delete the documents that had non-aborting exceptions
- if (sequenceIDs != null) {
- for (int i = 0; i < reader.maxDoc(); i++) {
- if (sequenceIDs[i] == -1) {
- reader.deleteDocument(i);
- any = true;
- }
- }
- }
-
- if (deletesInRAM.hasDeletes()) {
- IndexSearcher searcher = new IndexSearcher(reader);
-
- SortedMap<Long, BufferedDeletesInRAM.Delete> deletes = deletesInRAM.deletes.getReadCopy();
-
- SortedMap<Term, Long> deleteTerms = new TreeMap<Term, Long>();
- for (Entry<Long, BufferedDeletesInRAM.Delete> entry : deletes.entrySet()) {
- if (minSequenceID < entry.getKey()) {
- BufferedDeletesInRAM.Delete delete = entry.getValue();
- if (delete instanceof BufferedDeletesInRAM.DeleteTerm) {
- BufferedDeletesInRAM.DeleteTerm deleteTerm = (BufferedDeletesInRAM.DeleteTerm) delete;
- deleteTerms.put(deleteTerm.term, entry.getKey());
- } else if (delete instanceof BufferedDeletesInRAM.DeleteTerms) {
- BufferedDeletesInRAM.DeleteTerms terms = (BufferedDeletesInRAM.DeleteTerms) delete;
- for (Term t : terms.terms) {
- deleteTerms.put(t, entry.getKey());
- }
- } else {
- // delete query
- BufferedDeletesInRAM.DeleteQuery deleteQuery = (BufferedDeletesInRAM.DeleteQuery) delete;
- Query query = deleteQuery.query;
- Weight weight = query.weight(searcher);
- Scorer scorer = weight.scorer(reader, true, false);
- if (scorer != null) {
- while (true) {
- int doc = scorer.nextDoc();
- if (doc == DocsEnum.NO_MORE_DOCS) {
- break;
- }
- if ( (sequenceIDs != null && sequenceIDs[doc] < entry.getKey())
- || (sequenceIDs == null && maxSequenceID < entry.getKey())) {
- reader.deleteDocument(doc);
- any = true;
- }
- }
- }
- }
- }
- }
-
- // Delete by term
- if (deleteTerms.size() > 0) {
- Fields fields = reader.fields();
- if (fields == null) {
- // This reader has no postings
- return false;
- }
-
- TermsEnum termsEnum = null;
-
- String currentField = null;
- BytesRef termRef = new BytesRef();
- DocsEnum docs = null;
-
- for (Entry<Term, Long> entry : deleteTerms.entrySet()) {
- Term term = entry.getKey();
- // Since we visit terms sorted, we gain performance
- // by re-using the same TermsEnum and seeking only
- // forwards
- if (term.field() != currentField) {
- assert currentField == null || currentField.compareTo(term.field()) < 0;
- currentField = term.field();
- Terms terms = fields.terms(currentField);
- if (terms != null) {
- termsEnum = terms.iterator();
- } else {
- termsEnum = null;
- }
- }
-
- if (termsEnum == null) {
- continue;
- }
- // assert checkDeleteTerm(term);
-
- termRef.copy(term.text());
-
- if (termsEnum.seek(termRef, false) == TermsEnum.SeekStatus.FOUND) {
- DocsEnum docsEnum = termsEnum.docs(reader.getDeletedDocs(), docs);
-
- if (docsEnum != null) {
- docs = docsEnum;
- // int limit = entry.getValue().getNum();
- while (true) {
- final int doc = docs.nextDoc();
- // if (docID == DocsEnum.NO_MORE_DOCS || docIDStart+docID >= limit) {
- if (doc == DocsEnum.NO_MORE_DOCS) {
- break;
- }
- if ( (sequenceIDs != null && sequenceIDs[doc] < entry.getValue())
- || (sequenceIDs == null && maxSequenceID < entry.getValue())) {
- reader.deleteDocument(doc);
- any = true;
- }
- }
- }
- }
- }
- }
- }
-
- return any;
++ indexWriter.addNewSegment(newSegment);
+ }
+
- void message(String message) {
- indexWriter.message("DW: " + message);
- }
++// /* We have three pools of RAM: Postings, byte blocks
++// * (holds freq/prox posting data) and per-doc buffers
++// * (stored fields/term vectors). Different docs require
++// * varying amount of storage from these classes. For
++// * example, docs with many unique single-occurrence short
++// * terms will use up the Postings RAM and hardly any of
++// * the other two. Whereas docs with very large terms will
++// * use alot of byte blocks RAM. This method just frees
++// * allocations from the pools once we are over-budget,
++// * which balances the pools to match the current docs. */
++// void balanceRAM() {
++//
++// final boolean doBalance;
++// final long deletesRAMUsed;
++//
++// deletesRAMUsed = bufferedDeletes.bytesUsed();
++//
++// synchronized(this) {
++// if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH || bufferIsFull) {
++// return;
++// }
++//
++// doBalance = bytesUsed() + deletesRAMUsed >= ramBufferSize;
++// }
++//
++// if (doBalance) {
++//
++// if (infoStream != null)
++// message(" RAM: balance allocations: usedMB=" + toMB(bytesUsed()) +
++// " vs trigger=" + toMB(ramBufferSize) +
++// " deletesMB=" + toMB(deletesRAMUsed) +
++// " byteBlockFree=" + toMB(byteBlockAllocator.bytesUsed()) +
++// " perDocFree=" + toMB(perDocAllocator.bytesUsed()));
++//
++// final long startBytesUsed = bytesUsed() + deletesRAMUsed;
++//
++// int iter = 0;
++//
++// // We free equally from each pool in 32 KB
++// // chunks until we are below our threshold
++// // (freeLevel)
++//
++// boolean any = true;
++//
++// while(bytesUsed()+deletesRAMUsed > freeLevel) {
++//
++// synchronized(this) {
++// if (0 == perDocAllocator.numBufferedBlocks() &&
++// 0 == byteBlockAllocator.numBufferedBlocks() &&
++// 0 == freeIntBlocks.size() && !any) {
++// // Nothing else to free -- must flush now.
++// bufferIsFull = bytesUsed()+deletesRAMUsed > ramBufferSize;
++// if (infoStream != null) {
++// if (bytesUsed()+deletesRAMUsed > ramBufferSize)
++// message(" nothing to free; set bufferIsFull");
++// else
++// message(" nothing to free");
++// }
++// break;
++// }
++//
++// if ((0 == iter % 4) && byteBlockAllocator.numBufferedBlocks() > 0) {
++// byteBlockAllocator.freeBlocks(1);
++// }
++// if ((1 == iter % 4) && freeIntBlocks.size() > 0) {
++// freeIntBlocks.remove(freeIntBlocks.size()-1);
++// bytesUsed.addAndGet(-INT_BLOCK_SIZE * RamUsageEstimator.NUM_BYTES_INT);
++// }
++// if ((2 == iter % 4) && perDocAllocator.numBufferedBlocks() > 0) {
++// perDocAllocator.freeBlocks(32); // Remove upwards of 32 blocks (each block is 1K)
++// }
++// }
++//
++// if ((3 == iter % 4) && any)
++// // Ask consumer to free any recycled state
++// any = consumer.freeRAM();
++//
++// iter++;
++// }
++//
++// if (infoStream != null)
++// message(" after free: freedMB=" + nf.format((startBytesUsed-bytesUsed()-deletesRAMUsed)/1024./1024.) + " usedMB=" + nf.format((bytesUsed()+deletesRAMUsed)/1024./1024.));
++// }
++// }
}
diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
index 36b5707196b,00000000000..3dc25e50445
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
@@@ -1,315 -1,0 +1,423 @@@
+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.ArrayList;
++import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.document.Document;
- import org.apache.lucene.index.codecs.Codec;
++import org.apache.lucene.search.Query;
+import org.apache.lucene.search.Similarity;
+import org.apache.lucene.store.Directory;
- import org.apache.lucene.store.FilterDirectory;
- import org.apache.lucene.store.IndexOutput;
- import org.apache.lucene.util.ArrayUtil;
++import org.apache.lucene.util.RamUsageEstimator;
++import org.apache.lucene.util.RecyclingByteBlockAllocator;
+
+public class DocumentsWriterPerThread {
-
++
+ /**
+ * The IndexingChain must define the {@link #getChain(DocumentsWriter)} method
+ * which returns the DocConsumer that the DocumentsWriter calls to process the
- * documents.
++ * 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,
+ new TermsHash(documentsWriterPerThread, termVectorsWriter, null));
+ final NormsWriter normsWriter = new NormsWriter();
+ final DocInverter docInverter = new DocInverter(documentsWriterPerThread.docState, termsHash, normsWriter);
+ return new DocFieldProcessor(documentsWriterPerThread, docInverter);
+ }
+ };
-
++
++ // Deletes for our still-in-RAM (to be flushed next) segment
++ private SegmentDeletes pendingDeletes = new SegmentDeletes();
++
+ static class DocState {
+ final DocumentsWriterPerThread docWriter;
+ Analyzer analyzer;
+ int maxFieldLength;
+ PrintStream infoStream;
+ Similarity similarity;
+ 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);
+ }
+ }
-
++
+ /** 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 {
+ assert aborting;
+ try {
+ if (infoStream != null) {
+ message("docWriter: now abort");
+ }
+ try {
+ consumer.abort();
+ } catch (Throwable t) {
+ }
+
++ pendingDeletes.clear();
+ // Reset all postings data
+ doAfterFlush();
+
+ } finally {
+ aborting = false;
+ if (infoStream != null) {
+ message("docWriter: done abort");
+ }
+ }
+ }
+
-
- final DocumentsWriterRAMAllocator ramAllocator = new DocumentsWriterRAMAllocator();
-
+ final DocumentsWriter parent;
+ final IndexWriter writer;
-
++
+ final Directory directory;
+ final DocState docState;
+ final DocConsumer consumer;
+ private DocFieldProcessor docFieldProcessor;
-
++
+ String segment; // Current segment we are working on
+ boolean aborting; // True if an abort is pending
-
++
+ private final PrintStream infoStream;
+ private int numDocsInRAM;
+ private int flushedDocCount;
+ SegmentWriteState flushState;
+
- long[] sequenceIDs = new long[8];
-
- long numBytesUsed;
-
++ final AtomicLong bytesUsed = new AtomicLong(0);
++
++ FieldInfos fieldInfos = new FieldInfos();
++
+ public DocumentsWriterPerThread(Directory directory, DocumentsWriter parent, IndexingChain indexingChain) {
+ parent.indexWriter.testPoint("DocumentsWriterPerThread.init start");
+ this.directory = directory;
+ this.parent = parent;
+ this.writer = parent.indexWriter;
+ this.infoStream = parent.indexWriter.getInfoStream();
+ this.docState = new DocState(this);
- this.docState.similarity = parent.config.getSimilarity();
- this.docState.maxFieldLength = parent.config.getMaxFieldLength();
-
++ this.docState.similarity = parent.indexWriter.getConfig().getSimilarity();
++ this.docState.maxFieldLength = IndexWriterConfig.UNLIMITED_FIELD_LENGTH;
++
+ consumer = indexingChain.getChain(this);
+ if (consumer instanceof DocFieldProcessor) {
+ docFieldProcessor = (DocFieldProcessor) consumer;
+ }
+ }
-
++
+ void setAborting() {
+ aborting = true;
+ }
-
++
+ public void addDocument(Document doc, Analyzer analyzer) throws IOException {
+ 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 {
+ consumer.processDocument();
-
++
+ success = true;
+ } finally {
+ if (!success) {
+ if (!aborting) {
+ // mark document as deleted
- commitDocument(-1);
++ deleteDocID(docState.docID);
++ commitDocument();
+ }
+ }
+ }
+
+ success = false;
+ try {
+ consumer.finishDocument();
-
++
+ success = true;
+ } finally {
+ if (!success) {
+ setAborting();
+ }
+ }
++ }
+
++ void pushDeletes(SegmentInfo newSegment, SegmentInfos segmentInfos) {
++ // Lock order: DW -> BD
++ if (pendingDeletes.any()) {
++ if (newSegment != null) {
++ if (infoStream != null) {
++ message("flush: push buffered deletes to newSegment");
++ }
++ parent.bufferedDeletes.pushDeletes(pendingDeletes, newSegment);
++ } else if (segmentInfos.size() > 0) {
++ if (infoStream != null) {
++ message("flush: push buffered deletes to previously flushed segment " + segmentInfos.lastElement());
++ }
++ parent.bufferedDeletes.pushDeletes(pendingDeletes, segmentInfos.lastElement(), true);
++ } else {
++ if (infoStream != null) {
++ message("flush: drop buffered deletes: no segments");
++ }
++ // We can safely discard these deletes: since
++ // there are no segments, the deletions cannot
++ // affect anything.
++ }
++ pendingDeletes = new SegmentDeletes();
++ }
+ }
+
- public void commitDocument(long sequenceID) {
- if (numDocsInRAM == sequenceIDs.length) {
- sequenceIDs = ArrayUtil.grow(sequenceIDs);
++
++ // Buffer a specific docID for deletion. Currently only
++ // used when we hit a exception when adding a document
++ synchronized 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).
++ }
++
++ void deleteQueries(Query... queries) {
++ for (Query query : queries) {
++ pendingDeletes.addQuery(query, numDocsInRAM);
++ }
++ }
++
++ void deleteQuery(Query query) {
++ pendingDeletes.addQuery(query, numDocsInRAM);
++ }
++
++ void deleteTerms(Term... terms) {
++ for (Term term : terms) {
++ pendingDeletes.addTerm(term, numDocsInRAM);
+ }
-
- sequenceIDs[numDocsInRAM] = sequenceID;
++ }
++
++ void deleteTerm(Term term) {
++ pendingDeletes.addTerm(term, numDocsInRAM);
++ }
++
++ public void commitDocument() {
+ numDocsInRAM++;
+ }
-
++
+ int getNumDocsInRAM() {
+ return numDocsInRAM;
+ }
-
- long getMinSequenceID() {
- if (numDocsInRAM == 0) {
- return -1;
- }
- return sequenceIDs[0];
- }
-
++
+ /** Returns true if any of the fields in the current
+ * buffered docs have omitTermFreqAndPositions==false */
+ boolean hasProx() {
+ return (docFieldProcessor != null) ? docFieldProcessor.fieldInfos.hasProx()
+ : true;
+ }
-
- Codec getCodec() {
- return flushState.codec;
++
++ SegmentCodecs getCodec() {
++ return flushState.segmentCodecs;
+ }
-
++
+ /** Reset after a flush */
+ private void doAfterFlush() throws IOException {
+ segment = null;
+ numDocsInRAM = 0;
+ }
-
++
+ /** Flush all pending docs to a new segment */
+ SegmentInfo flush() throws IOException {
+ assert numDocsInRAM > 0;
+
- flushState = new SegmentWriteState(infoStream, directory, segment, docFieldProcessor.fieldInfos,
++ flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,
+ numDocsInRAM, writer.getConfig().getTermIndexInterval(),
- writer.codecs);
++ SegmentCodecs.build(fieldInfos, writer.codecs));
+
+ if (infoStream != null) {
+ message("flush postings as segment " + flushState.segmentName + " numDocs=" + numDocsInRAM);
+ }
-
++
+ boolean success = false;
+
+ try {
+ consumer.flush(flushState);
+
++ boolean hasVectors = flushState.hasVectors;
++
+ if (infoStream != null) {
+ SegmentInfo si = new SegmentInfo(flushState.segmentName,
+ flushState.numDocs,
+ directory, false,
+ hasProx(),
- getCodec());
++ getCodec(),
++ hasVectors);
+
- final long newSegmentSize = si.sizeInBytes();
- String message = " ramUsed=" + ramAllocator.nf.format(((double) numBytesUsed)/1024./1024.) + " MB" +
++ final long newSegmentSize = si.sizeInBytes(true);
++ String message = " ramUsed=" + nf.format(((double) bytesUsed.get())/1024./1024.) + " MB" +
+ " newFlushedSize=" + newSegmentSize +
- " docs/MB=" + ramAllocator.nf.format(numDocsInRAM/(newSegmentSize/1024./1024.)) +
- " new/old=" + ramAllocator.nf.format(100.0*newSegmentSize/numBytesUsed) + "%";
++ " docs/MB=" + nf.format(numDocsInRAM/(newSegmentSize/1024./1024.)) +
++ " new/old=" + nf.format(100.0*newSegmentSize/bytesUsed.get()) + "%";
+ message(message);
+ }
+
+ flushedDocCount += flushState.numDocs;
+
- long maxSequenceID = sequenceIDs[numDocsInRAM-1];
+ doAfterFlush();
-
++
+ // Create new SegmentInfo, but do not add to our
+ // segmentInfos until deletes are flushed
+ // successfully.
+ SegmentInfo newSegment = new SegmentInfo(flushState.segmentName,
+ flushState.numDocs,
+ directory, false,
+ hasProx(),
- getCodec());
++ getCodec(),
++ hasVectors);
++
+
-
- newSegment.setMinSequenceID(sequenceIDs[0]);
- newSegment.setMaxSequenceID(maxSequenceID);
-
+ IndexWriter.setDiagnostics(newSegment, "flush");
+ success = true;
+
+ return newSegment;
+ } finally {
+ if (!success) {
+ setAborting();
+ }
+ }
+ }
+
+ /** Get current segment name we are writing. */
+ String getSegment() {
+ return segment;
+ }
-
- void bytesUsed(long numBytes) {
- ramAllocator.bytesUsed(numBytes);
++
++ long bytesUsed() {
++ return bytesUsed.get();
++ }
++
++ FieldInfos getFieldInfos() {
++ return fieldInfos;
+ }
-
++
+ void message(String message) {
+ writer.message("DW: " + message);
+ }
++
++ NumberFormat nf = NumberFormat.getInstance();
++
++ /* 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;
++
++ private ArrayList<int[]> freeIntBlocks = new ArrayList<int[]>();
++
++ /* Allocate another int[] from the shared pool */
++ synchronized int[] getIntBlock() {
++ final int size = freeIntBlocks.size();
++ final int[] b;
++ if (0 == size) {
++ b = new int[INT_BLOCK_SIZE];
++ bytesUsed.addAndGet(INT_BLOCK_SIZE*RamUsageEstimator.NUM_BYTES_INT);
++ } else
++ b = freeIntBlocks.remove(size-1);
++ return b;
++ }
++
++ /* Return int[]s to the pool */
++ synchronized void recycleIntBlocks(int[][] blocks, int start, int end) {
++ for(int i=start;i<end;i++) {
++ freeIntBlocks.add(blocks[i]);
++ blocks[i] = null;
++ }
++ }
++
++ final RecyclingByteBlockAllocator byteBlockAllocator = new RecyclingByteBlockAllocator(BYTE_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);
++
++ final static int PER_DOC_BLOCK_SIZE = 1024;
++
++ final RecyclingByteBlockAllocator perDocAllocator = new RecyclingByteBlockAllocator(PER_DOC_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);
++
++ String toMB(long v) {
++ return nf.format(v/1024./1024.);
++ }
++
+}
diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriterThreadPool.java
index ec7956895ef,00000000000..77e6f12499d
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriterThreadPool.java
+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriterThreadPool.java
@@@ -1,311 -1,0 +1,314 @@@
+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.Iterator;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.lucene.document.Document;
+import org.apache.lucene.util.ThreadInterruptedException;
+
+abstract class DocumentsWriterThreadPool {
+ public static abstract class Task<T> {
+ private boolean clearThreadBindings = false;
-
++
+ protected void clearThreadBindings() {
+ this.clearThreadBindings = true;
+ }
-
++
+ boolean doClearThreadBindings() {
+ return clearThreadBindings;
+ }
+ }
+
+ public static abstract class PerThreadTask<T> extends Task<T> {
+ abstract T process(final DocumentsWriterPerThread perThread) throws IOException;
+ }
-
++
+ public static abstract class AllThreadsTask<T> extends Task<T> {
+ abstract T process(final Iterator<DocumentsWriterPerThread> threadsIterator) throws IOException;
+ }
+
- public static abstract class AbortTask {
- abstract void abort() throws IOException;
- }
-
+ protected abstract static class ThreadState {
+ private DocumentsWriterPerThread perThread;
+ private boolean isIdle = true;
-
++
+ void start() {/* extension hook */}
+ void finish() {/* extension hook */}
+ }
-
++
+ private int pauseThreads = 0;
-
++
+ protected final int maxNumThreadStates;
+ protected ThreadState[] allThreadStates = new ThreadState[0];
-
++
+ private final Lock lock = new ReentrantLock();
+ private final Condition threadStateAvailable = lock.newCondition();
+ private boolean globalLock;
+ private boolean aborting;
+
+ DocumentsWriterThreadPool(int maxNumThreadStates) {
+ this.maxNumThreadStates = (maxNumThreadStates < 1) ? IndexWriterConfig.DEFAULT_MAX_THREAD_STATES : maxNumThreadStates;
+ }
-
++
+ public final int getMaxThreadStates() {
+ return this.maxNumThreadStates;
+ }
-
++
+ void pauseAllThreads() {
+ lock.lock();
+ try {
+ pauseThreads++;
+ while(!allThreadsIdle()) {
+ try {
+ threadStateAvailable.await();
+ } catch (InterruptedException ie) {
+ throw new ThreadInterruptedException(ie);
+ }
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ void resumeAllThreads() {
+ lock.lock();
+ try {
+ pauseThreads--;
+ assert pauseThreads >= 0;
+ if (0 == pauseThreads) {
+ threadStateAvailable.signalAll();
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private boolean allThreadsIdle() {
+ for (ThreadState state : allThreadStates) {
+ if (!state.isIdle) {
+ return false;
+ }
+ }
-
++
+ return true;
+ }
-
- void abort(AbortTask task) throws IOException {
++
++ void abort() throws IOException {
+ lock.lock();
+ try {
+ if (!aborting) {
+ aborting = true;
+ pauseAllThreads();
+ for (ThreadState state : allThreadStates) {
+ state.perThread.aborting = true;
+ }
+
+ try {
+ for (ThreadState state : allThreadStates) {
+ state.perThread.abort();
+ }
-
- task.abort();
++
+ } finally {
+ aborting = false;
+ resumeAllThreads();
+ }
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
-
++
+ void finishAbort() {
+ aborting = false;
+ resumeAllThreads();
+ }
+
+ public <T> T executeAllThreads(DocumentsWriter documentsWriter, AllThreadsTask<T> task) throws IOException {
+ T result = null;
-
++
+ lock.lock();
+ try {
+ try {
+ while (globalLock) {
+ threadStateAvailable.await();
+ }
+ } catch (InterruptedException ie) {
+ throw new ThreadInterruptedException(ie);
+ }
+
+ assert !globalLock;
+ globalLock = true;
+
+ pauseAllThreads();
-
++
+ } finally {
+ lock.unlock();
+ }
+
+ final ThreadState[] localAllThreads = allThreadStates;
-
++
+ // all threads are idle now
+ boolean success = false;
+ try {
- result = task.process(new Iterator<DocumentsWriterPerThread>() {
- int i = 0;
-
- @Override
- public boolean hasNext() {
- return i < localAllThreads.length;
- }
-
- @Override
- public DocumentsWriterPerThread next() {
- return localAllThreads[i++].perThread;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException("remove() not supported.");
- }
- });
++ result = task.process(getPerThreadIterator(localAllThreads));
+ success = true;
+ return result;
+ } finally {
+ boolean abort = false;
+ if (!success) {
+ for (ThreadState state : localAllThreads) {
+ if (state.perThread.aborting) {
+ abort = true;
+ }
+ }
+ }
-
++
+ lock.lock();
+ try {
+ try {
+ if (task.doClearThreadBindings()) {
+ clearAllThreadBindings();
+ }
+ } finally {
+ globalLock = false;
+ resumeAllThreads();
+ threadStateAvailable.signalAll();
+ }
+ } finally {
+ lock.unlock();
+ }
-
++
+ if (!aborting && abort) {
+ documentsWriter.abort();
+ }
-
++
+ }
+ }
+
-
++
+ public final <T> T executePerThread(DocumentsWriter documentsWriter, Document doc, PerThreadTask<T> task) throws IOException {
+ ThreadState state = acquireThreadState(documentsWriter, doc);
+ boolean success = false;
+ try {
+ T result = task.process(state.perThread);
+ success = true;
+ return result;
+ } finally {
+ boolean abort = false;
+ if (!success && state.perThread.aborting) {
+ abort = true;
+ }
+
+ returnDocumentsWriterPerThread(state, task.doClearThreadBindings());
-
++
+ if (!aborting && abort) {
+ documentsWriter.abort();
+ }
+ }
+ }
-
++
++ final Iterator<DocumentsWriterPerThread> getPerThreadIterator() {
++ return getPerThreadIterator(allThreadStates);
++ }
++
++ private static final Iterator<DocumentsWriterPerThread> getPerThreadIterator(final ThreadState[] localAllThreads) {
++ return new Iterator<DocumentsWriterPerThread>() {
++ int i = 0;
++
++ @Override
++ public boolean hasNext() {
++ return i < localAllThreads.length;
++ }
++
++ @Override
++ public DocumentsWriterPerThread next() {
++ return localAllThreads[i++].perThread;
++ }
++
++ @Override
++ public void remove() {
++ throw new UnsupportedOperationException("remove() not supported.");
++ }
++ };
++ }
++
+ protected final <T extends ThreadState> T addNewThreadState(DocumentsWriter documentsWriter, T threadState) {
+ // Just create a new "private" thread state
+ ThreadState[] newArray = new ThreadState[1+allThreadStates.length];
+ if (allThreadStates.length > 0)
+ System.arraycopy(allThreadStates, 0, newArray, 0, allThreadStates.length);
- threadState.perThread = documentsWriter.newDocumentsWriterPerThread();
++ threadState.perThread = documentsWriter.newDocumentsWriterPerThread();
+ newArray[allThreadStates.length] = threadState;
+
+ allThreadStates = newArray;
+ return threadState;
+ }
-
++
+ protected abstract ThreadState selectThreadState(Thread requestingThread, DocumentsWriter documentsWriter, Document doc);
+ protected void clearThreadBindings(ThreadState flushedThread) {
+ // subclasses can optionally override this to cleanup after a thread flushed
+ }
+
+ protected void clearAllThreadBindings() {
+ // subclasses can optionally override this to cleanup after a thread flushed
+ }
-
-
++
++
+ private final ThreadState acquireThreadState(DocumentsWriter documentsWriter, Document doc) {
+ lock.lock();
+ try {
+ ThreadState threadState = selectThreadState(Thread.currentThread(), documentsWriter, doc);
-
++
+ try {
+ while (!threadState.isIdle || globalLock || aborting || threadState.perThread.aborting) {
+ threadStateAvailable.await();
+ }
+ } catch (InterruptedException ie) {
+ throw new ThreadInterruptedException(ie);
+ }
-
++
+ assert threadState.isIdle;
-
++
+ threadState.isIdle = false;
+ threadState.start();
-
++
+ return threadState;
-
++
+ } finally {
+ lock.unlock();
+ }
+ }
-
++
+ private final void returnDocumentsWriterPerThread(ThreadState state, boolean clearThreadBindings) {
+ lock.lock();
+ try {
+ state.finish();
+ if (clearThreadBindings) {
+ clearThreadBindings(state);
+ }
+ state.isIdle = true;
+ threadStateAvailable.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+}
diff --cc lucene/src/java/org/apache/lucene/index/FieldsWriter.java
index 40c57afbcc0,91ab30e7349..254c0ca060c
--- a/lucene/src/java/org/apache/lucene/index/FieldsWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/FieldsWriter.java
@@@ -2,13 -2,13 +2,13 @@@ package org.apache.lucene.index
/**
* Copyright 2004 The Apache Software Foundation
-- *
++ *
* Licensed 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
@@@ -22,15 -22,15 +22,14 @@@ import java.util.List
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.store.Directory;
--import org.apache.lucene.store.RAMOutputStream;
--import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.IndexInput;
++import org.apache.lucene.store.IndexOutput;
+ import org.apache.lucene.util.IOUtils;
- final class FieldsWriter
- {
+ final class FieldsWriter {
static final byte FIELD_IS_TOKENIZED = 0x1;
static final byte FIELD_IS_BINARY = 0x2;
--
++
// Lucene 3.0: Removal of compressed fields
static final int FORMAT_LUCENE_3_0_NO_COMPRESSED_FIELDS = 2;
@@@ -38,194 -38,150 +37,148 @@@
// than the current one, and always change this if you
// switch to a new format!
static final int FORMAT_CURRENT = FORMAT_LUCENE_3_0_NO_COMPRESSED_FIELDS;
--
++
// when removing support for old versions, leave the last supported version here
static final int FORMAT_MINIMUM = FORMAT_LUCENE_3_0_NO_COMPRESSED_FIELDS;
-
- private FieldInfos fieldInfos;
-
- private IndexOutput fieldsStream;
-
- private IndexOutput indexStream;
-
- private boolean doClose;
-
- FieldsWriter(Directory d, String segment, FieldInfos fn) throws IOException {
- fieldInfos = fn;
-
- boolean success = false;
- final String fieldsName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.FIELDS_EXTENSION);
- try {
- fieldsStream = d.createOutput(fieldsName);
- fieldsStream.writeInt(FORMAT_CURRENT);
- success = true;
- } finally {
- if (!success) {
- try {
- close();
- } catch (Throwable t) {
- // Suppress so we keep throwing the original exception
- }
- try {
- d.deleteFile(fieldsName);
- } catch (Throwable t) {
- // Suppress so we keep throwing the original exception
- }
- }
- }
-
- success = false;
- final String indexName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.FIELDS_INDEX_EXTENSION);
- try {
- indexStream = d.createOutput(indexName);
- indexStream.writeInt(FORMAT_CURRENT);
- success = true;
- } finally {
- if (!success) {
- try {
- close();
- } catch (IOException ioe) {
- }
- try {
- d.deleteFile(fieldsName);
- } catch (Throwable t) {
- // Suppress so we keep throwing the original exception
- }
- try {
- d.deleteFile(indexName);
- } catch (Throwable t) {
- // Suppress so we keep throwing the original exception
- }
- }
- }
-
- doClose = true;
- }
-
- FieldsWriter(IndexOutput fdx, IndexOutput fdt, FieldInfos fn) {
- fieldInfos = fn;
- fieldsStream = fdt;
- indexStream = fdx;
- doClose = false;
- }
-
- void setFieldsStream(IndexOutput stream) {
- this.fieldsStream = stream;
- }
- // Writes the contents of buffer into the fields stream
- // and adds a new entry for this document into the index
- // stream. This assumes the buffer was already written
- // in the correct fields format.
- void startDocument(int numStoredFields) throws IOException {
- indexStream.writeLong(fieldsStream.getFilePointer());
- fieldsStream.writeVInt(numStoredFields);
- }
-
- void skipDocument() throws IOException {
- indexStream.writeLong(fieldsStream.getFilePointer());
- fieldsStream.writeVInt(0);
- }
-
- void flush() throws IOException {
- indexStream.flush();
- fieldsStream.flush();
+ // If null - we were supplied with streams, if notnull - we manage them ourselves
+ private Directory directory;
+ private String segment;
+ private FieldInfos fieldInfos;
+ private IndexOutput fieldsStream;
+ private IndexOutput indexStream;
+
+ FieldsWriter(Directory directory, String segment, FieldInfos fn) throws IOException {
+ this.directory = directory;
+ this.segment = segment;
+ fieldInfos = fn;
+
+ boolean success = false;
+ try {
+ fieldsStream = directory.createOutput(IndexFileNames.segmentFileName(segment, "", IndexFileNames.FIELDS_EXTENSION));
+ indexStream = directory.createOutput(IndexFileNames.segmentFileName(segment, "", IndexFileNames.FIELDS_INDEX_EXTENSION));
+
+ fieldsStream.writeInt(FORMAT_CURRENT);
+ indexStream.writeInt(FORMAT_CURRENT);
+
+ success = true;
+ } finally {
+ if (!success) {
+ abort();
+ }
}
-
- final void close() throws IOException {
- if (doClose) {
-
- try {
- if (fieldsStream != null) {
- try {
- fieldsStream.close();
- } finally {
- fieldsStream = null;
- }
- }
- } catch (IOException ioe) {
- try {
- if (indexStream != null) {
- try {
- indexStream.close();
- } finally {
- indexStream = null;
- }
- }
- } catch (IOException ioe2) {
- // Ignore so we throw only first IOException hit
- }
- throw ioe;
- } finally {
- if (indexStream != null) {
- try {
- indexStream.close();
- } finally {
- indexStream = null;
- }
- }
- }
+ }
+
+ FieldsWriter(IndexOutput fdx, IndexOutput fdt, FieldInfos fn) {
+ directory = null;
+ segment = null;
+ fieldInfos = fn;
+ fieldsStream = fdt;
+ indexStream = fdx;
+ }
+
+ void setFieldsStream(IndexOutput stream) {
+ this.fieldsStream = stream;
+ }
+
+ // Writes the contents of buffer into the fields stream
+ // and adds a new entry for this document into the index
+ // stream. This assumes the buffer was already written
+ // in the correct fields format.
- void flushDocument(int numStoredFields, RAMOutputStream buffer) throws IOException {
++ void startDocument(int numStoredFields) throws IOException {
+ indexStream.writeLong(fieldsStream.getFilePointer());
+ fieldsStream.writeVInt(numStoredFields);
- buffer.writeTo(fieldsStream);
+ }
+
+ void skipDocument() throws IOException {
+ indexStream.writeLong(fieldsStream.getFilePointer());
+ fieldsStream.writeVInt(0);
+ }
+
+ void close() throws IOException {
+ if (directory != null) {
+ try {
+ IOUtils.closeSafely(fieldsStream, indexStream);
+ } finally {
+ fieldsStream = indexStream = null;
}
}
+ }
- final void writeField(int fieldNumber, Fieldable field) throws IOException {
- fieldsStream.writeVInt(fieldNumber);
- byte bits = 0;
- if (field.isTokenized())
- bits |= FieldsWriter.FIELD_IS_TOKENIZED;
- if (field.isBinary())
- bits |= FieldsWriter.FIELD_IS_BINARY;
-
- fieldsStream.writeByte(bits);
-
- if (field.isBinary()) {
- final byte[] data;
- final int len;
- final int offset;
- data = field.getBinaryValue();
- len = field.getBinaryLength();
- offset = field.getBinaryOffset();
-
- fieldsStream.writeVInt(len);
- fieldsStream.writeBytes(data, offset, len);
+ void abort() {
+ if (directory != null) {
+ try {
+ close();
+ } catch (IOException ignored) {
}
- else {
- fieldsStream.writeString(field.stringValue());
+ try {
+ directory.deleteFile(IndexFileNames.segmentFileName(segment, "", IndexFileNames.FIELDS_EXTENSION));
+ } catch (IOException ignored) {
}
- }
-
- /** Bulk write a contiguous series of documents. The
- * lengths array is the length (in bytes) of each raw
- * document. The stream IndexInput is the
- * fieldsStream from which we should bulk-copy all
- * bytes. */
- final void addRawDocuments(IndexInput stream, int[] lengths, int numDocs) throws IOException {
- long position = fieldsStream.getFilePointer();
- long start = position;
- for(int i=0;i<numDocs;i++) {
- indexStream.writeLong(position);
- position += lengths[i];
+ try {
+ directory.deleteFile(IndexFileNames.segmentFileName(segment, "", IndexFileNames.FIELDS_INDEX_EXTENSION));
+ } catch (IOException ignored) {
}
- fieldsStream.copyBytes(stream, position-start);
- assert fieldsStream.getFilePointer() == position;
}
+ }
+
- final void writeField(FieldInfo fi, Fieldable field) throws IOException {
- fieldsStream.writeVInt(fi.number);
++ final void writeField(int fieldNumber, Fieldable field) throws IOException {
++ fieldsStream.writeVInt(fieldNumber);
+ byte bits = 0;
+ if (field.isTokenized())
+ bits |= FieldsWriter.FIELD_IS_TOKENIZED;
+ if (field.isBinary())
+ bits |= FieldsWriter.FIELD_IS_BINARY;
+
+ fieldsStream.writeByte(bits);
+
+ if (field.isBinary()) {
+ final byte[] data;
+ final int len;
+ final int offset;
+ data = field.getBinaryValue();
+ len = field.getBinaryLength();
+ offset = field.getBinaryOffset();
+
+ fieldsStream.writeVInt(len);
+ fieldsStream.writeBytes(data, offset, len);
+ }
+ else {
+ fieldsStream.writeString(field.stringValue());
+ }
+ }
+
+ /** Bulk write a contiguous series of documents. The
+ * lengths array is the length (in bytes) of each raw
+ * document. The stream IndexInput is the
+ * fieldsStream from which we should bulk-copy all
+ * bytes. */
+ final void addRawDocuments(IndexInput stream, int[] lengths, int numDocs) throws IOException {
+ long position = fieldsStream.getFilePointer();
+ long start = position;
+ for(int i=0;i<numDocs;i++) {
+ indexStream.writeLong(position);
+ position += lengths[i];
+ }
+ fieldsStream.copyBytes(stream, position-start);
+ assert fieldsStream.getFilePointer() == position;
+ }
+
+ final void addDocument(Document doc) throws IOException {
+ indexStream.writeLong(fieldsStream.getFilePointer());
+
+ int storedCount = 0;
+ List<Fieldable> fields = doc.getFields();
+ for (Fieldable field : fields) {
+ if (field.isStored())
+ storedCount++;
+ }
+ fieldsStream.writeVInt(storedCount);
- final void addDocument(Document doc) throws IOException {
- indexStream.writeLong(fieldsStream.getFilePointer());
-
- int storedCount = 0;
- List<Fieldable> fields = doc.getFields();
- for (Fieldable field : fields) {
- if (field.isStored())
- storedCount++;
- }
- fieldsStream.writeVInt(storedCount);
-
-
- for (Fieldable field : fields) {
- if (field.isStored())
- writeField(fieldInfos.fieldInfo(field.name()).number, field);
- }
-
+ for (Fieldable field : fields) {
+ if (field.isStored())
- writeField(fieldInfos.fieldInfo(field.name()), field);
++ writeField(fieldInfos.fieldNumber(field.name()), field);
}
+ }
}
diff --cc lucene/src/java/org/apache/lucene/index/FreqProxTermsWriter.java
index 8768b092208,d749d24b555..0bc314f1d43
--- a/lucene/src/java/org/apache/lucene/index/FreqProxTermsWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/FreqProxTermsWriter.java
@@@ -19,12 -19,16 +19,12 @@@ package org.apache.lucene.index
import java.io.IOException;
import java.util.ArrayList;
- import java.util.Collections;
-import java.util.Collection;
import java.util.List;
import java.util.Map;
-import java.util.Comparator;
-import org.apache.lucene.index.codecs.PostingsConsumer;
import org.apache.lucene.index.codecs.FieldsConsumer;
-import org.apache.lucene.index.codecs.TermsConsumer;
import org.apache.lucene.util.BytesRef;
+ import org.apache.lucene.util.CollectionUtil;
final class FreqProxTermsWriter extends TermsHashConsumer {
@@@ -42,24 -53,28 +42,23 @@@
// Gather all FieldData's that have postings, across all
// ThreadStates
List<FreqProxTermsWriterPerField> allFields = new ArrayList<FreqProxTermsWriterPerField>();
-
- flushedDocCount = state.numDocs;
-
- for (Map.Entry<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>> entry : threadsAndFields.entrySet()) {
-
- Collection<TermsHashConsumerPerField> fields = entry.getValue();
-
- for (final TermsHashConsumerPerField i : fields) {
- final FreqProxTermsWriterPerField perField = (FreqProxTermsWriterPerField) i;
- if (perField.termsHashPerField.bytesHash.size() > 0)
+ for (TermsHashConsumerPerField f : fieldsToFlush.values()) {
+ final FreqProxTermsWriterPerField perField = (FreqProxTermsWriterPerField) f;
- if (perField.termsHashPerField.numPostings > 0) {
++ if (perField.termsHashPerField.bytesHash.size() > 0) {
allFields.add(perField);
- }
+ }
}
final int numAllFields = allFields.size();
-
+
- // Sort by field name
+ // sort by field name
- Collections.sort(allFields);
+ CollectionUtil.quickSort(allFields);
- // TODO: allow Lucene user to customize this codec:
- final FieldsConsumer consumer = state.codec.fieldsConsumer(state);
+ final FieldsConsumer consumer = state.segmentCodecs.codec().fieldsConsumer(state);
+ TermsHash termsHash = null;
-
++
/*
Current writer chain:
FieldsConsumer
@@@ -72,27 -87,42 +71,27 @@@
-> IMPL: FormatPostingsPositionsWriter
*/
- int start = 0;
- while(start < numAllFields) {
- final FieldInfo fieldInfo = allFields.get(start).fieldInfo;
- final String fieldName = fieldInfo.name;
+ for (int fieldNumber = 0; fieldNumber < numAllFields; fieldNumber++) {
+ final FieldInfo fieldInfo = allFields.get(fieldNumber).fieldInfo;
-
+
- int end = start+1;
- while(end < numAllFields && allFields.get(end).fieldInfo.name.equals(fieldName))
- end++;
-
- FreqProxTermsWriterPerField[] fields = new FreqProxTermsWriterPerField[end-start];
- for(int i=start;i<end;i++) {
- fields[i-start] = allFields.get(i);
-
- // Aggregate the storePayload as seen by the same
- // field across multiple threads
- fieldInfo.storePayloads |= fields[i-start].hasPayloads;
- }
+ FreqProxTermsWriterPerField fieldWriter = allFields.get(fieldNumber);
+ fieldInfo.storePayloads |= fieldWriter.hasPayloads;
// If this field has postings then add them to the
// segment
- appendPostings(fields, consumer);
-
- for(int i=0;i<fields.length;i++) {
- TermsHashPerField perField = fields[i].termsHashPerField;
- int numPostings = perField.bytesHash.size();
- perField.reset();
- perField.shrinkHash(numPostings);
- fields[i].reset();
- }
-
- start = end;
+ fieldWriter.flush(consumer, state);
+
+ TermsHashPerField perField = fieldWriter.termsHashPerField;
+ assert termsHash == null || termsHash == perField.termsHash;
+ termsHash = perField.termsHash;
- int numPostings = perField.numPostings;
++ int numPostings = perField.bytesHash.size();
+ perField.reset();
+ perField.shrinkHash(numPostings);
+ fieldWriter.reset();
}
- for (Map.Entry<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>> entry : threadsAndFields.entrySet()) {
- FreqProxTermsWriterPerThread perThread = (FreqProxTermsWriterPerThread) entry.getKey();
- perThread.termsHashPerThread.reset(true);
+ if (termsHash != null) {
+ termsHash.reset();
}
consumer.close();
}
diff --cc lucene/src/java/org/apache/lucene/index/FreqProxTermsWriterPerField.java
index 6c96babd108,f22c484d1a5..52d29033a78
--- a/lucene/src/java/org/apache/lucene/index/FreqProxTermsWriterPerField.java
+++ b/lucene/src/java/org/apache/lucene/index/FreqProxTermsWriterPerField.java
@@@ -22,10 -21,7 +22,11 @@@ import java.util.Comparator
import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
import org.apache.lucene.document.Fieldable;
+import org.apache.lucene.index.codecs.FieldsConsumer;
+import org.apache.lucene.index.codecs.PostingsConsumer;
+import org.apache.lucene.index.codecs.TermsConsumer;
+import org.apache.lucene.util.BytesRef;
+ import org.apache.lucene.util.RamUsageEstimator;
// TODO: break into separate freq and prox writers as
// codecs; make separate container (tii/tis/skip/*) that can
@@@ -82,8 -78,8 +83,8 @@@ final class FreqProxTermsWriterPerFiel
if (fields[i].isIndexed())
return true;
return false;
-- }
--
++ }
++
@Override
void start(Fieldable f) {
if (fieldState.attributeSource.hasAttribute(PayloadAttribute.class)) {
@@@ -100,18 -96,18 +101,18 @@@
} else {
payload = payloadAttribute.getPayload();
}
--
++
if (payload != null && payload.length > 0) {
termsHashPerField.writeVInt(1, (proxCode<<1)|1);
termsHashPerField.writeVInt(1, payload.length);
termsHashPerField.writeBytes(1, payload.data, payload.offset, payload.length);
-- hasPayloads = true;
++ hasPayloads = true;
} else
termsHashPerField.writeVInt(1, proxCode<<1);
--
++
FreqProxPostingsArray postings = (FreqProxPostingsArray) termsHashPerField.postingsArray;
postings.lastPositions[termID] = fieldState.position;
--
++
}
@Override
@@@ -119,7 -115,7 +120,7 @@@
// First time we're seeing this term since the last
// flush
assert docState.testPoint("FreqProxTermsWriterPerField.newTerm start");
--
++
FreqProxPostingsArray postings = (FreqProxPostingsArray) termsHashPerField.postingsArray;
postings.lastDocIDs[termID] = docState.docID;
if (omitTermFreqAndPositions) {
@@@ -132,12 -128,12 +133,12 @@@
}
@Override
- final void addTerm(final int termID) {
+ void addTerm(final int termID) {
assert docState.testPoint("FreqProxTermsWriterPerField.addTerm start");
--
++
FreqProxPostingsArray postings = (FreqProxPostingsArray) termsHashPerField.postingsArray;
--
++
assert omitTermFreqAndPositions || postings.docFreqs[termID] > 0;
if (omitTermFreqAndPositions) {
@@@ -171,7 -167,7 +172,7 @@@
}
}
}
--
++
@Override
ParallelPostingsArray createPostingsArray(int size) {
return new FreqProxPostingsArray(size);
@@@ -210,138 -206,10 +211,138 @@@
@Override
int bytesPerPosting() {
- return ParallelPostingsArray.BYTES_PER_POSTING + 4 * DocumentsWriterRAMAllocator.INT_NUM_BYTE;
+ return ParallelPostingsArray.BYTES_PER_POSTING + 4 * RamUsageEstimator.NUM_BYTES_INT;
}
}
--
++
public void abort() {}
-
++
+ BytesRef payload;
-
++
+ /* Walk through all unique text tokens (Posting
+ * instances) found in this field and serialize them
+ * into a single RAM segment. */
+ void flush(FieldsConsumer consumer, final SegmentWriteState state)
+ throws CorruptIndexException, IOException {
+
+ final TermsConsumer termsConsumer = consumer.addField(fieldInfo);
+ final Comparator<BytesRef> termComp = termsConsumer.getComparator();
+
+ final boolean currentFieldOmitTermFreqAndPositions = fieldInfo.omitTermFreqAndPositions;
-
++
+ final int[] termIDs = termsHashPerField.sortPostings(termComp);
- final int numTerms = termsHashPerField.numPostings;
++ final int numTerms = termsHashPerField.bytesHash.size();
+ final BytesRef text = new BytesRef();
+ final FreqProxPostingsArray postings = (FreqProxPostingsArray) termsHashPerField.postingsArray;
+ final ByteSliceReader freq = new ByteSliceReader();
+ final ByteSliceReader prox = new ByteSliceReader();
+
-
++
+ for (int i = 0; i < numTerms; i++) {
+ final int termID = termIDs[i];
+ // Get BytesRef
+ final int textStart = postings.textStarts[termID];
+ termsHashPerField.bytePool.setBytesRef(text, textStart);
-
++
+ termsHashPerField.initReader(freq, termID, 0);
+ if (!fieldInfo.omitTermFreqAndPositions) {
+ termsHashPerField.initReader(prox, termID, 1);
+ }
-
++
+ // TODO: really TermsHashPerField should take over most
+ // of this loop, including merge sort of terms from
+ // multiple threads and interacting with the
+ // TermsConsumer, only calling out to us (passing us the
+ // DocsConsumer) to handle delivery of docs/positions
-
++
+ final PostingsConsumer postingsConsumer = termsConsumer.startTerm(text);
-
++
+ // Now termStates has numToMerge FieldMergeStates
+ // which all share the same term. Now we must
+ // interleave the docID streams.
+ int numDocs = 0;
+ int docID = 0;
+ int termFreq = 0;
-
++
+ while(true) {
+ if (freq.eof()) {
+ if (postings.lastDocCodes[termID] != -1) {
+ // Return last doc
+ docID = postings.lastDocIDs[termID];
+ if (!omitTermFreqAndPositions) {
+ termFreq = postings.docFreqs[termID];
+ }
+ postings.lastDocCodes[termID] = -1;
+ } else {
+ // EOF
+ break;
+ }
+ } else {
+ final int code = freq.readVInt();
+ if (omitTermFreqAndPositions) {
+ docID += code;
+ } else {
+ docID += code >>> 1;
+ if ((code & 1) != 0) {
+ termFreq = 1;
+ } else {
+ termFreq = freq.readVInt();
+ }
+ }
-
++
+ assert docID != postings.lastDocIDs[termID];
+ }
-
++
+ numDocs++;
+ assert docID < state.numDocs: "doc=" + docID + " maxDoc=" + state.numDocs;
+ final int termDocFreq = termFreq;
+ postingsConsumer.startDoc(docID, termDocFreq);
-
++
+ // Carefully copy over the prox + payload info,
+ // changing the format to match Lucene's segment
+ // format.
+ if (!currentFieldOmitTermFreqAndPositions) {
+ // omitTermFreqAndPositions == false so we do write positions &
- // payload
++ // payload
+ int position = 0;
+ for(int j=0;j<termDocFreq;j++) {
+ final int code = prox.readVInt();
+ position += code >> 1;
-
++
+ final int payloadLength;
+ final BytesRef thisPayload;
-
++
+ if ((code & 1) != 0) {
+ // This position has a payload
- payloadLength = prox.readVInt();
-
++ payloadLength = prox.readVInt();
++
+ if (payload == null) {
+ payload = new BytesRef();
+ payload.bytes = new byte[payloadLength];
+ } else if (payload.bytes.length < payloadLength) {
+ payload.grow(payloadLength);
+ }
-
++
+ prox.readBytes(payload.bytes, 0, payloadLength);
+ payload.length = payloadLength;
+ thisPayload = payload;
-
++
+ } else {
+ payloadLength = 0;
+ thisPayload = null;
+ }
-
++
+ postingsConsumer.addPosition(position, thisPayload);
- }
-
++ }
++
+ postingsConsumer.finishDoc();
+ }
- }
++ }
+ termsConsumer.finishTerm(text, numDocs);
+ }
-
++
+ termsConsumer.finish();
+ }
+
}
diff --cc lucene/src/java/org/apache/lucene/index/IndexFileDeleter.java
index b5aa6a83501,5d2f959bc65..ecf41bacabc
--- a/lucene/src/java/org/apache/lucene/index/IndexFileDeleter.java
+++ b/lucene/src/java/org/apache/lucene/index/IndexFileDeleter.java
@@@ -21,14 -21,7 +21,13 @@@ import java.io.FileNotFoundException
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintStream;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
++import java.util.Date;
+import java.util.HashMap;
- import java.util.Set;
-
+import java.util.List;
+import java.util.Map;
import org.apache.lucene.index.codecs.CodecProvider;
import org.apache.lucene.store.Directory;
@@@ -55,12 -49,12 +55,12 @@@ import org.apache.lucene.util.Collectio
* (IndexDeletionPolicy) is consulted on creation (onInit)
* and once per commit (onCommit), to decide when a commit
* should be removed.
-- *
++ *
* It is the business of the IndexDeletionPolicy to choose
* when to delete commit points. The actual mechanics of
* file deletion, retrying, etc, derived from the deletion
* of commit points is the business of the IndexFileDeleter.
-- *
++ *
* The current default deletion policy is {@link
* KeepOnlyLastCommitDeletionPolicy}, which removes all
* prior commits when a new commit has completed. This
@@@ -78,7 -72,7 +78,7 @@@ final class IndexFileDeleter
* so we will retry them again later: */
private List<String> deletable;
-- /* Reference count for all files in the index.
++ /* Reference count for all files in the index.
* Counts how many existing commits reference a file.
**/
private Map<String, RefCount> refCounts = new HashMap<String, RefCount>();
@@@ -94,7 -88,7 +94,7 @@@
* non-commit checkpoint: */
private List<Collection<String>> lastFiles = new ArrayList<Collection<String>>();
-- /* Commits that the IndexDeletionPolicy have decided to delete: */
++ /* Commits that the IndexDeletionPolicy have decided to delete: */
private List<CommitPoint> commitsToDelete = new ArrayList<CommitPoint>();
private PrintStream infoStream;
@@@ -111,12 -104,13 +110,13 @@@
void setInfoStream(PrintStream infoStream) {
this.infoStream = infoStream;
- if (infoStream != null)
+ if (infoStream != null) {
message("setInfoStream deletionPolicy=" + policy);
+ }
}
--
++
private void message(String message) {
- infoStream.println("IFD [" + Thread.currentThread().getName() + "]: " + message);
+ infoStream.println("IFD [" + new Date() + "; " + Thread.currentThread().getName() + "]: " + message);
}
private final FilenameFilter indexFilenameFilter;
@@@ -148,12 -139,12 +145,12 @@@
// counts:
long currentGen = segmentInfos.getGeneration();
indexFilenameFilter = new IndexFileNameFilter(codecs);
--
++
CommitPoint currentCommitPoint = null;
String[] files = null;
try {
files = directory.listAll();
-- } catch (NoSuchDirectoryException e) {
++ } catch (NoSuchDirectoryException e) {
// it means the directory is empty, so ignore it.
files = new String[0];
}
@@@ -161,7 -152,7 +158,7 @@@
for (String fileName : files) {
if ((indexFilenameFilter.accept(null, fileName)) && !fileName.endsWith("write.lock") && !fileName.equals(IndexFileNames.SEGMENTS_GEN)) {
--
++
// Add this file to refCounts with initial count 0:
getRefCount(fileName);
@@@ -241,7 -233,7 +239,7 @@@
// Now delete anything with ref count at 0. These are
// presumably abandoned files eg due to crash of
// IndexWriter.
-- for(Map.Entry<String, RefCount> entry : refCounts.entrySet() ) {
++ for(Map.Entry<String, RefCount> entry : refCounts.entrySet() ) {
RefCount rc = entry.getValue();
final String fileName = entry.getKey();
if (0 == rc.count) {
@@@ -261,7 -253,7 +259,7 @@@
// Always protect the incoming segmentInfos since
// sometime it may not be the most recent commit
checkpoint(segmentInfos, false);
--
++
startingCommitDeleted = currentCommitPoint == null ? false : currentCommitPoint.isDeleted();
deleteCommits();
@@@ -335,7 -327,7 +333,7 @@@
segmentPrefix1 = null;
segmentPrefix2 = null;
}
--
++
for(int i=0;i<files.length;i++) {
String fileName = files[i];
if ((segmentName == null || fileName.startsWith(segmentPrefix1) || fileName.startsWith(segmentPrefix2)) &&
@@@ -386,7 -379,7 +385,7 @@@
deleteCommits();
}
}
--
++
public void deletePendingFiles() throws IOException {
if (deletable != null) {
List<String> oldDeletable = deletable;
@@@ -403,7 -397,7 +403,7 @@@
/**
* For definition of "check point" see IndexWriter comments:
* "Clarification: Check Points (and commits)".
-- *
++ *
* Writer calls this when it has made a "consistent
* change" to the index, meaning new files are written to
* the index and the in-memory SegmentInfos have been
diff --cc lucene/src/java/org/apache/lucene/index/IndexWriter.java
index 1e43e21c973,5c0cf7c09db..b660081875a
--- a/lucene/src/java/org/apache/lucene/index/IndexWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/IndexWriter.java
@@@ -50,22 -52,22 +52,22 @@@ import org.apache.lucene.util.ThreadInt
An <code>IndexWriter</code> creates and maintains an index.
<p>The <code>create</code> argument to the {@link
- #IndexWriter(Directory, Analyzer, boolean, MaxFieldLength) constructor} determines
- #IndexWriter(Directory, IndexWriterConfig) constructor} determines
++ #IndexWriter(Directory, IndexWriterConfig) constructor} determines
whether a new index is created, or whether an existing index is
opened. Note that you can open an index with <code>create=true</code>
-- even while readers are using the index. The old readers will
-- continue to search the "point in time" snapshot they had opened,
++ even while readers are using the index. The old readers will
++ continue to search the "point in time" snapshot they had opened,
and won't see the newly created index until they re-open. There are
- also {@link #IndexWriter(Directory, Analyzer, MaxFieldLength) constructors}
+ also {@link #IndexWriter(Directory, IndexWriterConfig) constructors}
with no <code>create</code> argument which will create a new index
-- if there is not already an index at the provided path and otherwise
++ if there is not already an index at the provided path and otherwise
open the existing index.</p>
<p>In either case, documents are added with {@link #addDocument(Document)
addDocument} and removed with {@link #deleteDocuments(Term)} or {@link
#deleteDocuments(Query)}. A document can be updated with {@link
#updateDocument(Term, Document) updateDocument} (which just deletes
-- and then adds the entire document). When finished adding, deleting
++ and then adds the entire document). When finished adding, deleting
and updating documents, {@link #close() close} should be called.</p>
<a name="flush"></a>
@@@ -98,7 -100,7 +100,7 @@@
{@link LockObtainFailedException}. The {@link LockObtainFailedException}
is also thrown if an IndexReader on the same directory is used to delete documents
from the index.</p>
--
++
<a name="deletionPolicy"></a>
<p>Expert: <code>IndexWriter</code> allows an optional
{@link IndexDeletionPolicy} implementation to be
@@@ -148,7 -150,7 +150,7 @@@
synchronize on the <code>IndexWriter</code> instance as
this may cause deadlock; use your own (non-Lucene) objects
instead. </p>
--
++
<p><b>NOTE</b>: If you call
<code>Thread.interrupt()</code> on a thread that's within
IndexWriter, IndexWriter will try to catch this (eg, if
@@@ -160,21 -162,21 +162,21 @@@
/*
* Clarification: Check Points (and commits)
* IndexWriter writes new index files to the directory without writing a new segments_N
-- * file which references these new files. It also means that the state of
++ * file which references these new files. It also means that the state of
* the in memory SegmentInfos object is different than the most recent
* segments_N file written to the directory.
-- *
-- * Each time the SegmentInfos is changed, and matches the (possibly
-- * modified) directory files, we have a new "check point".
-- * If the modified/new SegmentInfos is written to disk - as a new
-- * (generation of) segments_N file - this check point is also an
++ *
++ * Each time the SegmentInfos is changed, and matches the (possibly
++ * modified) directory files, we have a new "check point".
++ * If the modified/new SegmentInfos is written to disk - as a new
++ * (generation of) segments_N file - this check point is also an
* IndexCommit.
-- *
-- * A new checkpoint always replaces the previous checkpoint and
-- * becomes the new "front" of the index. This allows the IndexFileDeleter
++ *
++ * A new checkpoint always replaces the previous checkpoint and
++ * becomes the new "front" of the index. This allows the IndexFileDeleter
* to delete files that are referenced only by stale checkpoints.
* (files that were created since the last commit, but are no longer
-- * referenced by the "front" of the index). For this, IndexFileDeleter
++ * referenced by the "front" of the index). For this, IndexFileDeleter
* keeps track of the last non commit checkpoint.
*/
public class IndexWriter implements Closeable {
@@@ -240,7 -192,7 +192,7 @@@
* printed to infoStream, if set (see {@link
* #setInfoStream}).
*/
- public final static int MAX_TERM_LENGTH = DocumentsWriterRAMAllocator.MAX_TERM_LENGTH_UTF8;
- public final static int MAX_TERM_LENGTH = DocumentsWriter.MAX_TERM_LENGTH_UTF8;
++ public final static int MAX_TERM_LENGTH = DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8;
// The normal read buffer size defaults to 1024, but
// increasing this during merging seems to yield
@@@ -271,13 -219,13 +219,13 @@@
volatile SegmentInfos pendingCommit; // set when a commit is pending (after prepareCommit() & before commit())
volatile long pendingCommitChangeCount;
- private final SegmentInfos segmentInfos = new SegmentInfos(); // the segments
+ final SegmentInfos segmentInfos; // the segments
private DocumentsWriter docWriter;
-
-- private IndexFileDeleter deleter;
++ final IndexFileDeleter deleter;
private Set<SegmentInfo> segmentsToOptimize = new HashSet<SegmentInfo>(); // used by optimize to note those needing optimization
+ private int optimizeMaxNumSegments;
private Lock writeLock;
@@@ -300,11 -246,12 +246,12 @@@
private long mergeGen;
private boolean stopMerges;
- private int flushCount;
- private int flushDeletesCount;
+ private final AtomicInteger flushCount = new AtomicInteger();
+ private final AtomicInteger flushDeletesCount = new AtomicInteger();
+
+ final ReaderPool readerPool = new ReaderPool();
+ final BufferedDeletes bufferedDeletes;
-
+
- final IndexReaderPool readerPool;
-
// This is a "write once" variable (like the organic dye
// on a DVD-R that may or may not be heated by a laser and
// then cooled to permanently record the event): it's
@@@ -423,29 -352,264 +352,264 @@@
if (infoStream != null) {
message("return reader version=" + r.getVersion() + " reader=" + r);
}
- return r;
}
+ maybeMerge();
+
+ return r;
}
-
- // used only by asserts
- public synchronized boolean infoIsLive(SegmentInfo info) {
- int idx = segmentInfos.indexOf(info);
- assert idx != -1;
- assert segmentInfos.get(idx) == info;
- return true;
- }
-
- public synchronized SegmentInfo mapToLive(SegmentInfo info) {
- int idx = segmentInfos.indexOf(info);
- if (idx != -1) {
- info = segmentInfos.get(idx);
+
+ /** Holds shared SegmentReader instances. IndexWriter uses
+ * SegmentReaders for 1) applying deletes, 2) doing
+ * merges, 3) handing out a real-time reader. This pool
+ * reuses instances of the SegmentReaders in all these
+ * places if it is in "near real-time mode" (getReader()
+ * has been called on this instance). */
+
+ class ReaderPool {
+
+ private final Map<SegmentInfo,SegmentReader> readerMap = new HashMap<SegmentInfo,SegmentReader>();
+
+ /** Forcefully clear changes for the specified segments,
+ * and remove from the pool. This is called on successful merge. */
+ synchronized void clear(SegmentInfos infos) throws IOException {
+ if (infos == null) {
+ for (Map.Entry<SegmentInfo,SegmentReader> ent: readerMap.entrySet()) {
+ ent.getValue().hasChanges = false;
+ }
+ } else {
+ for (final SegmentInfo info: infos) {
+ if (readerMap.containsKey(info)) {
+ readerMap.get(info).hasChanges = false;
+ }
- }
++ }
+ }
+ }
-
++
+ // used only by asserts
+ public synchronized boolean infoIsLive(SegmentInfo info) {
+ int idx = segmentInfos.indexOf(info);
+ assert idx != -1;
+ assert segmentInfos.get(idx) == info;
+ return true;
+ }
+
+ public synchronized SegmentInfo mapToLive(SegmentInfo info) {
+ int idx = segmentInfos.indexOf(info);
+ if (idx != -1) {
+ info = segmentInfos.get(idx);
+ }
+ return info;
+ }
-
++
+ /**
+ * Release the segment reader (i.e. decRef it and close if there
+ * are no more references.
+ * @return true if this release altered the index (eg
+ * the SegmentReader had pending changes to del docs and
+ * was closed). Caller must call checkpoint() if so.
+ * @param sr
+ * @throws IOException
+ */
+ public synchronized boolean release(SegmentReader sr) throws IOException {
+ return release(sr, false);
+ }
-
++
+ /**
+ * Release the segment reader (i.e. decRef it and close if there
+ * are no more references.
+ * @return true if this release altered the index (eg
+ * the SegmentReader had pending changes to del docs and
+ * was closed). Caller must call checkpoint() if so.
+ * @param sr
+ * @throws IOException
+ */
+ public synchronized boolean release(SegmentReader sr, boolean drop) throws IOException {
+
+ final boolean pooled = readerMap.containsKey(sr.getSegmentInfo());
+
+ assert !pooled || readerMap.get(sr.getSegmentInfo()) == sr;
+
+ // Drop caller's ref; for an external reader (not
+ // pooled), this decRef will close it
+ sr.decRef();
+
+ if (pooled && (drop || (!poolReaders && sr.getRefCount() == 1))) {
+
+ // We invoke deleter.checkpoint below, so we must be
+ // sync'd on IW if there are changes:
+ assert !sr.hasChanges || Thread.holdsLock(IndexWriter.this);
+
+ // Discard (don't save) changes when we are dropping
+ // the reader; this is used only on the sub-readers
+ // after a successful merge.
+ sr.hasChanges &= !drop;
+
+ final boolean hasChanges = sr.hasChanges;
+
+ // Drop our ref -- this will commit any pending
+ // changes to the dir
+ sr.close();
+
+ // We are the last ref to this reader; since we're
+ // not pooling readers, we release it:
+ readerMap.remove(sr.getSegmentInfo());
+
+ return hasChanges;
+ }
+
+ return false;
+ }
-
++
+ /** Remove all our references to readers, and commits
+ * any pending changes. */
+ synchronized void close() throws IOException {
+ // We invoke deleter.checkpoint below, so we must be
+ // sync'd on IW:
+ assert Thread.holdsLock(IndexWriter.this);
+
+ Iterator<Map.Entry<SegmentInfo,SegmentReader>> iter = readerMap.entrySet().iterator();
+ while (iter.hasNext()) {
-
++
+ Map.Entry<SegmentInfo,SegmentReader> ent = iter.next();
+
+ SegmentReader sr = ent.getValue();
+ if (sr.hasChanges) {
+ assert infoIsLive(sr.getSegmentInfo());
+ sr.doCommit(null);
+
+ // Must checkpoint w/ deleter, because this
+ // segment reader will have created new _X_N.del
+ // file.
+ deleter.checkpoint(segmentInfos, false);
+ }
+
+ iter.remove();
+
+ // NOTE: it is allowed that this decRef does not
+ // actually close the SR; this can happen when a
+ // near real-time reader is kept open after the
+ // IndexWriter instance is closed
+ sr.decRef();
+ }
+ }
-
++
+ /**
+ * Commit all segment reader in the pool.
+ * @throws IOException
+ */
+ synchronized void commit() throws IOException {
+
+ // We invoke deleter.checkpoint below, so we must be
+ // sync'd on IW:
+ assert Thread.holdsLock(IndexWriter.this);
+
+ for (Map.Entry<SegmentInfo,SegmentReader> ent : readerMap.entrySet()) {
+
+ SegmentReader sr = ent.getValue();
+ if (sr.hasChanges) {
+ assert infoIsLive(sr.getSegmentInfo());
+ sr.doCommit(null);
+
+ // Must checkpoint w/ deleter, because this
+ // segment reader will have created new _X_N.del
+ // file.
+ deleter.checkpoint(segmentInfos, false);
+ }
+ }
+ }
-
++
+ /**
+ * Returns a ref to a clone. NOTE: this clone is not
+ * enrolled in the pool, so you should simply close()
+ * it when you're done (ie, do not call release()).
+ */
+ public synchronized SegmentReader getReadOnlyClone(SegmentInfo info, boolean doOpenStores, int termInfosIndexDivisor) throws IOException {
+ SegmentReader sr = get(info, doOpenStores, BufferedIndexInput.BUFFER_SIZE, termInfosIndexDivisor);
+ try {
+ return (SegmentReader) sr.clone(true);
+ } finally {
+ sr.decRef();
+ }
+ }
-
++
+ /**
+ * Obtain a SegmentReader from the readerPool. The reader
+ * must be returned by calling {@link #release(SegmentReader)}
+ * @see #release(SegmentReader)
+ * @param info
+ * @param doOpenStores
+ * @throws IOException
+ */
+ public synchronized SegmentReader get(SegmentInfo info, boolean doOpenStores) throws IOException {
+ return get(info, doOpenStores, BufferedIndexInput.BUFFER_SIZE, config.getReaderTermsIndexDivisor());
+ }
+
+ /**
+ * Obtain a SegmentReader from the readerPool. The reader
+ * must be returned by calling {@link #release(SegmentReader)}
- *
++ *
+ * @see #release(SegmentReader)
+ * @param info
+ * @param doOpenStores
+ * @param readBufferSize
+ * @param termsIndexDivisor
+ * @throws IOException
+ */
+ public synchronized SegmentReader get(SegmentInfo info, boolean doOpenStores, int readBufferSize, int termsIndexDivisor) throws IOException {
+
+ if (poolReaders) {
+ readBufferSize = BufferedIndexInput.BUFFER_SIZE;
+ }
+
+ SegmentReader sr = readerMap.get(info);
+ if (sr == null) {
+ // TODO: we may want to avoid doing this while
+ // synchronized
+ // Returns a ref, which we xfer to readerMap:
+ sr = SegmentReader.get(false, info.dir, info, readBufferSize, doOpenStores, termsIndexDivisor);
+
+ if (info.dir == directory) {
+ // Only pool if reader is not external
+ readerMap.put(info, sr);
+ }
+ } else {
+ if (doOpenStores) {
+ sr.openDocStores();
+ }
+ if (termsIndexDivisor != -1) {
+ // If this reader was originally opened because we
+ // needed to merge it, we didn't load the terms
+ // index. But now, if the caller wants the terms
+ // index (eg because it's doing deletes, or an NRT
+ // reader is being opened) we ask the reader to
+ // load its terms index.
+ sr.loadTermsIndex(termsIndexDivisor);
+ }
+ }
+
+ // Return a ref to our caller
+ if (info.dir == directory) {
+ // Only incRef if we pooled (reader is not external)
+ sr.incRef();
+ }
+ return sr;
+ }
+
+ // Returns a ref
+ public synchronized SegmentReader getIfExists(SegmentInfo info) throws IOException {
+ SegmentReader sr = readerMap.get(info);
+ if (sr != null) {
+ sr.incRef();
+ }
+ return sr;
}
- return info;
}
-
-
--
++
++
++
/**
* Obtain the number of deleted docs for a pooled reader.
-- * If the reader isn't being pooled, the segmentInfo's
++ * If the reader isn't being pooled, the segmentInfo's
* delCount is returned.
*/
public int numDeletedDocs(SegmentInfo info) throws IOException {
@@@ -462,7 -626,7 +626,7 @@@
}
}
}
--
++
/**
* Used internally to throw an {@link
* AlreadyClosedException} if this IndexWriter has been
@@@ -673,7 -665,7 +665,7 @@@
* <b>NOTE:</b> by default, {@link IndexWriterConfig#getMaxFieldLength()}
* returns {@link IndexWriterConfig#UNLIMITED_FIELD_LENGTH}. Pay attention to
* whether this setting fits your application.
-- *
++ *
* @param d
* the index directory. The index is either created or appended
* according <code>conf.getOpenMode()</code>.
@@@ -705,11 -696,11 +696,11 @@@
mergeScheduler = conf.getMergeScheduler();
mergedSegmentWarmer = conf.getMergedSegmentWarmer();
codecs = conf.getCodecProvider();
--
++
+ bufferedDeletes = new BufferedDeletes(messageID);
+ bufferedDeletes.setInfoStream(infoStream);
poolReaders = conf.getReaderPooling();
- this.readerPool = new IndexReaderPool(this, directory, config);
-
OpenMode mode = conf.getOpenMode();
boolean create;
if (mode == OpenMode.CREATE) {
@@@ -772,10 -766,9 +766,9 @@@
setRollbackSegmentInfos(segmentInfos);
- docWriter = new DocumentsWriter(directory, this, conf);
- // nocommit
- //docWriter.setInfoStream(infoStream);
- //docWriter.setMaxFieldLength(maxFieldLength);
- docWriter = new DocumentsWriter(directory, this, conf.getIndexingChain(), conf.getMaxThreadStates(), getCurrentFieldInfos(), bufferedDeletes);
++ docWriter = new DocumentsWriter(directory, this, conf.getIndexingChain(), conf.getIndexerThreadPool(), getCurrentFieldInfos(), bufferedDeletes);
+ docWriter.setInfoStream(infoStream);
+ docWriter.setMaxFieldLength(maxFieldLength);
// Default deleter (for backwards compatibility) is
// KeepOnlyLastCommitDeleter:
@@@ -837,45 -872,7 +872,7 @@@
public IndexWriterConfig getConfig() {
return config;
}
--
- /** Determines the minimal number of documents required
- * before the buffered in-memory documents are flushed as
- * a new Segment. Large values generally gives faster
- * indexing.
- *
- * <p>When this is set, the writer will flush every
- * maxBufferedDocs added documents. Pass in {@link
- * #DISABLE_AUTO_FLUSH} to prevent triggering a flush due
- * to number of buffered documents. Note that if flushing
- * by RAM usage is also enabled, then the flush will be
- * triggered by whichever comes first.</p>
- *
- * <p>Disabled by default (writer flushes by RAM usage).</p>
- *
- * @throws IllegalArgumentException if maxBufferedDocs is
- * enabled but smaller than 2, or it disables maxBufferedDocs
- * when ramBufferSize is already disabled
- * @see #setRAMBufferSizeMB
- * @deprecated use {@link IndexWriterConfig#setMaxBufferedDocs(int)} instead.
- */
- public void setMaxBufferedDocs(int maxBufferedDocs) {
- ensureOpen();
- if (maxBufferedDocs != DISABLE_AUTO_FLUSH && maxBufferedDocs < 2)
- throw new IllegalArgumentException(
- "maxBufferedDocs must at least be 2 when enabled");
- if (maxBufferedDocs == DISABLE_AUTO_FLUSH
- && getRAMBufferSizeMB() == DISABLE_AUTO_FLUSH)
- throw new IllegalArgumentException(
- "at least one of ramBufferSize and maxBufferedDocs must be enabled");
- docWriter.setMaxBufferedDocs(maxBufferedDocs);
- pushMaxBufferedDocs();
- if (infoStream != null)
- message("setMaxBufferedDocs " + maxBufferedDocs);
- // Required so config.getMaxBufferedDocs returns the right value. But this
- // will go away together with the method in 4.0.
- config.setMaxBufferedDocs(maxBufferedDocs);
- }
+
/**
* If we are flushing by doc count (not by RAM usage), and
* using LogDocMergePolicy then push maxBufferedDocs down
@@@ -1099,11 -944,7 +944,7 @@@
public boolean verbose() {
return infoStream != null;
}
-
- final IndexFileDeleter getIndexFileDeleter() {
- return deleter;
- }
--
++
/**
* Commits all changes to an index and closes all
* associated files. Note that this may be a costly
@@@ -1118,7 -959,7 +959,7 @@@
* even though part of it (flushing buffered documents)
* may have succeeded, so the write lock will still be
* held.</p>
-- *
++ *
* <p> If you can correct the underlying cause (eg free up
* some disk space) then you can call close() again.
* Failing that, if you want to force the write lock to be
@@@ -1237,9 -1078,9 +1078,9 @@@
if (infoStream != null)
message("now call final commit()");
--
++
if (!hitOOM) {
- commit(0);
+ commitInternal(null);
}
if (infoStream != null)
@@@ -1250,7 -1091,7 +1091,7 @@@
docWriter = null;
deleter.close();
}
--
++
if (writeLock != null) {
writeLock.release(); // release write lock
writeLock = null;
@@@ -1276,7 -1114,7 +1114,7 @@@
}
/** Returns the Directory used by this index. */
-- public Directory getDirectory() {
++ public Directory getDirectory() {
// Pass false because the flush during closing calls getDirectory
ensureOpen(false);
return directory;
@@@ -1334,10 -1176,26 +1176,26 @@@
return false;
}
+ /**
+ * The maximum number of terms that will be indexed for a single field in a
+ * document. This limits the amount of memory required for indexing, so that
+ * collections with very large files will not crash the indexing process by
+ * running out of memory.<p/>
+ * Note that this effectively truncates large documents, excluding from the
+ * index terms that occur further in the document. If you know your source
+ * documents are large, be sure to set this value high enough to accommodate
+ * the expected size. If you set it to Integer.MAX_VALUE, then the only limit
+ * is your memory, but you should anticipate an OutOfMemoryError.<p/>
+ * By default, no more than 10,000 terms will be indexed for a field.
+ *
+ * @see MaxFieldLength
+ */
+ private int maxFieldLength;
+
/**
* Adds a document to this index. If the document contains more than
- * {@link #setMaxFieldLength(int)} terms for a given field, the remainder are
- * discarded.
- * {@link IndexWriterConfig#setMaxFieldLength(int)} terms for a given field,
++ * {@link IndexWriterConfig#setMaxFieldLength(int)} terms for a given field,
+ * the remainder are discarded.
*
* <p> Note that if an Exception is hit (for example disk full)
* then the index will be consistent, but this document
@@@ -1399,36 -1257,23 +1257,8 @@@
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
- public long addDocument(Document doc, Analyzer analyzer) throws CorruptIndexException, IOException {
- ensureOpen();
- boolean success = false;
- try {
- try {
- long sequenceID = docWriter.addDocument(doc, analyzer);
- success = true;
- return sequenceID;
- } finally {
- if (!success) {
- if (infoStream != null) {
- message("hit exception adding document");
- }
- synchronized (this) {
- // If docWriter has some aborted files that were
- // never incref'd, then we clean them up here
- if (docWriter != null) {
- final Collection<String> files = docWriter.abortedFiles();
- if (files != null) {
- deleter.deleteNewFiles(files);
- }
- }
- }
- }
- }
- } catch (OutOfMemoryError oom) {
- handleOOM(oom, "addDocument");
- }
-
- return -1;
+ public void addDocument(Document doc, Analyzer analyzer) throws CorruptIndexException, IOException {
- ensureOpen();
- boolean doFlush = false;
- boolean success = false;
- try {
- try {
- doFlush = docWriter.updateDocument(doc, analyzer, null);
- success = true;
- } finally {
- if (!success && infoStream != null)
- message("hit exception adding document");
- }
- if (doFlush)
- flush(true, false);
- } catch (OutOfMemoryError oom) {
- handleOOM(oom, "addDocument");
- }
++ updateDocument(null, doc, analyzer);
}
/**
@@@ -1553,28 -1412,18 +1397,14 @@@
throws CorruptIndexException, IOException {
ensureOpen();
try {
- boolean doFlush = false;
boolean success = false;
try {
- long sequenceID = docWriter.updateDocument(term, doc, analyzer);
- doFlush = docWriter.updateDocument(doc, analyzer, term);
++ docWriter.updateDocument(doc, analyzer, term);
success = true;
- return sequenceID;
} finally {
- if (!success) {
-
- if (infoStream != null) {
- message("hit exception updating document");
- }
-
- synchronized (this) {
- // If docWriter has some aborted files that were
- // never incref'd, then we clean them up here
- final Collection<String> files = docWriter.abortedFiles();
- if (files != null) {
- deleter.deleteNewFiles(files);
- }
- }
- }
+ if (!success && infoStream != null)
+ message("hit exception updating document");
}
- if (doFlush) {
- flush(true, false);
- }
} catch (OutOfMemoryError oom) {
handleOOM(oom, "updateDocument");
}
@@@ -1746,7 -1597,8 +1578,8 @@@
synchronized(this) {
resetMergeExceptions();
segmentsToOptimize = new HashSet<SegmentInfo>(segmentInfos);
-
+ optimizeMaxNumSegments = maxNumSegments;
-
++
// Now mark all pending & running merges as optimize
// merge:
for(final MergePolicy.OneMerge merge : pendingMerges) {
@@@ -1812,12 -1664,12 +1645,12 @@@
if (merge.optimize)
return true;
}
--
++
for (final MergePolicy.OneMerge merge : runningMerges) {
if (merge.optimize)
return true;
}
--
++
return false;
}
@@@ -2078,7 -1943,7 +1924,7 @@@
/**
* Delete all documents in the index.
*
-- * <p>This method will drop all buffered documents and will
++ * <p>This method will drop all buffered documents and will
* remove all segments from the index. This change will not be
* visible until a {@link #commit()} has been called. This method
* can be rolled back using {@link #rollback()}.</p>
@@@ -2110,7 -1972,7 +1953,7 @@@
deleter.refresh();
// Don't bother saving any changes in our segmentInfos
-- readerPool.clear(null);
++ readerPool.clear(null);
// Mark that the index has changed
++changeCount;
@@@ -2137,7 -1999,7 +1980,7 @@@
mergeFinish(merge);
}
pendingMerges.clear();
--
++
for (final MergePolicy.OneMerge merge : runningMerges) {
if (infoStream != null)
message("now abort running merge " + merge.segString(directory));
@@@ -2164,7 -2026,7 +2007,7 @@@
message("all running merges have aborted");
} else {
-- // waitForMerges() will ensure any running addIndexes finishes.
++ // waitForMerges() will ensure any running addIndexes finishes.
// It's fine if a new one attempts to start because from our
// caller above the call will see that we are in the
// process of closing, and will throw an
@@@ -2176,7 -2038,7 +2019,7 @@@
/**
* Wait for any currently outstanding merges to finish.
*
-- * <p>It is guaranteed that any merges started prior to calling this method
++ * <p>It is guaranteed that any merges started prior to calling this method
* will have completed once this method completes.</p>
*/
public synchronized void waitForMerges() {
@@@ -2198,15 -2061,6 +2042,15 @@@
deleter.checkpoint(segmentInfos, false);
}
+ synchronized void addNewSegment(SegmentInfo newSegment) throws IOException {
+ segmentInfos.add(newSegment);
+ checkpoint();
+ }
-
- synchronized boolean useCompoundFile(SegmentInfo segmentInfo) {
++
++ synchronized boolean useCompoundFile(SegmentInfo segmentInfo) throws IOException {
+ return mergePolicy.useCompoundFile(segmentInfos, segmentInfo);
+ }
-
++
private synchronized void resetMergeExceptions() {
mergeExceptions = new ArrayList<MergePolicy.OneMerge>();
mergeGen++;
@@@ -2255,11 -2109,11 +2099,11 @@@
* <p>
* <b>NOTE:</b> this method only copies the segments of the incoming indexes
* and does not merge them. Therefore deleted documents are not removed and
-- * the new segments are not merged with the existing ones. Also, the segments
-- * are copied as-is, meaning they are not converted to CFS if they aren't,
-- * and vice-versa. If you wish to do that, you can call {@link #maybeMerge}
++ * the new segments are not merged with the existing ones. Also, the segments
++ * are copied as-is, meaning they are not converted to CFS if they aren't,
++ * and vice-versa. If you wish to do that, you can call {@link #maybeMerge}
* or {@link #optimize} afterwards.
-- *
++ *
* <p>This requires this index not be among those to be added.
*
* <p>
@@@ -2325,13 -2191,13 +2181,12 @@@
}
// Update SI appropriately
- info.setDocStoreSegment(newDsName);
- info.setDocStore(info.getDocStoreOffset(), newDsName, info.getDocStoreIsCompoundFile());
info.dir = directory;
info.name = newSegName;
infos.add(info);
}
-- }
++ }
synchronized (this) {
ensureOpen();
@@@ -2356,8 -2218,8 +2207,8 @@@
* add or delete documents (with another thread) will be
* paused until this method completes.
*
-- * <p>See {@link #addIndexes} for details on transactional
-- * semantics, temporary free space required in the Directory,
++ * <p>See {@link #addIndexes} for details on transactional
++ * semantics, temporary free space required in the Directory,
* and non-CFS segments on an Exception.</p>
*
* <p><b>NOTE</b>: if this method hits an OutOfMemoryError
@@@ -2374,51 -2235,38 +2224,38 @@@
try {
String mergedName = newSegmentName();
SegmentMerger merger = new SegmentMerger(directory, termIndexInterval,
- mergedName, null, codecs, payloadProcessorProvider);
-
+ mergedName, null, codecs, payloadProcessorProvider,
+ ((FieldInfos) docWriter.getFieldInfos().clone()));
-
++
for (IndexReader reader : readers) // add new indexes
merger.add(reader);
--
++
int docCount = merger.merge(); // merge 'em
--
- SegmentInfo info = null;
- synchronized(this) {
- info = new SegmentInfo(mergedName, docCount, directory, false, merger.hasProx(), merger.getCodec());
- setDiagnostics(info, "addIndexes(IndexReader...)");
- segmentInfos.add(info);
- checkpoint();
-
- // Notify DocumentsWriter that the flushed count just increased
- // nocommit
- //docWriter.updateFlushedDocCount(docCount);
++
+ SegmentInfo info = new SegmentInfo(mergedName, docCount, directory,
+ false, merger.fieldInfos().hasProx(), merger.getSegmentCodecs(),
+ merger.fieldInfos().hasVectors());
+ setDiagnostics(info, "addIndexes(IndexReader...)");
+
+ boolean useCompoundFile;
+ synchronized(this) { // Guard segmentInfos
+ useCompoundFile = mergePolicy.useCompoundFile(segmentInfos, info);
}
--
- // Now create the compound file if needed
- if (mergePolicy instanceof LogMergePolicy && getLogMergePolicy().getUseCompoundFile()) {
+
- List<String> files = null;
+ // Now create the compound file if needed
+ if (useCompoundFile) {
+ merger.createCompoundFile(mergedName + ".cfs", info);
+ info.setUseCompoundFile(true);
-
+
- synchronized(this) {
- // Must incRef our files so that if another thread
- // is running merge/optimize, it doesn't delete our
- // segment's files before we have a chance to
- // finish making the compound file.
- if (segmentInfos.contains(info)) {
- files = info.files();
- deleter.incRef(files);
- }
- }
+ // delete new non cfs files directly: they were never
+ // registered with IFD
+ deleter.deleteNewFiles(merger.getMergedFiles(info));
+ }
- if (files != null) {
- try {
- merger.createCompoundFile(mergedName + ".cfs", info);
- synchronized(this) {
- info.setUseCompoundFile(true);
- }
- } finally {
- deleter.decRef(files);
- }
- }
+ // Register the new segment
+ synchronized(this) {
+ segmentInfos.add(info);
+ checkpoint();
}
} catch (OutOfMemoryError oom) {
handleOOM(oom, "addIndexes(IndexReader...)");
@@@ -2460,7 -2308,7 +2297,7 @@@
* #commit()} to finish the commit, or {@link
* #rollback()} to revert the commit and undo all changes
* done since the writer was opened.</p>
-- *
++ *
* You can also just call {@link #commit(Map)} directly
* without prepareCommit first in which case that method
* will internally call prepareCommit.
@@@ -2608,44 -2457,104 +2446,101 @@@
* to the Directory.
* @param triggerMerge if true, we may merge segments (if
* deletes or docs were flushed) if necessary
- * @param flushDocStores if false we are allowed to keep
- * doc stores open to share with the next segment
* @param flushDeletes whether pending deletes should also
- * be flushed
*/
protected final void flush(boolean triggerMerge, boolean flushDeletes) throws CorruptIndexException, IOException {
+
+ // NOTE: this method cannot be sync'd because
+ // maybeMerge() in turn calls mergeScheduler.merge which
+ // in turn can take a long time to run and we don't want
+ // to hold the lock for that. In the case of
+ // ConcurrentMergeScheduler this can lead to deadlock
+ // when it stalls due to too many running merges.
+
// We can be called during close, when closing==true, so we must pass false to ensureOpen:
ensureOpen(false);
-
- doBeforeFlush();
-
- if (flushDeletes) {
- if (applyDeletes()) {
- checkpoint();
- }
+ if (doFlush(flushDeletes) && triggerMerge) {
+ maybeMerge();
}
- boolean maybeMerge = false;
+ }
+
+ // TODO: this method should not have to be entirely
+ // synchronized, ie, merges should be allowed to commit
+ // even while a flush is happening
- private synchronized boolean doFlush(boolean applyAllDeletes) throws CorruptIndexException, IOException {
-
++ private boolean doFlush(boolean applyAllDeletes) throws CorruptIndexException, IOException {
+ if (hitOOM) {
+ throw new IllegalStateException("this writer hit an OutOfMemoryError; cannot flush");
+ }
+
+ doBeforeFlush();
+
+ assert testPoint("startDoFlush");
+
+ // We may be flushing because it was triggered by doc
+ // count, del count, ram usage (in which case flush
+ // pending is already set), or we may be flushing
+ // due to external event eg getReader or commit is
+ // called (in which case we now set it, and this will
+ // pause all threads):
+ flushControl.setFlushPendingNoWait("explicit flush");
+
boolean success = false;
+
try {
- maybeMerge = docWriter.flushAllThreads(flushDeletes) && triggerMerge;
- success = true;
- } finally {
- if (!success) {
- synchronized (this) {
- // If docWriter has some aborted files that were
- // never incref'd, then we clean them up here
- final Collection<String> files = docWriter.abortedFiles();
- if (files != null) {
- deleter.deleteNewFiles(files);
+
+ if (infoStream != null) {
+ message(" start flush: applyAllDeletes=" + applyAllDeletes);
+ message(" index before flush " + segString());
+ }
-
- final SegmentInfo newSegment = docWriter.flush(this, deleter, mergePolicy, segmentInfos);
- if (newSegment != null) {
- setDiagnostics(newSegment, "flush");
- segmentInfos.add(newSegment);
- checkpoint();
- }
+
- if (!applyAllDeletes) {
- // If deletes alone are consuming > 1/2 our RAM
- // buffer, force them all to apply now. This is to
- // prevent too-frequent flushing of a long tail of
- // tiny segments:
- if (flushControl.getFlushDeletes() ||
- (config.getRAMBufferSizeMB() != IndexWriterConfig.DISABLE_AUTO_FLUSH &&
- bufferedDeletes.bytesUsed() > (1024*1024*config.getRAMBufferSizeMB()/2))) {
- applyAllDeletes = true;
- if (infoStream != null) {
- message("force apply deletes bytesUsed=" + bufferedDeletes.bytesUsed() + " vs ramBuffer=" + (1024*1024*config.getRAMBufferSizeMB()));
++ boolean maybeMerge = docWriter.flushAllThreads(applyAllDeletes);
++
++ synchronized(this) {
++
++ if (!applyAllDeletes) {
++ // If deletes alone are consuming > 1/2 our RAM
++ // buffer, force them all to apply now. This is to
++ // prevent too-frequent flushing of a long tail of
++ // tiny segments:
++ if (flushControl.getFlushDeletes() ||
++ (config.getRAMBufferSizeMB() != IndexWriterConfig.DISABLE_AUTO_FLUSH &&
++ bufferedDeletes.bytesUsed() > (1024*1024*config.getRAMBufferSizeMB()/2))) {
++ applyAllDeletes = true;
++ if (infoStream != null) {
++ message("force apply deletes bytesUsed=" + bufferedDeletes.bytesUsed() + " vs ramBuffer=" + (1024*1024*config.getRAMBufferSizeMB()));
++ }
+ }
+ }
- }
+
- if (applyAllDeletes) {
- if (infoStream != null) {
- message("apply all deletes during flush");
- }
- flushDeletesCount.incrementAndGet();
- if (bufferedDeletes.applyDeletes(readerPool, segmentInfos, segmentInfos)) {
- checkpoint();
++ if (applyAllDeletes) {
++ if (infoStream != null) {
++ message("apply all deletes during flush");
++ }
++ flushDeletesCount.incrementAndGet();
++ if (bufferedDeletes.applyDeletes(readerPool, segmentInfos, segmentInfos)) {
++ checkpoint();
+ }
++ flushControl.clearDeletes();
++ } else if (infoStream != null) {
++ message("don't apply deletes now delTermCount=" + bufferedDeletes.numTerms() + " bytesUsed=" + bufferedDeletes.bytesUsed());
}
- flushControl.clearDeletes();
- } else if (infoStream != null) {
- message("don't apply deletes now delTermCount=" + bufferedDeletes.numTerms() + " bytesUsed=" + bufferedDeletes.bytesUsed());
- }
+
- doAfterFlush();
- flushCount.incrementAndGet();
++ doAfterFlush();
++ flushCount.incrementAndGet();
+
- success = true;
++ success = true;
+
- return newSegment != null;
++ return maybeMerge;
+ }
- }
-
- doAfterFlush();
-
- if (maybeMerge) {
- maybeMerge();
+
+ } catch (OutOfMemoryError oom) {
+ handleOOM(oom, "doFlush");
+ // never hit
+ return false;
+ } finally {
+ flushControl.clearFlushPending();
+ if (!success && infoStream != null)
+ message("hit exception during flush");
}
}
@@@ -2654,7 -2563,7 +2549,9 @@@
*/
public final long ramSizeInBytes() {
ensureOpen();
- return docWriter.getRAMUsed();
- return docWriter.bytesUsed() + bufferedDeletes.bytesUsed();
++ // nocommit
++ //return docWriter.bytesUsed() + bufferedDeletes.bytesUsed();
++ return 0;
}
/** Expert: Return the number of documents currently
@@@ -2671,7 -2580,7 +2568,7 @@@
throw new MergePolicy.MergeException("could not find segment " + merge.segments.info(0).name + " in current index " + segString(), directory);
final int numSegments = segmentInfos.size();
--
++
final int numSegmentsToMerge = merge.segments.size();
for(int i=0;i<numSegmentsToMerge;i++) {
final SegmentInfo info = merge.segments.info(i);
@@@ -2794,15 -2703,19 +2691,13 @@@
final int start = ensureContiguousMerge(merge);
commitMergedDeletes(merge, mergedReader);
- // nocommit
- //docWriter.remapDeletes(segmentInfos, merger.getDocMaps(), merger.getDelCounts(), merge, mergedDocCount);
--
- merge.info.setHasProx(merger.hasProx());
- // If the doc store we are using has been closed and
- // is in now compound format (but wasn't when we
- // started), then we will switch to the compound
- // format as well:
- setMergeDocStoreIsCompoundFile(merge);
segmentInfos.subList(start, start + merge.segments.size()).clear();
assert !segmentInfos.contains(merge.info);
segmentInfos.add(start, merge.info);
-
+
+ closeMergeReaders(merge, false);
+
// Must note the change to segmentInfos so any commits
// in-flight don't lose it:
checkpoint();
@@@ -2811,17 -2724,20 +2706,20 @@@
// them so that they don't bother writing them to
// disk, updating SegmentInfo, etc.:
readerPool.clear(merge.segments);
-
- // remove pending deletes of the segments
+
- if (merge.optimize)
++ // remove pending deletes of the segments
+ // that were merged, moving them onto the segment just
+ // before the merged segment
+ // Lock order: IW -> BD
+ bufferedDeletes.commitMerge(merge);
+
+ if (merge.optimize) {
+ // cascade the optimize:
segmentsToOptimize.add(merge.info);
+ }
return true;
}
--
- private synchronized void decrefMergeSegments(MergePolicy.OneMerge merge) throws IOException {
- assert merge.increfDone;
- merge.increfDone = false;
- }
+
final private void handleMergeException(Throwable t, MergePolicy.OneMerge merge) throws IOException {
if (infoStream != null) {
@@@ -2909,7 -2826,7 +2808,7 @@@
/** Hook that's called when the specified merge is complete. */
void mergeSuccess(MergePolicy.OneMerge merge) {
}
--
++
/** Checks whether this merge involves any segments
* already participating in a merge. If not, this merge
* is "registered", meaning we record that its segments
@@@ -3019,12 -2943,12 +2925,12 @@@
// CFS:
mergingSegments.add(merge.info);
}
-
+
- private void setDiagnostics(SegmentInfo info, String source) {
+ static void setDiagnostics(SegmentInfo info, String source) {
setDiagnostics(info, source, null);
}
-
- static void setDiagnostics(SegmentInfo info, String source, Map<String,String> details) {
+
- private void setDiagnostics(SegmentInfo info, String source, Map<String,String> details) {
++ private static void setDiagnostics(SegmentInfo info, String source, Map<String,String> details) {
Map<String,String> diagnostics = new HashMap<String,String>();
diagnostics.put("source", source);
diagnostics.put("lucene.version", Constants.LUCENE_VERSION);
@@@ -3042,7 -2966,7 +2948,7 @@@
/** Does fininishing for a merge, which is fast but holds
* the synchronized lock on IndexWriter instance. */
final synchronized void mergeFinish(MergePolicy.OneMerge merge) throws IOException {
--
++
// Optimize, addIndexes or finishMerges may be waiting
// on merges to finish.
notifyAll();
@@@ -3069,18 -2985,79 +2967,62 @@@
runningMerges.remove(merge);
}
- private synchronized void setMergeDocStoreIsCompoundFile(MergePolicy.OneMerge merge) {
- final String mergeDocStoreSegment = merge.info.getDocStoreSegment();
- if (mergeDocStoreSegment != null && !merge.info.getDocStoreIsCompoundFile()) {
- final int size = segmentInfos.size();
- for(int i=0;i<size;i++) {
- final SegmentInfo info = segmentInfos.info(i);
- final String docStoreSegment = info.getDocStoreSegment();
- if (docStoreSegment != null &&
- docStoreSegment.equals(mergeDocStoreSegment) &&
- info.getDocStoreIsCompoundFile()) {
- merge.info.setDocStoreIsCompoundFile(true);
- break;
- }
- }
- }
- }
-
+ private synchronized void closeMergeReaders(MergePolicy.OneMerge merge, boolean suppressExceptions) throws IOException {
+ final int numSegments = merge.segments.size();
+ if (suppressExceptions) {
+ // Suppress any new exceptions so we throw the
+ // original cause
+ boolean anyChanges = false;
+ for (int i=0;i<numSegments;i++) {
+ if (merge.readers[i] != null) {
+ try {
+ anyChanges |= readerPool.release(merge.readers[i], false);
+ } catch (Throwable t) {
+ }
+ merge.readers[i] = null;
+ }
+
+ if (merge.readersClone[i] != null) {
+ try {
+ merge.readersClone[i].close();
+ } catch (Throwable t) {
+ }
+ // This was a private clone and we had the
+ // only reference
+ assert merge.readersClone[i].getRefCount() == 0: "refCount should be 0 but is " + merge.readersClone[i].getRefCount();
+ merge.readersClone[i] = null;
+ }
+ }
+ if (anyChanges) {
+ checkpoint();
+ }
+ } else {
+ for (int i=0;i<numSegments;i++) {
+ if (merge.readers[i] != null) {
+ readerPool.release(merge.readers[i], true);
+ merge.readers[i] = null;
+ }
+
+ if (merge.readersClone[i] != null) {
+ merge.readersClone[i].close();
+ // This was a private clone and we had the only reference
+ assert merge.readersClone[i].getRefCount() == 0;
+ merge.readersClone[i] = null;
+ }
+ }
+ }
+ }
+
/** Does the actual (time-consuming) work of the merge,
* but without holding synchronized lock on IndexWriter
* instance */
- final private int mergeMiddle(MergePolicy.OneMerge merge)
+ private int mergeMiddle(MergePolicy.OneMerge merge)
throws CorruptIndexException, IOException {
--
++
merge.checkAborted(directory);
final String mergedName = merge.info.name;
--
- SegmentMerger merger = null;
+
int mergedDocCount = 0;
SegmentInfos sourceSegments = merge.segments;
@@@ -3133,8 -3109,13 +3074,13 @@@
mergedDocCount = merge.info.docCount = merger.merge();
// Record which codec was used to write the segment
- merge.info.setCodec(merger.getCodec());
-
+ merge.info.setSegmentCodecs(merger.getSegmentCodecs());
+
+ if (infoStream != null) {
+ message("merge segmentCodecs=" + merger.getSegmentCodecs());
+ message("merge store matchedCount=" + merger.getMatchedSubReaderCount() + " vs " + numSegments);
+ }
-
++
assert mergedDocCount == totDocCount;
// Very important to do this before opening the reader
@@@ -3408,36 -3330,35 +3295,35 @@@
synchronized(this) {
assert lastCommitChangeCount <= changeCount;
-
+ myChangeCount = changeCount;
-
++
if (changeCount == lastCommitChangeCount) {
if (infoStream != null)
message(" skip startCommit(): no changes pending");
return;
}
--
++
// First, we clone & incref the segmentInfos we intend
- // to sync, then, without locking, we sync() each file
- // referenced by toSync, in the background. Multiple
- // threads can be doing this at once, if say a large
- // merge and a small merge finish at the same time:
-
+ // to sync, then, without locking, we sync() all files
+ // referenced by toSync, in the background.
-
++
if (infoStream != null)
message("startCommit index=" + segString(segmentInfos) + " changeCount=" + changeCount);
-
+
readerPool.commit();
--
++
toSync = (SegmentInfos) segmentInfos.clone();
-
+ assert filesExist(toSync);
-
++
if (commitUserData != null)
toSync.setUserData(commitUserData);
--
++
+ // This protects the segmentInfos we are now going
+ // to commit. This is important in case, eg, while
+ // we are trying to sync all referenced files, a
+ // merge completes which would otherwise have
+ // removed the files we are now syncing.
deleter.incRef(toSync, false);
- myChangeCount = changeCount;
-
- Collection<String> files = toSync.files(directory, false);
- for(final String fileName: files) {
- assert directory.fileExists(fileName): "file " + fileName + " does not exist";
- }
}
assert testPoint("midStartCommit");
@@@ -3675,7 -3486,7 +3451,7 @@@
/** Expert: remove any index files that are no longer
* used.
-- *
++ *
* <p> IndexWriter normally deletes unused files itself,
* during indexing. However, on Windows, which disallows
* deletion of open files, if there is a reader open on
@@@ -3689,10 -3500,10 +3465,10 @@@
* IndexWriter, you'll see the unused files linger. If
* that's a problem, call this method to delete them
* (once you've closed the open readers that were
-- * preventing their deletion).
-- *
-- * <p> In addition, you can call this method to delete
-- * unreferenced index commits. This might be useful if you
++ * preventing their deletion).
++ *
++ * <p> In addition, you can call this method to delete
++ * unreferenced index commits. This might be useful if you
* are using an {@link IndexDeletionPolicy} which holds
* onto index commits until some criteria are met, but those
* commits are no longer needed. Otherwise, those commits will
@@@ -3725,7 -3535,7 +3500,7 @@@
public void setPayloadProcessorProvider(PayloadProcessorProvider pcp) {
payloadProcessorProvider = pcp;
}
--
++
/**
* Returns the {@link PayloadProcessorProvider} that is used during segment
* merges to process payloads.
@@@ -3734,4 -3544,123 +3509,124 @@@
return payloadProcessorProvider;
}
+ // decides when flushes happen
+ final class FlushControl {
+
+ private boolean flushPending;
+ private boolean flushDeletes;
+ private int delCount;
+ private int docCount;
+ private boolean flushing;
+
+ private synchronized boolean setFlushPending(String reason, boolean doWait) {
+ if (flushPending || flushing) {
+ if (doWait) {
+ while(flushPending || flushing) {
+ try {
+ wait();
+ } catch (InterruptedException ie) {
+ throw new ThreadInterruptedException(ie);
+ }
+ }
+ }
+ return false;
+ } else {
+ if (infoStream != null) {
+ message("now trigger flush reason=" + reason);
+ }
+ flushPending = true;
+ return flushPending;
+ }
+ }
+
+ public synchronized void setFlushPendingNoWait(String reason) {
+ setFlushPending(reason, false);
+ }
+
+ public synchronized boolean getFlushPending() {
+ return flushPending;
+ }
+
+ public synchronized boolean getFlushDeletes() {
+ return flushDeletes;
+ }
+
+ public synchronized void clearFlushPending() {
+ if (infoStream != null) {
+ message("clearFlushPending");
+ }
+ flushPending = false;
+ flushDeletes = false;
+ docCount = 0;
+ notifyAll();
+ }
+
+ public synchronized void clearDeletes() {
+ delCount = 0;
+ }
+
+ public synchronized boolean waitUpdate(int docInc, int delInc) {
+ return waitUpdate(docInc, delInc, false);
+ }
+
+ public synchronized boolean waitUpdate(int docInc, int delInc, boolean skipWait) {
+ while(flushPending) {
+ try {
+ wait();
+ } catch (InterruptedException ie) {
+ throw new ThreadInterruptedException(ie);
+ }
+ }
+
+ // skipWait is only used when a thread is BOTH adding
+ // a doc and buffering a del term, and, the adding of
+ // the doc already triggered a flush
+ if (skipWait) {
+ docCount += docInc;
+ delCount += delInc;
+ return false;
+ }
+
+ final int maxBufferedDocs = config.getMaxBufferedDocs();
+ if (maxBufferedDocs != IndexWriterConfig.DISABLE_AUTO_FLUSH &&
+ (docCount+docInc) >= maxBufferedDocs) {
+ return setFlushPending("maxBufferedDocs", true);
+ }
+ docCount += docInc;
+
+ final int maxBufferedDeleteTerms = config.getMaxBufferedDeleteTerms();
+ if (maxBufferedDeleteTerms != IndexWriterConfig.DISABLE_AUTO_FLUSH &&
+ (delCount+delInc) >= maxBufferedDeleteTerms) {
+ flushDeletes = true;
+ return setFlushPending("maxBufferedDeleteTerms", true);
+ }
+ delCount += delInc;
+
+ return flushByRAMUsage("add delete/doc");
+ }
+
+ public synchronized boolean flushByRAMUsage(String reason) {
- final double ramBufferSizeMB = config.getRAMBufferSizeMB();
- if (ramBufferSizeMB != IndexWriterConfig.DISABLE_AUTO_FLUSH) {
- final long limit = (long) (ramBufferSizeMB*1024*1024);
- long used = bufferedDeletes.bytesUsed() + docWriter.bytesUsed();
- if (used >= limit) {
-
- // DocumentsWriter may be able to free up some
- // RAM:
- // Lock order: FC -> DW
- docWriter.balanceRAM();
-
- used = bufferedDeletes.bytesUsed() + docWriter.bytesUsed();
- if (used >= limit) {
- return setFlushPending("ram full: " + reason, false);
- }
- }
- }
++ // nocommit
++// final double ramBufferSizeMB = config.getRAMBufferSizeMB();
++// if (ramBufferSizeMB != IndexWriterConfig.DISABLE_AUTO_FLUSH) {
++// final long limit = (long) (ramBufferSizeMB*1024*1024);
++// long used = bufferedDeletes.bytesUsed() + docWriter.bytesUsed();
++// if (used >= limit) {
++//
++// // DocumentsWriter may be able to free up some
++// // RAM:
++// // Lock order: FC -> DW
++// docWriter.balanceRAM();
++//
++// used = bufferedDeletes.bytesUsed() + docWriter.bytesUsed();
++// if (used >= limit) {
++// return setFlushPending("ram full: " + reason, false);
++// }
++// }
++// }
+ return false;
+ }
+ }
+
+ final FlushControl flushControl = new FlushControl();
}
diff --cc lucene/src/java/org/apache/lucene/index/IndexWriterConfig.java
index 5e179af58fa,4b25cabde37..7d8bb99b711
--- a/lucene/src/java/org/apache/lucene/index/IndexWriterConfig.java
+++ b/lucene/src/java/org/apache/lucene/index/IndexWriterConfig.java
@@@ -156,12 -153,12 +153,12 @@@ public final class IndexWriterConfig im
maxBufferedDeleteTerms = DEFAULT_MAX_BUFFERED_DELETE_TERMS;
ramBufferSizeMB = DEFAULT_RAM_BUFFER_SIZE_MB;
maxBufferedDocs = DEFAULT_MAX_BUFFERED_DOCS;
- indexingChain = DocumentsWriter.defaultIndexingChain;
+ indexingChain = DocumentsWriterPerThread.defaultIndexingChain;
mergedSegmentWarmer = null;
- codecProvider = DEFAULT_CODEC_PROVIDER;
+ codecProvider = CodecProvider.getDefault();
mergePolicy = new LogByteSizeMergePolicy();
- maxThreadStates = DEFAULT_MAX_THREAD_STATES;
readerPooling = DEFAULT_READER_POOLING;
+ indexerThreadPool = new ThreadAffinityDocumentsWriterThreadPool(DEFAULT_MAX_THREAD_STATES);
readerTermsIndexDivisor = DEFAULT_READER_TERMS_INDEX_DIVISOR;
}
diff --cc lucene/src/java/org/apache/lucene/index/IntBlockPool.java
index 253a471b344,013c7b3248f..fb57899cd2f
--- a/lucene/src/java/org/apache/lucene/index/IntBlockPool.java
+++ b/lucene/src/java/org/apache/lucene/index/IntBlockPool.java
@@@ -22,14 -22,14 +22,14 @@@ final class IntBlockPool
public int[][] buffers = new int[10][];
int bufferUpto = -1; // Which buffer we are upto
- public int intUpto = DocumentsWriterRAMAllocator.INT_BLOCK_SIZE; // Where we are in head buffer
- public int intUpto = DocumentsWriter.INT_BLOCK_SIZE; // Where we are in head buffer
++ public int intUpto = DocumentsWriterPerThread.INT_BLOCK_SIZE; // Where we are in head buffer
public int[] buffer; // Current head buffer
- public int intOffset = -DocumentsWriterRAMAllocator.INT_BLOCK_SIZE; // Current head offset
- public int intOffset = -DocumentsWriter.INT_BLOCK_SIZE; // Current head offset
++ public int intOffset = -DocumentsWriterPerThread.INT_BLOCK_SIZE; // Current head offset
- final private DocumentsWriter docWriter;
+ final private DocumentsWriterPerThread docWriter;
- public IntBlockPool(DocumentsWriter docWriter) {
+ public IntBlockPool(DocumentsWriterPerThread docWriter) {
this.docWriter = docWriter;
}
@@@ -57,7 -57,7 +57,7 @@@
bufferUpto++;
intUpto = 0;
- intOffset += DocumentsWriterRAMAllocator.INT_BLOCK_SIZE;
- intOffset += DocumentsWriter.INT_BLOCK_SIZE;
++ intOffset += DocumentsWriterPerThread.INT_BLOCK_SIZE;
}
}
diff --cc lucene/src/java/org/apache/lucene/index/InvertedDocConsumer.java
index 6284ae5b6e2,063a920b7b6..bc384b2a1df
--- a/lucene/src/java/org/apache/lucene/index/InvertedDocConsumer.java
+++ b/lucene/src/java/org/apache/lucene/index/InvertedDocConsumer.java
@@@ -26,14 -30,8 +26,14 @@@ abstract class InvertedDocConsumer
abstract void abort();
/** Flush a new segment */
- abstract void flush(Map<InvertedDocConsumerPerThread,Collection<InvertedDocConsumerPerField>> threadsAndFields, SegmentWriteState state) throws IOException;
+ abstract void flush(Map<FieldInfo, InvertedDocConsumerPerField> fieldsToFlush, SegmentWriteState state) throws IOException;
+
+ abstract InvertedDocConsumerPerField addField(DocInverterPerField docInverterPerField, FieldInfo fieldInfo);
-
++
+ abstract void startDocument() throws IOException;
-
++
+ abstract void finishDocument() throws IOException;
-
+
/** Attempt to free RAM, returning true if any RAM was
* freed */
abstract boolean freeRAM();
diff --cc lucene/src/java/org/apache/lucene/index/LogMergePolicy.java
index 8992b25c588,4b1d305647c..e1f06ab2c13
--- a/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java
+++ b/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java
@@@ -54,16 -54,22 +54,22 @@@ public abstract class LogMergePolicy ex
* or larger will never be merged. @see setMaxMergeDocs */
public static final int DEFAULT_MAX_MERGE_DOCS = Integer.MAX_VALUE;
- private int mergeFactor = DEFAULT_MERGE_FACTOR;
+ /** Default noCFSRatio. If a merge's size is >= 10% of
+ * the index, then we disable compound file for it.
+ * @see #setNoCFSRatio */
+ public static final double DEFAULT_NO_CFS_RATIO = 0.1;
- long minMergeSize;
- long maxMergeSize;
- int maxMergeDocs = DEFAULT_MAX_MERGE_DOCS;
+ protected int mergeFactor = DEFAULT_MERGE_FACTOR;
- /* TODO 3.0: change this default to true */
- protected boolean calibrateSizeByDeletes = false;
-
- private boolean useCompoundFile = true;
+ protected long minMergeSize;
+ protected long maxMergeSize;
+ protected int maxMergeDocs = DEFAULT_MAX_MERGE_DOCS;
+
+ protected double noCFSRatio = DEFAULT_NO_CFS_RATIO;
+
+ protected boolean calibrateSizeByDeletes = true;
-
++
+ protected boolean useCompoundFile = true;
public LogMergePolicy() {
super();
@@@ -73,8 -79,25 +79,25 @@@
IndexWriter w = writer.get();
return w != null && w.verbose();
}
-
- private void message(String message) {
+
+ /** @see #setNoCFSRatio */
+ public double getNoCFSRatio() {
+ return noCFSRatio;
+ }
+
+ /** If a merged segment will be more than this percentage
+ * of the total size of the index, leave the segment as
+ * non-compound file even if compound file is enabled.
+ * Set to 1.0 to always use CFS regardless of merge
+ * size. */
+ public void setNoCFSRatio(double noCFSRatio) {
+ if (noCFSRatio < 0.0 || noCFSRatio > 1.0) {
+ throw new IllegalArgumentException("noCFSRatio must be 0.0 to 1.0 inclusive; got " + noCFSRatio);
+ }
+ this.noCFSRatio = noCFSRatio;
+ }
-
++
+ protected void message(String message) {
if (verbose())
writer.get().message("LMP: " + message);
}
@@@ -126,7 -162,7 +162,7 @@@
this.calibrateSizeByDeletes = calibrateSizeByDeletes;
}
-- /** Returns true if the segment size should be calibrated
++ /** Returns true if the segment size should be calibrated
* by the number of deletes when choosing segments for merge. */
public boolean getCalibrateSizeByDeletes() {
return calibrateSizeByDeletes;
@@@ -145,19 -182,20 +182,20 @@@
return info.docCount;
}
}
--
++
protected long sizeBytes(SegmentInfo info) throws IOException {
- long byteSize = info.sizeInBytes();
+ long byteSize = info.sizeInBytes(true);
if (calibrateSizeByDeletes) {
int delCount = writer.get().numDeletedDocs(info);
- float delRatio = (info.docCount <= 0 ? 0.0f : ((float)delCount / (float)info.docCount));
- return (info.docCount <= 0 ? byteSize : (long)(byteSize * (1.0f - delRatio)));
+ double delRatio = (info.docCount <= 0 ? 0.0f : ((float)delCount / (float)info.docCount));
+ assert delRatio <= 1.0;
+ return (info.docCount <= 0 ? byteSize : (long)(byteSize * (1.0 - delRatio)));
} else {
return byteSize;
}
}
--
- private boolean isOptimized(SegmentInfos infos, int maxNumSegments, Set<SegmentInfo> segmentsToOptimize) throws IOException {
++
+ protected boolean isOptimized(SegmentInfos infos, int maxNumSegments, Set<SegmentInfo> segmentsToOptimize) throws IOException {
final int numSegments = infos.size();
int numToOptimize = 0;
SegmentInfo optimizeInfo = null;
@@@ -184,9 -222,106 +222,106 @@@
return !hasDeletions &&
!info.hasSeparateNorms() &&
info.dir == w.getDirectory() &&
- info.getUseCompoundFile() == useCompoundFile;
+ (info.getUseCompoundFile() == useCompoundFile || noCFSRatio < 1.0);
+ }
+
+ /**
+ * Returns the merges necessary to optimize the index, taking the max merge
+ * size or max merge docs into consideration. This method attempts to respect
+ * the {@code maxNumSegments} parameter, however it might be, due to size
+ * constraints, that more than that number of segments will remain in the
+ * index. Also, this method does not guarantee that exactly {@code
+ * maxNumSegments} will remain, but &lt;= that number.
+ */
+ private MergeSpecification findMergesForOptimizeSizeLimit(
+ SegmentInfos infos, int maxNumSegments, int last) throws IOException {
+ MergeSpecification spec = new MergeSpecification();
+
+ int start = last - 1;
+ while (start >= 0) {
+ SegmentInfo info = infos.info(start);
+ if (size(info) > maxMergeSize || sizeDocs(info) > maxMergeDocs) {
+ // need to skip that segment + add a merge for the 'right' segments,
+ // unless there is only 1 which is optimized.
+ if (last - start - 1 > 1 || (start != last - 1 && !isOptimized(infos.info(start + 1)))) {
+ // there is more than 1 segment to the right of this one, or an unoptimized single segment.
+ spec.add(new OneMerge(infos.range(start + 1, last)));
+ }
+ last = start;
+ } else if (last - start == mergeFactor) {
+ // mergeFactor eligible segments were found, add them as a merge.
+ spec.add(new OneMerge(infos.range(start, last)));
+ last = start;
+ }
+ --start;
+ }
+
+ // Add any left-over segments, unless there is just 1 already optimized.
+ if (last > 0 && (++start + 1 < last || !isOptimized(infos.info(start)))) {
+ spec.add(new OneMerge(infos.range(start, last)));
+ }
+
+ return spec.merges.size() == 0 ? null : spec;
+ }
-
++
+ /**
+ * Returns the merges necessary to optimize the index. This method constraints
+ * the returned merges only by the {@code maxNumSegments} parameter, and
+ * guaranteed that exactly that number of segments will remain in the index.
+ */
+ private MergeSpecification findMergesForOptimizeMaxNumSegments(SegmentInfos infos, int maxNumSegments, int last) throws IOException {
+ MergeSpecification spec = new MergeSpecification();
-
++
+ // First, enroll all "full" merges (size
+ // mergeFactor) to potentially be run concurrently:
+ while (last - maxNumSegments + 1 >= mergeFactor) {
+ spec.add(new OneMerge(infos.range(last - mergeFactor, last)));
+ last -= mergeFactor;
+ }
+
+ // Only if there are no full merges pending do we
+ // add a final partial (< mergeFactor segments) merge:
+ if (0 == spec.merges.size()) {
+ if (maxNumSegments == 1) {
+
+ // Since we must optimize down to 1 segment, the
+ // choice is simple:
+ if (last > 1 || !isOptimized(infos.info(0))) {
+ spec.add(new OneMerge(infos.range(0, last)));
+ }
+ } else if (last > maxNumSegments) {
+
+ // Take care to pick a partial merge that is
+ // least cost, but does not make the index too
+ // lopsided. If we always just picked the
+ // partial tail then we could produce a highly
+ // lopsided index over time:
+
+ // We must merge this many segments to leave
+ // maxNumSegments in the index (from when
+ // optimize was first kicked off):
+ final int finalMergeSize = last - maxNumSegments + 1;
+
+ // Consider all possible starting points:
+ long bestSize = 0;
+ int bestStart = 0;
+
+ for(int i=0;i<last-finalMergeSize+1;i++) {
+ long sumSize = 0;
+ for(int j=0;j<finalMergeSize;j++)
+ sumSize += size(infos.info(j+i));
+ if (i == 0 || (sumSize < 2*size(infos.info(i-1)) && sumSize < bestSize)) {
+ bestStart = i;
+ bestSize = sumSize;
+ }
+ }
+
+ spec.add(new OneMerge(infos.range(bestStart, bestStart + finalMergeSize)));
+ }
+ }
+ return spec.merges.size() == 0 ? null : spec;
}
-
+
/** Returns the merges necessary to optimize the index.
* This merge policy defines "optimized" to mean only one
* segment in the index, where that segment has no
@@@ -201,85 -336,49 +336,49 @@@
assert maxNumSegments > 0;
- if (!isOptimized(infos, maxNumSegments, segmentsToOptimize)) {
+ // If the segments are already optimized (e.g. there's only 1 segment), or
+ // there are <maxNumSegements, all optimized, nothing to do.
+ if (isOptimized(infos, maxNumSegments, segmentsToOptimize)) return null;
-
+
- // Find the newest (rightmost) segment that needs to
- // be optimized (other segments may have been flushed
- // since optimize started):
- int last = infos.size();
- while(last > 0) {
- final SegmentInfo info = infos.info(--last);
- if (segmentsToOptimize.contains(info)) {
- last++;
- break;
- }
+ // Find the newest (rightmost) segment that needs to
+ // be optimized (other segments may have been flushed
+ // since optimize started):
+ int last = infos.size();
+ while (last > 0) {
+ final SegmentInfo info = infos.info(--last);
+ if (segmentsToOptimize.contains(info)) {
+ last++;
+ break;
}
+ }
- if (last > 0) {
-
- spec = new MergeSpecification();
+ if (last == 0) return null;
-
+
- // First, enroll all "full" merges (size
- // mergeFactor) to potentially be run concurrently:
- while (last - maxNumSegments + 1 >= mergeFactor) {
- spec.add(new OneMerge(infos.range(last-mergeFactor, last), useCompoundFile));
- last -= mergeFactor;
- }
+ // There is only one segment already, and it is optimized
+ if (maxNumSegments == 1 && last == 1 && isOptimized(infos.info(0))) return null;
- // Only if there are no full merges pending do we
- // add a final partial (< mergeFactor segments) merge:
- if (0 == spec.merges.size()) {
- if (maxNumSegments == 1) {
-
- // Since we must optimize down to 1 segment, the
- // choice is simple:
- if (last > 1 || !isOptimized(infos.info(0)))
- spec.add(new OneMerge(infos.range(0, last), useCompoundFile));
- } else if (last > maxNumSegments) {
-
- // Take care to pick a partial merge that is
- // least cost, but does not make the index too
- // lopsided. If we always just picked the
- // partial tail then we could produce a highly
- // lopsided index over time:
-
- // We must merge this many segments to leave
- // maxNumSegments in the index (from when
- // optimize was first kicked off):
- final int finalMergeSize = last - maxNumSegments + 1;
-
- // Consider all possible starting points:
- long bestSize = 0;
- int bestStart = 0;
-
- for(int i=0;i<last-finalMergeSize+1;i++) {
- long sumSize = 0;
- for(int j=0;j<finalMergeSize;j++)
- sumSize += size(infos.info(j+i));
- if (i == 0 || (sumSize < 2*size(infos.info(i-1)) && sumSize < bestSize)) {
- bestStart = i;
- bestSize = sumSize;
- }
- }
-
- spec.add(new OneMerge(infos.range(bestStart, bestStart+finalMergeSize), useCompoundFile));
- }
- }
-
- } else
- spec = null;
- } else
- spec = null;
+ // Check if there are any segments above the threshold
+ boolean anyTooLarge = false;
+ for (int i = 0; i < last; i++) {
+ SegmentInfo info = infos.info(i);
+ if (size(info) > maxMergeSize || sizeDocs(info) > maxMergeDocs) {
+ anyTooLarge = true;
+ break;
+ }
+ }
-
+
- return spec;
+ if (anyTooLarge) {
+ return findMergesForOptimizeSizeLimit(infos, maxNumSegments, last);
+ } else {
+ return findMergesForOptimizeMaxNumSegments(infos, maxNumSegments, last);
+ }
}
/**
* Finds merges necessary to expunge all deletes from the
* index. We simply merge adjacent segments that have
* deletes, up to mergeFactor at a time.
-- */
++ */
@Override
public MergeSpecification findMergesToExpungeDeletes(SegmentInfos segmentInfos)
throws CorruptIndexException, IOException {
@@@ -462,4 -561,17 +561,17 @@@
return maxMergeDocs;
}
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder("[" + getClass().getSimpleName() + ": ");
+ sb.append("minMergeSize=").append(minMergeSize).append(", ");
+ sb.append("mergeFactor=").append(mergeFactor).append(", ");
+ sb.append("maxMergeSize=").append(maxMergeSize).append(", ");
+ sb.append("calibrateSizeByDeletes=").append(calibrateSizeByDeletes).append(", ");
+ sb.append("maxMergeDocs=").append(maxMergeDocs).append(", ");
+ sb.append("useCompoundFile=").append(useCompoundFile);
+ sb.append("]");
+ return sb.toString();
+ }
-
++
}
diff --cc lucene/src/java/org/apache/lucene/index/SegmentInfo.java
index d8d93379ebb,ff621277dd2..465b3398237
--- a/lucene/src/java/org/apache/lucene/index/SegmentInfo.java
+++ b/lucene/src/java/org/apache/lucene/index/SegmentInfo.java
@@@ -35,14 -35,14 +35,14 @@@ import java.util.ArrayList
/**
* Information about a segment such as it's name, directory, and files related
* to the segment.
-- *
++ *
* @lucene.experimental
*/
public final class SegmentInfo {
static final int NO = -1; // e.g. no norms; no deletes;
static final int YES = 1; // e.g. have norms; have deletes;
-- static final int WITHOUT_GEN = 0; // a file name that has no GEN in it.
++ static final int WITHOUT_GEN = 0; // a file name that has no GEN in it.
public String name; // unique name in dir
public int docCount; // number of docs in seg
@@@ -54,16 -54,16 +54,16 @@@
* - YES or higher if there are deletes at generation N
*/
private long delGen;
--
++
/*
* Current generation of each field's norm file. If this array is null,
* means no separate norms. If this array is not null, its values mean:
* - NO says this field has no separate norms
* >= YES says this field has separate norms with the specified generation
*/
-- private long[] normGen;
++ private long[] normGen;
-- private boolean isCompoundFile;
++ private boolean isCompoundFile;
private List<String> files; // cached list of files that this segment uses
// in the Directory
@@@ -201,21 -175,52 +177,52 @@@
assert delCount <= docCount;
hasProx = input.readByte() == YES;
--
++
// System.out.println(Thread.currentThread().getName() + ": si.read hasProx=" + hasProx + " seg=" + name);
-
- if (format <= DefaultSegmentInfosWriter.FORMAT_4_0)
- codecName = input.readString();
- else
- codecName = "PreFlex";
-
+ segmentCodecs = new SegmentCodecs(codecs);
+ if (format <= DefaultSegmentInfosWriter.FORMAT_4_0) {
+ segmentCodecs.read(input);
+ } else {
+ // codec ID on FieldInfo is 0 so it will simply use the first codec available
+ // TODO what todo if preflex is not available in the provider? register it or fail?
+ segmentCodecs.codecs = new Codec[] { codecs.lookup("PreFlex")};
+ }
diagnostics = input.readStringStringMap();
- codec = codecs.lookup(codecName);
-
++
+ if (format <= DefaultSegmentInfosWriter.FORMAT_HAS_VECTORS) {
+ hasVectors = input.readByte() == 1;
+ } else {
+ final String storesSegment;
+ final String ext;
+ final boolean isCompoundFile;
+ if (docStoreOffset != -1) {
+ storesSegment = docStoreSegment;
+ isCompoundFile = docStoreIsCompoundFile;
+ ext = IndexFileNames.COMPOUND_FILE_STORE_EXTENSION;
+ } else {
+ storesSegment = name;
+ isCompoundFile = getUseCompoundFile();
+ ext = IndexFileNames.COMPOUND_FILE_EXTENSION;
+ }
+ final Directory dirToTest;
+ if (isCompoundFile) {
+ dirToTest = new CompoundFileReader(dir, IndexFileNames.segmentFileName(storesSegment, "", ext));
+ } else {
+ dirToTest = dir;
+ }
+ try {
+ hasVectors = dirToTest.fileExists(IndexFileNames.segmentFileName(storesSegment, "", IndexFileNames.VECTORS_INDEX_EXTENSION));
+ } finally {
+ if (isCompoundFile) {
+ dirToTest.close();
+ }
+ }
+ }
}
--
++
/** Returns total size in bytes of all of files used by
* this segment. */
- public long sizeInBytes() throws IOException {
+ public long sizeInBytes(boolean includeDocStores) throws IOException {
if (sizeInBytes == -1) {
List<String> files = files();
final int size = files.size();
@@@ -278,7 -293,7 +295,7 @@@
// against this segment
return null;
} else {
-- return IndexFileNames.fileNameFromGeneration(name, IndexFileNames.DELETES_EXTENSION, delGen);
++ return IndexFileNames.fileNameFromGeneration(name, IndexFileNames.DELETES_EXTENSION, delGen);
}
}
@@@ -339,7 -354,7 +356,7 @@@
if (hasSeparateNorms(number)) {
return IndexFileNames.fileNameFromGeneration(name, "s" + number, normGen[number]);
} else {
-- // single file for all norms
++ // single file for all norms
return IndexFileNames.fileNameFromGeneration(name, IndexFileNames.NORMS_EXTENSION, WITHOUT_GEN);
}
}
@@@ -376,23 -390,36 +393,28 @@@
public int getDocStoreOffset() {
return docStoreOffset;
}
--
++
+ @Deprecated
public boolean getDocStoreIsCompoundFile() {
return docStoreIsCompoundFile;
}
-
- void setDocStoreIsCompoundFile(boolean v) {
- docStoreIsCompoundFile = v;
- clearFiles();
- }
--
++
+ @Deprecated
public String getDocStoreSegment() {
return docStoreSegment;
}
-
- public void setDocStoreSegment(String segment) {
- docStoreSegment = segment;
- }
-
+
++ @Deprecated
+ void setDocStoreOffset(int offset) {
+ docStoreOffset = offset;
+ clearFiles();
+ }
+
- void setDocStore(int offset, String segment, boolean isCompoundFile) {
- docStoreOffset = offset;
- docStoreSegment = segment;
- docStoreIsCompoundFile = isCompoundFile;
- clearFiles();
+ @Deprecated
+ public void setDocStoreSegment(String docStoreSegment) {
+ this.docStoreSegment = docStoreSegment;
- clearFiles();
}
--
++
/** Save this segment's info. */
public void write(IndexOutput output)
throws IOException {
@@@ -416,7 -441,7 +438,7 @@@
output.writeLong(fieldNormGen);
}
}
--
++
output.writeByte((byte) (isCompoundFile ? YES : NO));
output.writeInt(delCount);
output.writeByte((byte) (hasProx ? 1:0));
@@@ -463,9 -489,9 +486,9 @@@
// Already cached:
return files;
}
--
++
Set<String> fileSet = new HashSet<String>();
--
++
boolean useCompoundFile = getUseCompoundFile();
if (useCompoundFile) {
@@@ -484,12 -510,22 +507,22 @@@
if (docStoreIsCompoundFile) {
fileSet.add(IndexFileNames.segmentFileName(docStoreSegment, "", IndexFileNames.COMPOUND_FILE_STORE_EXTENSION));
} else {
- for (String ext : IndexFileNames.STORE_INDEX_EXTENSIONS)
- addIfExists(fileSet, IndexFileNames.segmentFileName(docStoreSegment, "", ext));
+ fileSet.add(IndexFileNames.segmentFileName(docStoreSegment, "", IndexFileNames.FIELDS_INDEX_EXTENSION));
+ fileSet.add(IndexFileNames.segmentFileName(docStoreSegment, "", IndexFileNames.FIELDS_EXTENSION));
+ if (hasVectors) {
+ fileSet.add(IndexFileNames.segmentFileName(docStoreSegment, "", IndexFileNames.VECTORS_INDEX_EXTENSION));
+ fileSet.add(IndexFileNames.segmentFileName(docStoreSegment, "", IndexFileNames.VECTORS_DOCUMENTS_EXTENSION));
+ fileSet.add(IndexFileNames.segmentFileName(docStoreSegment, "", IndexFileNames.VECTORS_FIELDS_EXTENSION));
+ }
}
} else if (!useCompoundFile) {
- for (String ext : IndexFileNames.STORE_INDEX_EXTENSIONS)
- addIfExists(fileSet, IndexFileNames.segmentFileName(name, "", ext));
+ fileSet.add(IndexFileNames.segmentFileName(name, "", IndexFileNames.FIELDS_INDEX_EXTENSION));
+ fileSet.add(IndexFileNames.segmentFileName(name, "", IndexFileNames.FIELDS_EXTENSION));
+ if (hasVectors) {
+ fileSet.add(IndexFileNames.segmentFileName(name, "", IndexFileNames.VECTORS_INDEX_EXTENSION));
+ fileSet.add(IndexFileNames.segmentFileName(name, "", IndexFileNames.VECTORS_DOCUMENTS_EXTENSION));
+ fileSet.add(IndexFileNames.segmentFileName(name, "", IndexFileNames.VECTORS_FIELDS_EXTENSION));
- }
++ }
}
String delFileName = IndexFileNames.fileNameFromGeneration(name, IndexFileNames.DELETES_EXTENSION, delGen);
@@@ -526,7 -562,7 +559,7 @@@
}
/** Used for debugging. Format may suddenly change.
-- *
++ *
* <p>Current format looks like
* <code>_a:c45/4->_1</code>, which means the segment's
* name is <code>_a</code>; it's using compound file
@@@ -553,9 -592,15 +589,15 @@@
if (delCount != 0) {
s.append('/').append(delCount);
}
--
++
if (docStoreOffset != -1) {
s.append("->").append(docStoreSegment);
+ if (docStoreIsCompoundFile) {
+ s.append('c');
+ } else {
+ s.append('C');
+ }
+ s.append('+').append(docStoreOffset);
}
return s.toString();
diff --cc lucene/src/java/org/apache/lucene/index/SegmentMerger.java
index 8580d5f68fc,9dc928678a4..6dc93f3722e
--- a/lucene/src/java/org/apache/lucene/index/SegmentMerger.java
+++ b/lucene/src/java/org/apache/lucene/index/SegmentMerger.java
@@@ -40,27 -40,24 +40,24 @@@ import org.apache.lucene.util.MultiBits
/**
* The SegmentMerger class combines two or more Segments, represented by an IndexReader ({@link #add},
-- * into a single Segment. After adding the appropriate readers, call the merge method to combine the
++ * into a single Segment. After adding the appropriate readers, call the merge method to combine the
* segments.
- *<P>
- * If the compoundFile flag is set, then the segments will be merged into a compound file.
- *
-- *
++ *
* @see #merge
* @see #add
*/
final class SegmentMerger {
--
++
/** norms header placeholder */
-- static final byte[] NORMS_HEADER = new byte[]{'N','R','M',-1};
--
++ static final byte[] NORMS_HEADER = new byte[]{'N','R','M',-1};
++
private Directory directory;
private String segment;
private int termIndexInterval = IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL;
private List<IndexReader> readers = new ArrayList<IndexReader>();
- private FieldInfos fieldInfos;
-
+ private final FieldInfos fieldInfos;
-
++
private int mergedDocs;
private final CheckAbort checkAbort;
@@@ -68,14 -65,14 +65,14 @@@
/** Maximum number of contiguous documents to bulk-copy
when merging stored fields */
private final static int MAX_RAW_MERGE_DOCS = 4192;
--
++
private final CodecProvider codecs;
private Codec codec;
private SegmentWriteState segmentWriteState;
private PayloadProcessorProvider payloadProcessorProvider;
--
- SegmentMerger(Directory dir, int termIndexInterval, String name, MergePolicy.OneMerge merge, CodecProvider codecs, PayloadProcessorProvider payloadProcessorProvider) {
++
+ SegmentMerger(Directory dir, int termIndexInterval, String name, MergePolicy.OneMerge merge, CodecProvider codecs, PayloadProcessorProvider payloadProcessorProvider, FieldInfos fieldInfos) {
this.payloadProcessorProvider = payloadProcessorProvider;
directory = dir;
this.codecs = codecs;
@@@ -160,8 -135,8 +135,8 @@@
fileSet.add(IndexFileNames.segmentFileName(segment, "", ext));
}
- codec.files(directory, info, fileSet);
-
+ segmentWriteState.segmentCodecs.files(directory, info, fileSet);
-
++
// Fieldable norm files
int numFIs = fieldInfos.size();
for (int i = 0; i < numFIs; i++) {
@@@ -179,18 -154,26 +154,26 @@@
}
}
+ return fileSet;
+ }
+
+ final Collection<String> createCompoundFile(String fileName, final SegmentInfo info)
+ throws IOException {
+
// Now merge all added files
- for (String file : fileSet) {
+ Collection<String> files = getMergedFiles(info);
+ CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, fileName, checkAbort);
+ for (String file : files) {
cfsWriter.addFile(file);
}
--
++
// Perform the merge
cfsWriter.close();
--
- return new ArrayList<String>(fileSet);
++
+ return files;
}
- private void addIndexed(IndexReader reader, FieldInfos fInfos,
+ private static void addIndexed(IndexReader reader, FieldInfos fInfos,
Collection<String> names, boolean storeTermVectors,
boolean storePositionWithTermVector, boolean storeOffsetWithTermVector,
boolean storePayloads, boolean omitTFAndPositions)
@@@ -239,27 -228,13 +228,12 @@@
}
/**
-- *
++ *
* @return The number of documents in all of the readers
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
- private final int mergeFields() throws CorruptIndexException, IOException {
-
- //nocommit
- // if (!mergeDocStores) {
- // // When we are not merging by doc stores, their field
- // // name -> number mapping are the same. So, we start
- // // with the fieldInfos of the last segment in this
- // // case, to keep that numbering.
- // final SegmentReader sr = (SegmentReader) readers.get(readers.size()-1);
- // fieldInfos = (FieldInfos) sr.core.fieldInfos.clone();
- // } else {
- // fieldInfos = new FieldInfos(); // merge field names
- // }
-
- fieldInfos = new FieldInfos(); // merge field names
-
+ private int mergeFields() throws CorruptIndexException, IOException {
-
for (IndexReader reader : readers) {
if (reader instanceof SegmentReader) {
SegmentReader segmentReader = (SegmentReader) reader;
@@@ -325,10 -296,9 +296,9 @@@
// entering the index. See LUCENE-1282 for
// details.
throw new RuntimeException("mergeFields produced an invalid result: docCount is " + docCount + " but fdx file size is " + fdxFileLength + " file=" + fileName + " file exists?=" + directory.fileExists(fileName) + "; now aborting this merge to prevent index corruption");
- }
-
- segmentWriteState = new SegmentWriteState(null, directory, segment, fieldInfos, docCount, termIndexInterval, codecs);
+
+ segmentWriteState = new SegmentWriteState(null, directory, segment, fieldInfos, docCount, termIndexInterval, codecInfo);
-
+
return docCount;
}
@@@ -345,7 -316,7 +316,7 @@@
++j;
continue;
}
-- // We can optimize this case (doing a bulk byte copy) since the field
++ // We can optimize this case (doing a bulk byte copy) since the field
// numbers are identical
int start = j, numDocs = 0;
do {
@@@ -357,7 -328,7 +328,7 @@@
break;
}
} while(numDocs < MAX_RAW_MERGE_DOCS);
--
++
IndexInput stream = matchingFieldsReader.rawDocs(rawDocLengths, start, numDocs);
fieldsWriter.addRawDocuments(stream, rawDocLengths, numDocs);
docCount += numDocs;
@@@ -411,7 -382,7 +382,7 @@@
* @throws IOException
*/
private final void mergeVectors() throws IOException {
-- TermVectorsWriter termVectorsWriter =
++ TermVectorsWriter termVectorsWriter =
new TermVectorsWriter(directory, segment, fieldInfos);
try {
@@@ -431,7 -402,7 +402,7 @@@
copyVectorsWithDeletions(termVectorsWriter, matchingVectorsReader, reader);
} else {
copyVectorsNoDeletions(termVectorsWriter, matchingVectorsReader, reader);
--
++
}
}
} finally {
@@@ -463,7 -435,7 +435,7 @@@
++docNum;
continue;
}
-- // We can optimize this case (doing a bulk byte copy) since the field
++ // We can optimize this case (doing a bulk byte copy) since the field
// numbers are identical
int start = docNum, numDocs = 0;
do {
@@@ -475,7 -447,7 +447,7 @@@
break;
}
} while(numDocs < MAX_RAW_MERGE_DOCS);
--
++
matchingVectorsReader.rawDocs(rawDocLengths, rawDocLengths2, start, numDocs);
termVectorsWriter.addRawDocuments(matchingVectorsReader, rawDocLengths, rawDocLengths2, numDocs);
checkAbort.work(300 * numDocs);
@@@ -486,7 -458,7 +458,7 @@@
// skip deleted docs
continue;
}
--
++
// NOTE: it's very important to first assign to vectors then pass it to
// termVectorsWriter.addAllDocVectors; see LUCENE-1282
TermFreqVector[] vectors = reader.getTermFreqVectors(docNum);
@@@ -495,7 -467,7 +467,7 @@@
}
}
}
--
++
private void copyVectorsNoDeletions(final TermVectorsWriter termVectorsWriter,
final TermVectorsReader matchingVectorsReader,
final IndexReader reader)
@@@ -530,8 -503,7 +503,7 @@@
// Let CodecProvider decide which codec will be used to write
// the new segment:
- codec = codecs.getWriter(segmentWriteState);
--
++
int docBase = 0;
final List<Fields> fields = new ArrayList<Fields>();
@@@ -561,11 -527,11 +527,11 @@@
// we may gather more readers than mergeState.readerCount
mergeState = new MergeState();
- mergeState.readers = subReaders;
- mergeState.readerCount = subReaders.size();
+ mergeState.readers = readers;
+ mergeState.readerCount = readers.size();
mergeState.fieldInfos = fieldInfos;
mergeState.mergedDocCount = mergedDocs;
--
++
// Remap docIDs
mergeState.delCounts = new int[mergeState.readerCount];
mergeState.docMaps = new int[mergeState.readerCount][];
@@@ -605,7 -568,7 +568,7 @@@
}
assert delCount == mergeState.delCounts[i]: "reader delCount=" + mergeState.delCounts[i] + " vs recomputed delCount=" + delCount;
}
--
++
if (payloadProcessorProvider != null) {
mergeState.dirPayloadProcessor[i] = payloadProcessorProvider.getDirProcessor(reader.directory());
}
@@@ -617,12 -579,9 +579,9 @@@
// NOTE: this is silly, yet, necessary -- we create a
// MultiBits as our skip docs only to have it broken
// apart when we step through the docs enums in
- // MultidDcsEnum.... this only matters when we are
- // interacting with a non-core IR subclass, because
- // LegacyFieldsEnum.LegacyDocs[AndPositions]Enum checks
- // that the skipDocs matches the delDocs for the reader
+ // MultiDocsEnum.
mergeState.multiDeletedDocs = new MultiBits(bits, bitsStarts);
--
++
try {
consumer.merge(mergeState,
new MultiFields(fields.toArray(Fields.EMPTY_ARRAY),
@@@ -641,16 -600,21 +600,21 @@@
int[] getDelCounts() {
return mergeState.delCounts;
}
--
++
private void mergeNorms() throws IOException {
+ // get needed buffer size by finding the largest segment
+ int bufferSize = 0;
+ for (IndexReader reader : readers) {
+ bufferSize = Math.max(bufferSize, reader.maxDoc());
+ }
-
++
byte[] normBuffer = null;
IndexOutput output = null;
try {
- int numFieldInfos = fieldInfos.size();
- for (int i = 0; i < numFieldInfos; i++) {
- FieldInfo fi = fieldInfos.fieldInfo(i);
+ for (int i = 0, numFieldInfos = fieldInfos.size(); i < numFieldInfos; i++) {
+ final FieldInfo fi = fieldInfos.fieldInfo(i);
if (fi.isIndexed && !fi.omitNorms) {
-- if (output == null) {
++ if (output == null) {
output = directory.createOutput(IndexFileNames.segmentFileName(segment, "", IndexFileNames.NORMS_EXTENSION));
output.writeBytes(NORMS_HEADER,NORMS_HEADER.length);
}
@@@ -678,7 -642,7 +642,7 @@@
}
}
} finally {
-- if (output != null) {
++ if (output != null) {
output.close();
}
}
@@@ -709,5 -673,5 +673,5 @@@
}
}
}
--
++
}
diff --cc lucene/src/java/org/apache/lucene/index/SegmentWriteState.java
index 38e06dc35d8,ae9477e76fa..fa4e43ee656
--- a/lucene/src/java/org/apache/lucene/index/SegmentWriteState.java
+++ b/lucene/src/java/org/apache/lucene/index/SegmentWriteState.java
@@@ -52,21 -51,39 +51,39 @@@ public class SegmentWriteState
* smaller values result in bigger indexes, less acceleration and more
* accelerable cases. More detailed experiments would be useful here. */
public final int skipInterval = 16;
--
-- /** Expert: The maximum number of skip levels. Smaller values result in
++
++ /** Expert: The maximum number of skip levels. Smaller values result in
* slightly smaller indexes, but slower skipping in big posting lists.
*/
public final int maxSkipLevels = 10;
-
+
+
+
public SegmentWriteState(PrintStream infoStream, Directory directory, String segmentName, FieldInfos fieldInfos,
- int numDocs, int termIndexInterval, CodecProvider codecs) {
+ int numDocs, int termIndexInterval, SegmentCodecs segmentCodecs) {
this.infoStream = infoStream;
this.directory = directory;
this.segmentName = segmentName;
this.fieldInfos = fieldInfos;
this.numDocs = numDocs;
this.termIndexInterval = termIndexInterval;
- this.codec = codecs.getWriter(this);
+ this.segmentCodecs = segmentCodecs;
flushedFiles = new HashSet<String>();
+ codecId = "";
+ }
-
++
+ /**
+ * Create a shallow {@link SegmentWriteState} copy final a codec ID
+ */
+ SegmentWriteState(SegmentWriteState state, String codecId) {
+ infoStream = state.infoStream;
+ directory = state.directory;
+ segmentName = state.segmentName;
+ fieldInfos = state.fieldInfos;
+ numDocs = state.numDocs;
+ termIndexInterval = state.termIndexInterval;
+ segmentCodecs = state.segmentCodecs;
+ flushedFiles = state.flushedFiles;
+ this.codecId = codecId;
}
}
diff --cc lucene/src/java/org/apache/lucene/index/StoredFieldsWriter.java
index 5b921934554,95da97f3d31..35f1b868f36
--- a/lucene/src/java/org/apache/lucene/index/StoredFieldsWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/StoredFieldsWriter.java
@@@ -27,45 -26,25 +27,41 @@@ import org.apache.lucene.util.RamUsageE
final class StoredFieldsWriter {
FieldsWriter fieldsWriter;
- final DocumentsWriter docWriter;
+ final DocumentsWriterPerThread docWriter;
final FieldInfos fieldInfos;
int lastDocID;
- private String segment;
- PerDoc[] docFreeList = new PerDoc[1];
int freeCount;
-
+
- public StoredFieldsWriter(DocumentsWriter docWriter, FieldInfos fieldInfos) {
+ final DocumentsWriterPerThread.DocState docState;
+
+ public StoredFieldsWriter(DocumentsWriterPerThread docWriter, FieldInfos fieldInfos) {
this.docWriter = docWriter;
this.fieldInfos = fieldInfos;
+ this.docState = docWriter.docState;
+ }
-
++
+ private int numStoredFields;
+ private Fieldable[] storedFields;
+ private int[] fieldNumbers;
+
+ public void reset() {
+ numStoredFields = 0;
+ storedFields = new Fieldable[1];
+ fieldNumbers = new int[1];
}
- public StoredFieldsWriterPerThread addThread(DocumentsWriter.DocState docState) throws IOException {
- return new StoredFieldsWriterPerThread(docState, this);
+ public void startDocument() {
+ reset();
}
-
+
- synchronized public void flush(SegmentWriteState state) throws IOException {
- if (state.numDocs > lastDocID) {
+ public void flush(SegmentWriteState state) throws IOException {
+
+ if (state.numDocs > 0) {
+ // It's possible that all documents seen in this segment
+ // hit non-aborting exceptions, in which case we will
+ // not have yet init'd the FieldsWriter:
initFieldsWriter();
-
- // Fill fdx file to include any final docs that we
- // skipped because they hit non-aborting exceptions
fill(state.numDocs);
}
@@@ -100,14 -73,25 +90,11 @@@
int allocCount;
- synchronized PerDoc getPerDoc() {
- if (freeCount == 0) {
- allocCount++;
- if (allocCount > docFreeList.length) {
- // Grow our free list up front to make sure we have
- // enough space to recycle all outstanding PerDoc
- // instances
- assert allocCount == 1+docFreeList.length;
- docFreeList = new PerDoc[ArrayUtil.oversize(allocCount, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
- }
- return new PerDoc();
- } else {
- return docFreeList[--freeCount];
- }
- }
+ void abort() {
+ reset();
- synchronized void abort() {
if (fieldsWriter != null) {
- try {
- fieldsWriter.close();
- } catch (Throwable t) {
- }
+ fieldsWriter.abort();
fieldsWriter = null;
lastDocID = 0;
}
@@@ -124,41 -107,53 +110,40 @@@
}
}
- synchronized void finishDocument(PerDoc perDoc) throws IOException {
+ void finishDocument() throws IOException {
assert docWriter.writer.testPoint("StoredFieldsWriter.finishDocument start");
+
initFieldsWriter();
+ fill(docState.docID);
-
- if (fieldsWriter != null && numStoredFields > 0) {
+
- fill(perDoc.docID);
++ if (fieldsWriter != null && numStoredFields > 0) {
+ fieldsWriter.startDocument(numStoredFields);
+ for (int i = 0; i < numStoredFields; i++) {
+ fieldsWriter.writeField(fieldNumbers[i], storedFields[i]);
+ }
+ lastDocID++;
+ }
-
+
- // Append stored fields to the real FieldsWriter:
- fieldsWriter.flushDocument(perDoc.numStoredFields, perDoc.fdt);
- lastDocID++;
- perDoc.reset();
- free(perDoc);
+ reset();
assert docWriter.writer.testPoint("StoredFieldsWriter.finishDocument end");
}
-
- synchronized void free(PerDoc perDoc) {
- assert freeCount < docFreeList.length;
- assert 0 == perDoc.numStoredFields;
- assert 0 == perDoc.fdt.length();
- assert 0 == perDoc.fdt.getFilePointer();
- docFreeList[freeCount++] = perDoc;
- }
-
- class PerDoc extends DocumentsWriter.DocWriter {
- final DocumentsWriter.PerDocBuffer buffer = docWriter.newPerDocBuffer();
- RAMOutputStream fdt = new RAMOutputStream(buffer);
- int numStoredFields;
-
- void reset() {
- fdt.reset();
- buffer.recycle();
- numStoredFields = 0;
+ public void addField(Fieldable field, FieldInfo fieldInfo) throws IOException {
+ if (numStoredFields == storedFields.length) {
- int newSize = ArrayUtil.oversize(numStoredFields + 1, RamUsageEstimator.NUM_BYTES_OBJ_REF);
++ int newSize = ArrayUtil.oversize(numStoredFields + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF);
+ Fieldable[] newArray = new Fieldable[newSize];
+ System.arraycopy(storedFields, 0, newArray, 0, numStoredFields);
+ storedFields = newArray;
}
-
+
- @Override
- void abort() {
- reset();
- free(this);
+ if (numStoredFields == fieldNumbers.length) {
+ fieldNumbers = ArrayUtil.grow(fieldNumbers);
}
-
+
- @Override
- public long sizeInBytes() {
- return buffer.getSizeInBytes();
- }
+ storedFields[numStoredFields] = field;
+ fieldNumbers[numStoredFields] = fieldInfo.number;
+ numStoredFields++;
-
+
- @Override
- public void finish() throws IOException {
- finishDocument(this);
- }
+ assert docState.testPoint("StoredFieldsWriterPerThread.processFields.writeField");
}
}
diff --cc lucene/src/java/org/apache/lucene/index/TermVectorsTermsWriter.java
index 03c2b4189dc,7ac08151d4c..f5e978a19c8
--- a/lucene/src/java/org/apache/lucene/index/TermVectorsTermsWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/TermVectorsTermsWriter.java
@@@ -17,72 -17,91 +17,66 @@@ package org.apache.lucene.index
* limitations under the License.
*/
+import java.io.IOException;
+import java.util.Map;
+
import org.apache.lucene.store.IndexOutput;
-import org.apache.lucene.store.RAMOutputStream;
import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.BytesRef;
+ import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.RamUsageEstimator;
-import java.io.IOException;
-import java.util.Collection;
-
-import java.util.Map;
-
final class TermVectorsTermsWriter extends TermsHashConsumer {
- final DocumentsWriter docWriter;
- PerDoc[] docFreeList = new PerDoc[1];
+ final DocumentsWriterPerThread docWriter;
- TermVectorsWriter termVectorsWriter;
int freeCount;
IndexOutput tvx;
IndexOutput tvd;
IndexOutput tvf;
int lastDocID;
-
++
+ final DocumentsWriterPerThread.DocState docState;
+ final BytesRef flushTerm = new BytesRef();
-
++
+ // Used by perField when serializing the term vectors
+ final ByteSliceReader vectorSliceReader = new ByteSliceReader();
+ boolean hasVectors;
- public TermVectorsTermsWriter(DocumentsWriter docWriter) {
+ public TermVectorsTermsWriter(DocumentsWriterPerThread docWriter) {
this.docWriter = docWriter;
+ docState = docWriter.docState;
}
@Override
- public TermsHashConsumerPerThread addThread(TermsHashPerThread termsHashPerThread) {
- return new TermVectorsTermsWriterPerThread(termsHashPerThread, this);
- }
-
- @Override
- synchronized void flush(Map<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>> threadsAndFields, final SegmentWriteState state) throws IOException {
+ void flush(Map<FieldInfo, TermsHashConsumerPerField> fieldsToFlush, final SegmentWriteState state) throws IOException {
-
if (tvx != null) {
+ // At least one doc in this run had term vectors enabled
+ fill(state.numDocs);
- tvx.close();
- tvf.close();
- tvd.close();
- tvx = tvd = tvf = null;
+ assert state.segmentName != null;
+ String idxName = IndexFileNames.segmentFileName(state.segmentName, "", IndexFileNames.VECTORS_INDEX_EXTENSION);
+ String fldName = IndexFileNames.segmentFileName(state.segmentName, "", IndexFileNames.VECTORS_FIELDS_EXTENSION);
+ String docName = IndexFileNames.segmentFileName(state.segmentName, "", IndexFileNames.VECTORS_DOCUMENTS_EXTENSION);
- if (state.numDocs > 0) {
- // In case there are some final documents that we
- // didn't see (because they hit a non-aborting exception):
- fill(state.numDocs);
- }
-
- tvx.flush();
- tvd.flush();
- tvf.flush();
-
- if (4 + ((long) state.numDocs) * 16 != state.directory.fileLength(idxName)) {
+ tvx.close();
+ tvf.close();
+ tvd.close();
+ tvx = null;
- String idxName = IndexFileNames.segmentFileName(state.segmentName, "", IndexFileNames.VECTORS_INDEX_EXTENSION);
+ if (4+((long) state.numDocs)*16 != state.directory.fileLength(idxName))
throw new RuntimeException("after flush: tvx size mismatch: " + state.numDocs + " docs vs " + state.directory.fileLength(idxName) + " length in bytes of " + idxName + " file exists?=" + state.directory.fileExists(idxName));
- }
- String fldName = IndexFileNames.segmentFileName(state.segmentName, "", IndexFileNames.VECTORS_FIELDS_EXTENSION);
- String docName = IndexFileNames.segmentFileName(state.segmentName, "", IndexFileNames.VECTORS_DOCUMENTS_EXTENSION);
state.flushedFiles.add(idxName);
state.flushedFiles.add(fldName);
state.flushedFiles.add(docName);
lastDocID = 0;
-
+ state.hasVectors = hasVectors;
+ hasVectors = false;
}
- for (Map.Entry<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>> entry : threadsAndFields.entrySet()) {
- for (final TermsHashConsumerPerField field : entry.getValue() ) {
- TermVectorsTermsWriterPerField perField = (TermVectorsTermsWriterPerField) field;
- perField.termsHashPerField.reset();
- perField.shrinkHash();
- }
-
- TermVectorsTermsWriterPerThread perThread = (TermVectorsTermsWriterPerThread) entry.getKey();
- perThread.termsHashPerThread.reset(true);
- }
- }
-
- int allocCount;
-
- synchronized PerDoc getPerDoc() {
- if (freeCount == 0) {
- allocCount++;
- if (allocCount > docFreeList.length) {
- // Grow our free list up front to make sure we have
- // enough space to recycle all outstanding PerDoc
- // instances
- assert allocCount == 1+docFreeList.length;
- docFreeList = new PerDoc[ArrayUtil.oversize(allocCount, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
- }
- return new PerDoc();
- } else {
- return docFreeList[--freeCount];
+ for (final TermsHashConsumerPerField field : fieldsToFlush.values() ) {
+ TermVectorsTermsWriterPerField perField = (TermVectorsTermsWriterPerField) field;
+ perField.termsHashPerField.reset();
+ perField.shrinkHash();
}
}
@@@ -101,25 -119,18 +94,18 @@@
}
}
- private final void initTermVectorsWriter() throws IOException {
- synchronized void initTermVectorsWriter() throws IOException {
++ private final void initTermVectorsWriter() throws IOException {
if (tvx == null) {
-
- final String segment = docWriter.getSegment();
-
- if (segment == null)
- return;
// If we hit an exception while init'ing the term
// vector output files, we must abort this segment
// because those files will be in an unknown
// state:
- String idxName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.VECTORS_INDEX_EXTENSION);
- String docName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.VECTORS_DOCUMENTS_EXTENSION);
- String fldName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.VECTORS_FIELDS_EXTENSION);
- tvx = docWriter.directory.createOutput(idxName);
- tvd = docWriter.directory.createOutput(docName);
- tvf = docWriter.directory.createOutput(fldName);
-
+ hasVectors = true;
+ tvx = docWriter.directory.createOutput(IndexFileNames.segmentFileName(docWriter.getSegment(), "", IndexFileNames.VECTORS_INDEX_EXTENSION));
+ tvd = docWriter.directory.createOutput(IndexFileNames.segmentFileName(docWriter.getSegment(), "", IndexFileNames.VECTORS_DOCUMENTS_EXTENSION));
+ tvf = docWriter.directory.createOutput(IndexFileNames.segmentFileName(docWriter.getSegment(), "", IndexFileNames.VECTORS_FIELDS_EXTENSION));
-
++
tvx.writeInt(TermVectorsReader.FORMAT_CURRENT);
tvd.writeInt(TermVectorsReader.FORMAT_CURRENT);
tvf.writeInt(TermVectorsReader.FORMAT_CURRENT);
@@@ -135,28 -145,28 +121,28 @@@
initTermVectorsWriter();
- fill(perDoc.docID);
+ fill(docState.docID);
-
+
// Append term vectors to the real outputs:
- tvx.writeLong(tvd.getFilePointer());
+ long pointer = tvd.getFilePointer();
+ tvx.writeLong(pointer);
tvx.writeLong(tvf.getFilePointer());
- tvd.writeVInt(perDoc.numVectorFields);
- if (perDoc.numVectorFields > 0) {
- for(int i=0;i<perDoc.numVectorFields;i++) {
- tvd.writeVInt(perDoc.fieldNumbers[i]);
+ tvd.writeVInt(numVectorFields);
+ if (numVectorFields > 0) {
+ for(int i=0;i<numVectorFields;i++) {
+ tvd.writeVInt(perFields[i].fieldInfo.number);
}
- assert 0 == perDoc.fieldPointers[0];
- long lastPos = perDoc.fieldPointers[0];
- for(int i=1;i<perDoc.numVectorFields;i++) {
- long pos = perDoc.fieldPointers[i];
+ long lastPos = tvf.getFilePointer();
+ perFields[0].finishDocument();
+ for(int i=1;i<numVectorFields;i++) {
+ long pos = tvf.getFilePointer();
tvd.writeVLong(pos-lastPos);
lastPos = pos;
+ perFields[i].finishDocument();
}
- perDoc.perDocTvf.writeTo(tvf);
- perDoc.numVectorFields = 0;
}
- assert lastDocID == perDoc.docID;
+ assert lastDocID == docState.docID;
lastDocID++;
@@@ -167,82 -177,74 +153,78 @@@
@Override
public void abort() {
-
- if (tvx != null) {
- try {
- tvx.close();
- } catch (Throwable t) {
- }
- tvx = null;
+ hasVectors = false;
+ try {
+ IOUtils.closeSafely(tvx, tvd, tvf);
+ } catch (IOException ignored) {
}
- if (tvd != null) {
- try {
- tvd.close();
- } catch (Throwable t) {
- }
- tvd = null;
+ try {
+ docWriter.directory.deleteFile(IndexFileNames.segmentFileName(docWriter.getSegment(), "", IndexFileNames.VECTORS_INDEX_EXTENSION));
+ } catch (IOException ignored) {
}
- if (tvf != null) {
- try {
- tvf.close();
- } catch (Throwable t) {
- }
- tvf = null;
+ try {
+ docWriter.directory.deleteFile(IndexFileNames.segmentFileName(docWriter.getSegment(), "", IndexFileNames.VECTORS_DOCUMENTS_EXTENSION));
+ } catch (IOException ignored) {
+ }
+ try {
+ docWriter.directory.deleteFile(IndexFileNames.segmentFileName(docWriter.getSegment(), "", IndexFileNames.VECTORS_FIELDS_EXTENSION));
+ } catch (IOException ignored) {
}
+ tvx = tvd = tvf = null;
lastDocID = 0;
-
- }
+
- synchronized void free(PerDoc doc) {
- assert freeCount < docFreeList.length;
- docFreeList[freeCount++] = doc;
+ reset();
}
- class PerDoc extends DocumentsWriter.DocWriter {
+ int numVectorFields;
- final DocumentsWriter.PerDocBuffer buffer = docWriter.newPerDocBuffer();
- RAMOutputStream perDocTvf = new RAMOutputStream(buffer);
+ TermVectorsTermsWriterPerField[] perFields;
- int numVectorFields;
+ void reset() {
+ numVectorFields = 0;
+ perFields = new TermVectorsTermsWriterPerField[1];
+ }
- int[] fieldNumbers = new int[1];
- long[] fieldPointers = new long[1];
+ @Override
+ public TermsHashConsumerPerField addField(TermsHashPerField termsHashPerField, FieldInfo fieldInfo) {
+ return new TermVectorsTermsWriterPerField(termsHashPerField, this, fieldInfo);
+ }
- void reset() {
- perDocTvf.reset();
- buffer.recycle();
- numVectorFields = 0;
+ void addFieldToFlush(TermVectorsTermsWriterPerField fieldToFlush) {
+ if (numVectorFields == perFields.length) {
- int newSize = ArrayUtil.oversize(numVectorFields + 1, RamUsageEstimator.NUM_BYTES_OBJ_REF);
++ int newSize = ArrayUtil.oversize(numVectorFields + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF);
+ TermVectorsTermsWriterPerField[] newArray = new TermVectorsTermsWriterPerField[newSize];
+ System.arraycopy(perFields, 0, newArray, 0, numVectorFields);
+ perFields = newArray;
}
- @Override
- void abort() {
- reset();
- free(this);
- }
+ perFields[numVectorFields++] = fieldToFlush;
+ }
-
+
- void addField(final int fieldNumber) {
- if (numVectorFields == fieldNumbers.length) {
- fieldNumbers = ArrayUtil.grow(fieldNumbers);
- }
- if (numVectorFields == fieldPointers.length) {
- fieldPointers = ArrayUtil.grow(fieldPointers);
- }
- fieldNumbers[numVectorFields] = fieldNumber;
- fieldPointers[numVectorFields] = perDocTvf.getFilePointer();
- numVectorFields++;
- }
+ @Override
+ void startDocument() throws IOException {
+ assert clearLastVectorFieldName();
+ perFields = new TermVectorsTermsWriterPerField[1];
+ reset();
+ }
-
+
- @Override
- public long sizeInBytes() {
- return buffer.getSizeInBytes();
- }
+ // Called only by assert
+ final boolean clearLastVectorFieldName() {
+ lastVectorFieldName = null;
+ return true;
+ }
- @Override
- public void finish() throws IOException {
- finishDocument(this);
+ // Called only by assert
+ String lastVectorFieldName;
+ final boolean vectorFieldsInOrder(FieldInfo fi) {
+ try {
+ if (lastVectorFieldName != null)
+ return lastVectorFieldName.compareTo(fi.name) < 0;
+ else
+ return true;
+ } finally {
+ lastVectorFieldName = fi.name;
}
}
+
}
diff --cc lucene/src/java/org/apache/lucene/index/TermVectorsTermsWriterPerField.java
index c873674a07c,4938538d054..4ed3a819146
--- a/lucene/src/java/org/apache/lucene/index/TermVectorsTermsWriterPerField.java
+++ b/lucene/src/java/org/apache/lucene/index/TermVectorsTermsWriterPerField.java
@@@ -38,10 -41,11 +40,10 @@@ final class TermVectorsTermsWriterPerFi
int maxNumPostings;
OffsetAttribute offsetAttribute = null;
--
- public TermVectorsTermsWriterPerField(TermsHashPerField termsHashPerField, TermVectorsTermsWriterPerThread perThread, FieldInfo fieldInfo) {
++
+ public TermVectorsTermsWriterPerField(TermsHashPerField termsHashPerField, TermVectorsTermsWriter termsWriter, FieldInfo fieldInfo) {
this.termsHashPerField = termsHashPerField;
- this.perThread = perThread;
- this.termsWriter = perThread.termsWriter;
+ this.termsWriter = termsWriter;
this.fieldInfo = fieldInfo;
docState = termsHashPerField.docState;
fieldState = termsHashPerField.fieldState;
@@@ -68,12 -72,22 +70,13 @@@
}
if (doVectors) {
- if (perThread.doc == null) {
- perThread.doc = termsWriter.getPerDoc();
- perThread.doc.docID = docState.docID;
- assert perThread.doc.numVectorFields == 0;
- assert 0 == perThread.doc.perDocTvf.length();
- assert 0 == perThread.doc.perDocTvf.getFilePointer();
- }
-
- assert perThread.doc.docID == docState.docID;
-
- if (termsHashPerField.bytesHash.size() != 0) {
- // Only necessary if previous doc hit a
- // non-aborting exception while writing vectors in
- // this field:
- termsHashPerField.reset();
- perThread.termsHashPerThread.reset(false);
+ if (termsWriter.tvx != null) {
- if (termsHashPerField.numPostings != 0)
++ if (termsHashPerField.bytesHash.size() != 0) {
+ // Only necessary if previous doc hit a
+ // non-aborting exception while writing vectors in
+ // this field:
+ termsHashPerField.reset();
++ }
}
}
@@@ -81,24 -95,22 +84,27 @@@
//perThread.postingsCount = 0;
return doVectors;
-- }
++ }
public void abort() {}
- @Override
+ /** Called once per field per document if term vectors
+ * are enabled, to write the vectors to
+ * RAMOutputStream, which is then quickly flushed to
- * the real term vectors files in the Directory. */
- @Override
++ * the real term vectors files in the Directory. */ @Override
void finish() throws IOException {
- if (!doVectors || termsHashPerField.numPostings == 0)
++ if (!doVectors || termsHashPerField.bytesHash.size() == 0)
+ return;
+ termsWriter.addFieldToFlush(this);
+ }
-
++
+ void finishDocument() throws IOException {
assert docState.testPoint("TermVectorsTermsWriterPerField.finish start");
- final int numPostings = termsHashPerField.numPostings;
+ final int numPostings = termsHashPerField.bytesHash.size();
- final BytesRef flushTerm = perThread.flushTerm;
+ final BytesRef flushTerm = termsWriter.flushTerm;
assert numPostings >= 0;
@@@ -123,21 -140,21 +129,21 @@@
byte bits = 0x0;
if (doVectorPositions)
bits |= TermVectorsReader.STORE_POSITIONS_WITH_TERMVECTOR;
-- if (doVectorOffsets)
++ if (doVectorOffsets)
bits |= TermVectorsReader.STORE_OFFSET_WITH_TERMVECTOR;
tvf.writeByte(bits);
int lastLen = 0;
byte[] lastBytes = null;
int lastStart = 0;
--
- final ByteSliceReader reader = perThread.vectorSliceReader;
- final ByteBlockPool termBytePool = perThread.termsHashPerThread.termBytePool;
++
+ final ByteSliceReader reader = termsWriter.vectorSliceReader;
+ final ByteBlockPool termBytePool = termsHashPerField.termBytePool;
for(int j=0;j<numPostings;j++) {
final int termID = termIDs[j];
final int freq = postings.freqs[termID];
--
++
// Get BytesRef
termBytePool.setBytesRef(flushTerm, postings.textStarts[termID]);
@@@ -181,7 -205,7 +187,7 @@@
termsHashPerField.shrinkHash(maxNumPostings);
maxNumPostings = 0;
}
--
++
@Override
void start(Fieldable f) {
if (doVectorOffsets) {
@@@ -201,7 -225,7 +207,7 @@@
if (doVectorOffsets) {
int startOffset = fieldState.offset + offsetAttribute.startOffset();
int endOffset = fieldState.offset + offsetAttribute.endOffset();
--
++
termsHashPerField.writeVInt(1, startOffset);
termsHashPerField.writeVInt(1, endOffset - startOffset);
postings.lastOffsets[termID] = endOffset;
@@@ -219,13 -243,13 +225,13 @@@
assert docState.testPoint("TermVectorsTermsWriterPerField.addTerm start");
TermVectorsPostingsArray postings = (TermVectorsPostingsArray) termsHashPerField.postingsArray;
--
++
postings.freqs[termID]++;
if (doVectorOffsets) {
int startOffset = fieldState.offset + offsetAttribute.startOffset();
int endOffset = fieldState.offset + offsetAttribute.endOffset();
--
++
termsHashPerField.writeVInt(1, startOffset - postings.lastOffsets[termID]);
termsHashPerField.writeVInt(1, endOffset - startOffset);
postings.lastOffsets[termID] = endOffset;
@@@ -256,7 -280,7 +262,7 @@@
int[] freqs; // How many times this term occurred in the current doc
int[] lastOffsets; // Last offset we saw
int[] lastPositions; // Last position where this term occurred
--
++
ParallelPostingsArray newInstance(int size) {
return new TermVectorsPostingsArray(size);
}
diff --cc lucene/src/java/org/apache/lucene/index/TermsHash.java
index 98849cd46f7,2ad2a827b5f..bd72b395ff5
--- a/lucene/src/java/org/apache/lucene/index/TermsHash.java
+++ b/lucene/src/java/org/apache/lucene/index/TermsHash.java
@@@ -18,11 -18,12 +18,12 @@@ package org.apache.lucene.index
*/
import java.io.IOException;
-import java.util.Collection;
import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
import java.util.Map;
++import org.apache.lucene.util.ByteBlockPool;
+import org.apache.lucene.util.BytesRef;
+
/** This class implements {@link InvertedDocConsumer}, which
* is passed each token produced by the analyzer on each
* field. It stores these tokens in a hash table, and
@@@ -35,42 -36,24 +36,41 @@@ final class TermsHash extends InvertedD
final TermsHashConsumer consumer;
final TermsHash nextTermsHash;
- final DocumentsWriter docWriter;
+ final DocumentsWriterPerThread docWriter;
-
++
+ final IntBlockPool intPool;
+ final ByteBlockPool bytePool;
+ ByteBlockPool termBytePool;
+
+ final boolean primary;
+ final DocumentsWriterPerThread.DocState docState;
+
+ // Used when comparing postings via termRefComp, in TermsHashPerField
+ final BytesRef tr1 = new BytesRef();
+ final BytesRef tr2 = new BytesRef();
+
- // Used by perField:
- final BytesRef utf8 = new BytesRef(10);
-
++ // Used by perField to obtain terms from the analysis chain
++ final BytesRef termBytesRef = new BytesRef(10);
+
boolean trackAllocations;
-
- public TermsHash(final DocumentsWriter docWriter, boolean trackAllocations, final TermsHashConsumer consumer, final TermsHash nextTermsHash) {
++
+ public TermsHash(final DocumentsWriterPerThread docWriter, final TermsHashConsumer consumer, final TermsHash nextTermsHash) {
+ this.docState = docWriter.docState;
this.docWriter = docWriter;
this.consumer = consumer;
- this.nextTermsHash = nextTermsHash;
+ this.nextTermsHash = nextTermsHash;
- this.trackAllocations = trackAllocations;
- }
-
- @Override
- InvertedDocConsumerPerThread addThread(DocInverterPerThread docInverterPerThread) {
- return new TermsHashPerThread(docInverterPerThread, this, nextTermsHash, null);
- }
-
- TermsHashPerThread addThread(DocInverterPerThread docInverterPerThread, TermsHashPerThread primaryPerThread) {
- return new TermsHashPerThread(docInverterPerThread, this, nextTermsHash, primaryPerThread);
+ intPool = new IntBlockPool(docWriter);
- bytePool = new ByteBlockPool(docWriter.ramAllocator.byteBlockAllocator);
-
++ bytePool = new ByteBlockPool(docWriter.byteBlockAllocator);
++
+ if (nextTermsHash != null) {
+ // We are primary
+ primary = true;
+ termBytePool = bytePool;
+ nextTermsHash.termBytePool = bytePool;
+ } else {
+ primary = false;
+ }
-
}
@Override
@@@ -81,71 -64,52 +81,71 @@@
@Override
public void abort() {
- consumer.abort();
- if (nextTermsHash != null)
- nextTermsHash.abort();
+ reset();
+ try {
+ consumer.abort();
+ } finally {
+ if (nextTermsHash != null) {
+ nextTermsHash.abort();
+ }
+ }
}
-
+
- @Override
- synchronized void flush(Map<InvertedDocConsumerPerThread,Collection<InvertedDocConsumerPerField>> threadsAndFields, final SegmentWriteState state) throws IOException {
- Map<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>> childThreadsAndFields = new HashMap<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>>();
- Map<InvertedDocConsumerPerThread,Collection<InvertedDocConsumerPerField>> nextThreadsAndFields;
+ // Clear all state
+ void reset() {
+ intPool.reset();
+ bytePool.reset();
- if (nextTermsHash != null)
- nextThreadsAndFields = new HashMap<InvertedDocConsumerPerThread,Collection<InvertedDocConsumerPerField>>();
- else
- nextThreadsAndFields = null;
+ if (primary) {
+ bytePool.reset();
+ }
+ }
- for (final Map.Entry<InvertedDocConsumerPerThread,Collection<InvertedDocConsumerPerField>> entry : threadsAndFields.entrySet()) {
+ @Override
+ void flush(Map<FieldInfo,InvertedDocConsumerPerField> fieldsToFlush, final SegmentWriteState state) throws IOException {
+ Map<FieldInfo,TermsHashConsumerPerField> childFields = new HashMap<FieldInfo,TermsHashConsumerPerField>();
+ Map<FieldInfo,InvertedDocConsumerPerField> nextChildFields;
+
+ if (nextTermsHash != null) {
+ nextChildFields = new HashMap<FieldInfo,InvertedDocConsumerPerField>();
+ } else {
+ nextChildFields = null;
+ }
- TermsHashPerThread perThread = (TermsHashPerThread) entry.getKey();
+ for (final Map.Entry<FieldInfo,InvertedDocConsumerPerField> entry : fieldsToFlush.entrySet()) {
+ TermsHashPerField perField = (TermsHashPerField) entry.getValue();
+ childFields.put(entry.getKey(), perField.consumer);
+ if (nextTermsHash != null) {
+ nextChildFields.put(entry.getKey(), perField.nextPerField);
+ }
+ }
-
+
- Collection<InvertedDocConsumerPerField> fields = entry.getValue();
+ consumer.flush(childFields, state);
- Iterator<InvertedDocConsumerPerField> fieldsIt = fields.iterator();
- Collection<TermsHashConsumerPerField> childFields = new HashSet<TermsHashConsumerPerField>();
- Collection<InvertedDocConsumerPerField> nextChildFields;
+ if (nextTermsHash != null) {
+ nextTermsHash.flush(nextChildFields, state);
+ }
+ }
-
+
- if (nextTermsHash != null)
- nextChildFields = new HashSet<InvertedDocConsumerPerField>();
- else
- nextChildFields = null;
+ @Override
+ InvertedDocConsumerPerField addField(DocInverterPerField docInverterPerField, final FieldInfo fieldInfo) {
+ return new TermsHashPerField(docInverterPerField, this, nextTermsHash, fieldInfo);
+ }
- while(fieldsIt.hasNext()) {
- TermsHashPerField perField = (TermsHashPerField) fieldsIt.next();
- childFields.add(perField.consumer);
- if (nextTermsHash != null)
- nextChildFields.add(perField.nextPerField);
- }
+ @Override
+ public boolean freeRAM() {
+ return false;
+ }
- childThreadsAndFields.put(perThread.consumer, childFields);
- if (nextTermsHash != null)
- nextThreadsAndFields.put(perThread.nextPerThread, nextChildFields);
+ @Override
+ void finishDocument() throws IOException {
+ try {
+ consumer.finishDocument(this);
+ } finally {
+ if (nextTermsHash != null) {
+ nextTermsHash.consumer.finishDocument(nextTermsHash);
+ }
}
-
- consumer.flush(childThreadsAndFields, state);
-
- if (nextTermsHash != null)
- nextTermsHash.flush(nextThreadsAndFields, state);
}
@Override
diff --cc lucene/src/java/org/apache/lucene/index/TermsHashConsumer.java
index 99b2de8e70f,5f23675ff1d..38fbbc6b5b7
--- a/lucene/src/java/org/apache/lucene/index/TermsHashConsumer.java
+++ b/lucene/src/java/org/apache/lucene/index/TermsHashConsumer.java
@@@ -21,11 -21,11 +21,12 @@@ import java.io.IOException
import java.util.Map;
abstract class TermsHashConsumer {
- abstract TermsHashConsumerPerThread addThread(TermsHashPerThread perThread);
- abstract void flush(Map<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>> threadsAndFields, final SegmentWriteState state) throws IOException;
+ abstract void flush(Map<FieldInfo, TermsHashConsumerPerField> fieldsToFlush, final SegmentWriteState state) throws IOException;
abstract void abort();
+ abstract void startDocument() throws IOException;
+ abstract void finishDocument(TermsHash termsHash) throws IOException;
+ abstract public TermsHashConsumerPerField addField(TermsHashPerField termsHashPerField, FieldInfo fieldInfo);
+
FieldInfos fieldInfos;
void setFieldInfos(FieldInfos fieldInfos) {
diff --cc lucene/src/java/org/apache/lucene/index/TermsHashPerField.java
index c42bf431ba9,2d6d8e7a3d2..9d486df8d13
--- a/lucene/src/java/org/apache/lucene/index/TermsHashPerField.java
+++ b/lucene/src/java/org/apache/lucene/index/TermsHashPerField.java
@@@ -30,10 -34,9 +34,10 @@@ final class TermsHashPerField extends I
final TermsHashConsumerPerField consumer;
+ final TermsHash termsHash;
-
++
final TermsHashPerField nextPerField;
- final TermsHashPerThread perThread;
- final DocumentsWriter.DocState docState;
+ final DocumentsWriterPerThread.DocState docState;
final FieldInvertState fieldState;
TermToBytesRefAttribute termAtt;
@@@ -47,73 -50,38 +51,39 @@@
final FieldInfo fieldInfo;
- boolean postingsCompacted;
- int numPostings;
- private int postingsHashSize = 4;
- private int postingsHashHalfSize = postingsHashSize/2;
- private int postingsHashMask = postingsHashSize-1;
- private int[] postingsHash;
-
+ final BytesRefHash bytesHash;
-
++
ParallelPostingsArray postingsArray;
- private final BytesRef utf8;
- private Comparator<BytesRef> termComp;
+ private final BytesRef termBytesRef;
+ private final AtomicLong bytesUsed;
- public TermsHashPerField(DocInverterPerField docInverterPerField, final TermsHashPerThread perThread, final TermsHashPerThread nextPerThread, final FieldInfo fieldInfo) {
- this.perThread = perThread;
- intPool = perThread.intPool;
- bytePool = perThread.bytePool;
- termBytePool = perThread.termBytePool;
- docState = perThread.docState;
- bytesUsed = perThread.termsHash.trackAllocations?perThread.termsHash.docWriter.bytesUsed:new AtomicLong();
+ public TermsHashPerField(DocInverterPerField docInverterPerField, final TermsHash termsHash, final TermsHash nextTermsHash, final FieldInfo fieldInfo) {
+ intPool = termsHash.intPool;
+ bytePool = termsHash.bytePool;
+ termBytePool = termsHash.termBytePool;
+ docState = termsHash.docState;
+ this.termsHash = termsHash;
-
- postingsHash = new int[postingsHashSize];
- Arrays.fill(postingsHash, -1);
- bytesUsed(postingsHashSize * RamUsageEstimator.NUM_BYTES_INT);
++ bytesUsed = termsHash.trackAllocations?termsHash.docWriter.bytesUsed:new AtomicLong();
fieldState = docInverterPerField.fieldState;
- this.consumer = perThread.consumer.addField(this, fieldInfo);
+ this.consumer = termsHash.consumer.addField(this, fieldInfo);
- initPostingsArray();
-
+ PostingsBytesStartArray byteStarts = new PostingsBytesStartArray(this, bytesUsed);
- bytesHash = new BytesRefHash(termBytePool, HASH_INIT_SIZE, byteStarts);
++ bytesHash = new BytesRefHash(termBytePool, HASH_INIT_SIZE, byteStarts);
streamCount = consumer.getStreamCount();
numPostingInt = 2*streamCount;
- utf8 = termsHash.utf8;
- termBytesRef = perThread.termBytesRef;
++
++ termBytesRef = termsHash.termBytesRef;
this.fieldInfo = fieldInfo;
- if (nextPerThread != null)
- nextPerField = (TermsHashPerField) nextPerThread.addField(docInverterPerField, fieldInfo);
+ if (nextTermsHash != null)
+ nextPerField = (TermsHashPerField) nextTermsHash.addField(docInverterPerField, fieldInfo);
else
nextPerField = null;
}
- private void initPostingsArray() {
- postingsArray = consumer.createPostingsArray(2);
- bytesUsed(postingsArray.size * postingsArray.bytesPerPosting());
- }
-
- // sugar: just forwards to DW
- private void bytesUsed(long size) {
- if (termsHash.trackAllocations) {
- termsHash.docWriter.bytesUsed(size);
- }
- }
-
void shrinkHash(int targetSize) {
- assert postingsCompacted || numPostings == 0;
-
- final int newSize = 4;
- if (newSize != postingsHash.length) {
- final long previousSize = postingsHash.length;
- postingsHash = new int[newSize];
- bytesUsed((newSize-previousSize)*RamUsageEstimator.NUM_BYTES_INT);
- Arrays.fill(postingsHash, -1);
- postingsHashSize = newSize;
- postingsHashHalfSize = newSize/2;
- postingsHashMask = newSize-1;
- }
-
- // Fully free the postings array on each flush:
- if (postingsArray != null) {
- bytesUsed(-postingsArray.bytesPerPosting() * postingsArray.size);
- postingsArray = null;
- }
+ // Fully free the bytesHash on each flush but keep the pool untouched
+ // bytesHash.clear will clear the ByteStartArray and in turn the ParallelPostingsArray too
- bytesHash.clear(false);
++ bytesHash.clear(false);
}
public void reset() {
@@@ -145,146 -100,19 +102,18 @@@
public void initReader(ByteSliceReader reader, int termID, int stream) {
assert stream < streamCount;
int intStart = postingsArray.intStarts[termID];
- final int[] ints = intPool.buffers[intStart >> DocumentsWriterRAMAllocator.INT_BLOCK_SHIFT];
- final int upto = intStart & DocumentsWriterRAMAllocator.INT_BLOCK_MASK;
- final int[] ints = intPool.buffers[intStart >> DocumentsWriter.INT_BLOCK_SHIFT];
- final int upto = intStart & DocumentsWriter.INT_BLOCK_MASK;
++ final int[] ints = intPool.buffers[intStart >> DocumentsWriterPerThread.INT_BLOCK_SHIFT];
++ final int upto = intStart & DocumentsWriterPerThread.INT_BLOCK_MASK;
reader.init(bytePool,
postingsArray.byteStarts[termID]+stream*ByteBlockPool.FIRST_LEVEL_SIZE,
ints[upto+stream]);
}
- private void compactPostings() {
- int upto = 0;
- for(int i=0;i<postingsHashSize;i++) {
- if (postingsHash[i] != -1) {
- if (upto < i) {
- postingsHash[upto] = postingsHash[i];
- postingsHash[i] = -1;
- }
- upto++;
- }
- }
-
- assert upto == numPostings;
- postingsCompacted = true;
- }
--
/** Collapse the hash table & sort in-place. */
public int[] sortPostings(Comparator<BytesRef> termComp) {
- this.termComp = termComp;
- compactPostings();
- quickSort(postingsHash, 0, numPostings-1);
- return postingsHash;
- }
-
- void quickSort(int[] termIDs, int lo, int hi) {
- if (lo >= hi)
- return;
- else if (hi == 1+lo) {
- if (comparePostings(termIDs[lo], termIDs[hi]) > 0) {
- final int tmp = termIDs[lo];
- termIDs[lo] = termIDs[hi];
- termIDs[hi] = tmp;
- }
- return;
- }
-
- int mid = (lo + hi) >>> 1;
-
- if (comparePostings(termIDs[lo], termIDs[mid]) > 0) {
- int tmp = termIDs[lo];
- termIDs[lo] = termIDs[mid];
- termIDs[mid] = tmp;
- }
-
- if (comparePostings(termIDs[mid], termIDs[hi]) > 0) {
- int tmp = termIDs[mid];
- termIDs[mid] = termIDs[hi];
- termIDs[hi] = tmp;
-
- if (comparePostings(termIDs[lo], termIDs[mid]) > 0) {
- int tmp2 = termIDs[lo];
- termIDs[lo] = termIDs[mid];
- termIDs[mid] = tmp2;
- }
- }
-
- int left = lo + 1;
- int right = hi - 1;
-
- if (left >= right)
- return;
-
- int partition = termIDs[mid];
-
- for (; ;) {
- while (comparePostings(termIDs[right], partition) > 0)
- --right;
-
- while (left < right && comparePostings(termIDs[left], partition) <= 0)
- ++left;
-
- if (left < right) {
- int tmp = termIDs[left];
- termIDs[left] = termIDs[right];
- termIDs[right] = tmp;
- --right;
- } else {
- break;
- }
- }
-
- quickSort(termIDs, lo, left);
- quickSort(termIDs, left + 1, hi);
+ return bytesHash.sort(termComp);
}
- /** Compares term text for two Posting instance and
- * returns -1 if p1 < p2; 1 if p1 > p2; else 0. */
- int comparePostings(int term1, int term2) {
-
- if (term1 == term2) {
- // Our quicksort does this, eg during partition
- return 0;
- }
-
- termBytePool.setBytesRef(termsHash.tr1, postingsArray.textStarts[term1]);
- termBytePool.setBytesRef(termsHash.tr2, postingsArray.textStarts[term2]);
-
- return termComp.compare(termsHash.tr1, termsHash.tr2);
- }
-
- /** Test whether the text for current RawPostingList p equals
- * current tokenText in utf8. */
- private boolean postingEquals(final int termID) {
- final int textStart = postingsArray.textStarts[termID];
- final byte[] text = termBytePool.buffers[textStart >> DocumentsWriterRAMAllocator.BYTE_BLOCK_SHIFT];
- assert text != null;
-
- int pos = textStart & DocumentsWriterRAMAllocator.BYTE_BLOCK_MASK;
-
- final int len;
- if ((text[pos] & 0x80) == 0) {
- // length is 1 byte
- len = text[pos];
- pos += 1;
- } else {
- // length is 2 bytes
- len = (text[pos]&0x7f) + ((text[pos+1]&0xff)<<7);
- pos += 2;
- }
-
- if (len == utf8.length) {
- final byte[] utf8Bytes = utf8.bytes;
- for(int tokenPos=0;tokenPos<utf8.length;pos++,tokenPos++) {
- if (utf8Bytes[tokenPos] != text[pos]) {
- return false;
- }
- }
- return true;
- } else {
- return false;
- }
- }
-
private boolean doCall;
private boolean doNextCall;
@@@ -296,7 -124,7 +125,7 @@@
nextPerField.start(f);
}
}
--
++
@Override
boolean start(Fieldable[] fields, int count) throws IOException {
doCall = consumer.start(fields, count);
@@@ -313,53 -138,16 +139,15 @@@
// because token text has already been "interned" into
// textStart, so we hash by textStart
public void add(int textStart) throws IOException {
- int code = textStart;
-
- int hashPos = code & postingsHashMask;
-
- assert !postingsCompacted;
-
- // Locate RawPostingList in hash
- int termID = postingsHash[hashPos];
-
- if (termID != -1 && postingsArray.textStarts[termID] != textStart) {
- // Conflict: keep searching different locations in
- // the hash table.
- final int inc = ((code>>8)+code)|1;
- do {
- code += inc;
- hashPos = code & postingsHashMask;
- termID = postingsHash[hashPos];
- } while (termID != -1 && postingsArray.textStarts[termID] != textStart);
- }
-
- if (termID == -1) {
-
+ int termID = bytesHash.addByPoolOffset(textStart);
+ if (termID >= 0) { // New posting
// First time we are seeing this token since we last
// flushed the hash.
-
- // New posting
- termID = numPostings++;
- if (termID >= postingsArray.size) {
- growParallelPostingsArray();
- }
-
- assert termID >= 0;
-
- postingsArray.textStarts[termID] = textStart;
-
- assert postingsHash[hashPos] == -1;
- postingsHash[hashPos] = termID;
-
- if (numPostings == postingsHashHalfSize)
- rehashPostings(2*postingsHashSize);
-
// Init stream slices
- if (numPostingInt + intPool.intUpto > DocumentsWriterRAMAllocator.INT_BLOCK_SIZE)
- if (numPostingInt + intPool.intUpto > DocumentsWriter.INT_BLOCK_SIZE)
++ if (numPostingInt + intPool.intUpto > DocumentsWriterPerThread.INT_BLOCK_SIZE)
intPool.nextBuffer();
- if (DocumentsWriterRAMAllocator.BYTE_BLOCK_SIZE - bytePool.byteUpto < numPostingInt*ByteBlockPool.FIRST_LEVEL_SIZE)
- if (ByteBlockPool.BYTE_BLOCK_SIZE - bytePool.byteUpto < numPostingInt*ByteBlockPool.FIRST_LEVEL_SIZE)
-- bytePool.nextBuffer();
++ if (ByteBlockPool.BYTE_BLOCK_SIZE - bytePool.byteUpto < numPostingInt*ByteBlockPool.FIRST_LEVEL_SIZE) bytePool.nextBuffer();
intUptos = intPool.buffer;
intUptoStart = intPool.intUpto;
@@@ -376,9 -164,10 +164,10 @@@
consumer.newTerm(termID);
} else {
+ termID = (-termID)-1;
int intStart = postingsArray.intStarts[termID];
- intUptos = intPool.buffers[intStart >> DocumentsWriterRAMAllocator.INT_BLOCK_SHIFT];
- intUptoStart = intStart & DocumentsWriterRAMAllocator.INT_BLOCK_MASK;
- intUptos = intPool.buffers[intStart >> DocumentsWriter.INT_BLOCK_SHIFT];
- intUptoStart = intStart & DocumentsWriter.INT_BLOCK_MASK;
++ intUptos = intPool.buffers[intStart >> DocumentsWriterPerThread.INT_BLOCK_SHIFT];
++ intUptoStart = intStart & DocumentsWriterPerThread.INT_BLOCK_MASK;
consumer.addTerm(termID);
}
}
@@@ -387,101 -176,35 +176,35 @@@
@Override
void add() throws IOException {
- assert !postingsCompacted;
-
// We are first in the chain so we must "intern" the
// term text into textStart address
-
// Get the text & hash of this term.
- int code = termAtt.toBytesRef(utf8);
-
- int hashPos = code & postingsHashMask;
-
- // Locate RawPostingList in hash
- int termID = postingsHash[hashPos];
-
- if (termID != -1 && !postingEquals(termID)) {
- // Conflict: keep searching different locations in
- // the hash table.
- final int inc = ((code>>8)+code)|1;
- do {
- code += inc;
- hashPos = code & postingsHashMask;
- termID = postingsHash[hashPos];
- } while (termID != -1 && !postingEquals(termID));
- }
-
- if (termID == -1) {
-
- // First time we are seeing this token since we last
- // flushed the hash.
- final int textLen2 = 2+utf8.length;
- if (textLen2 + bytePool.byteUpto > DocumentsWriterRAMAllocator.BYTE_BLOCK_SIZE) {
- // Not enough room in current block
-
- if (utf8.length > DocumentsWriterRAMAllocator.MAX_TERM_LENGTH_UTF8) {
- // Just skip this term, to remain as robust as
- // possible during indexing. A TokenFilter
- // can be inserted into the analyzer chain if
- // other behavior is wanted (pruning the term
- // to a prefix, throwing an exception, etc).
- if (docState.maxTermPrefix == null) {
- final int saved = utf8.length;
- try {
- utf8.length = Math.min(30, DocumentsWriterRAMAllocator.MAX_TERM_LENGTH_UTF8);
- docState.maxTermPrefix = utf8.toString();
- } finally {
- utf8.length = saved;
- }
- }
-
- consumer.skippingLongTerm();
- return;
+ int termID;
+ try{
+ termID = bytesHash.add(termBytesRef, termAtt.toBytesRef(termBytesRef));
+ }catch (MaxBytesLengthExceededException e) {
+ // Not enough room in current block
+ // Just skip this term, to remain as robust as
+ // possible during indexing. A TokenFilter
+ // can be inserted into the analyzer chain if
+ // other behavior is wanted (pruning the term
+ // to a prefix, throwing an exception, etc).
+ if (docState.maxTermPrefix == null) {
+ final int saved = termBytesRef.length;
+ try {
- termBytesRef.length = Math.min(30, DocumentsWriter.MAX_TERM_LENGTH_UTF8);
++ termBytesRef.length = Math.min(30, DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8);
+ docState.maxTermPrefix = termBytesRef.toString();
+ } finally {
+ termBytesRef.length = saved;
}
- bytePool.nextBuffer();
}
-
- // New posting
- termID = numPostings++;
- if (termID >= postingsArray.size) {
- growParallelPostingsArray();
- }
-
- assert termID != -1;
- assert postingsHash[hashPos] == -1;
-
- postingsHash[hashPos] = termID;
-
- final byte[] text = bytePool.buffer;
- final int textUpto = bytePool.byteUpto;
- postingsArray.textStarts[termID] = textUpto + bytePool.byteOffset;
-
- // We first encode the length, followed by the UTF8
- // bytes. Length is encoded as vInt, but will consume
- // 1 or 2 bytes at most (we reject too-long terms,
- // above).
-
- // encode length @ start of bytes
- if (utf8.length < 128) {
- // 1 byte to store length
- text[textUpto] = (byte) utf8.length;
- bytePool.byteUpto += utf8.length + 1;
- System.arraycopy(utf8.bytes, 0, text, textUpto+1, utf8.length);
- } else {
- // 2 byte to store length
- text[textUpto] = (byte) (0x80 | (utf8.length & 0x7f));
- text[textUpto+1] = (byte) ((utf8.length>>7) & 0xff);
- bytePool.byteUpto += utf8.length + 2;
- System.arraycopy(utf8.bytes, 0, text, textUpto+2, utf8.length);
- }
-
- if (numPostings == postingsHashHalfSize) {
- rehashPostings(2*postingsHashSize);
- bytesUsed(2*numPostings * RamUsageEstimator.NUM_BYTES_INT);
- }
-
+ consumer.skippingLongTerm();
+ return;
+ }
+ if (termID >= 0) {// New posting
+ bytesHash.byteStart(termID);
// Init stream slices
- if (numPostingInt + intPool.intUpto > DocumentsWriterRAMAllocator.INT_BLOCK_SIZE) {
- if (numPostingInt + intPool.intUpto > DocumentsWriter.INT_BLOCK_SIZE) {
++ if (numPostingInt + intPool.intUpto > DocumentsWriterPerThread.INT_BLOCK_SIZE) {
intPool.nextBuffer();
}
@@@ -504,9 -227,10 +227,10 @@@
consumer.newTerm(termID);
} else {
+ termID = (-termID)-1;
final int intStart = postingsArray.intStarts[termID];
- intUptos = intPool.buffers[intStart >> DocumentsWriterRAMAllocator.INT_BLOCK_SHIFT];
- intUptoStart = intStart & DocumentsWriterRAMAllocator.INT_BLOCK_MASK;
- intUptos = intPool.buffers[intStart >> DocumentsWriter.INT_BLOCK_SHIFT];
- intUptoStart = intStart & DocumentsWriter.INT_BLOCK_MASK;
++ intUptos = intPool.buffers[intStart >> DocumentsWriterPerThread.INT_BLOCK_SHIFT];
++ intUptoStart = intStart & DocumentsWriterPerThread.INT_BLOCK_MASK;
consumer.addTerm(termID);
}
@@@ -554,61 -278,51 +278,51 @@@
if (nextPerField != null)
nextPerField.finish();
}
-
+
- /** Called when postings hash is too small (> 50%
- * occupied) or too large (< 20% occupied). */
- void rehashPostings(final int newSize) {
-
- final int newMask = newSize-1;
-
- int[] newHash = new int[newSize];
- Arrays.fill(newHash, -1);
- for(int i=0;i<postingsHashSize;i++) {
- int termID = postingsHash[i];
- if (termID != -1) {
- int code;
- if (termsHash.primary) {
- final int textStart = postingsArray.textStarts[termID];
- final int start = textStart & DocumentsWriterRAMAllocator.BYTE_BLOCK_MASK;
- final byte[] text = bytePool.buffers[textStart >> DocumentsWriterRAMAllocator.BYTE_BLOCK_SHIFT];
- code = 0;
-
- final int len;
- int pos;
- if ((text[start] & 0x80) == 0) {
- // length is 1 byte
- len = text[start];
- pos = start+1;
- } else {
- len = (text[start]&0x7f) + ((text[start+1]&0xff)<<7);
- pos = start+2;
- }
-
- final int endPos = pos+len;
- while(pos < endPos) {
- code = (code*31) + text[pos++];
- }
- } else {
- code = postingsArray.textStarts[termID];
- }
+ private static final class PostingsBytesStartArray extends BytesStartArray {
- int hashPos = code & newMask;
- assert hashPos >= 0;
- if (newHash[hashPos] != -1) {
- final int inc = ((code>>8)+code)|1;
- do {
- code += inc;
- hashPos = code & newMask;
- } while (newHash[hashPos] != -1);
- }
- newHash[hashPos] = termID;
+ private final TermsHashPerField perField;
+ private final AtomicLong bytesUsed;
+
+ private PostingsBytesStartArray(
+ TermsHashPerField perField, AtomicLong bytesUsed) {
+ this.perField = perField;
+ this.bytesUsed = bytesUsed;
+ }
-
++
+ @Override
+ public int[] init() {
- if(perField.postingsArray == null) {
++ if(perField.postingsArray == null) {
+ perField.postingsArray = perField.consumer.createPostingsArray(2);
+ bytesUsed.addAndGet(perField.postingsArray.size * perField.postingsArray.bytesPerPosting());
+ }
+ return perField.postingsArray.textStarts;
+ }
+
+ @Override
+ public int[] grow() {
+ ParallelPostingsArray postingsArray = perField.postingsArray;
+ final int oldSize = perField.postingsArray.size;
+ postingsArray = perField.postingsArray = postingsArray.grow();
+ bytesUsed
+ .addAndGet((postingsArray.bytesPerPosting() * (postingsArray.size - oldSize)));
+ return postingsArray.textStarts;
+ }
+
+ @Override
+ public int[] clear() {
+ if(perField.postingsArray != null) {
+ bytesUsed.addAndGet(-perField.postingsArray.size * perField.postingsArray.bytesPerPosting());
+ perField.postingsArray = null;
}
+ return null;
}
- postingsHashMask = newMask;
- postingsHash = newHash;
+ @Override
+ public AtomicLong bytesUsed() {
+ return bytesUsed;
+ }
- postingsHashSize = newSize;
- postingsHashHalfSize = newSize >> 1;
}
+
}
diff --cc lucene/src/java/org/apache/lucene/index/ThreadAffinityDocumentsWriterThreadPool.java
index ee9483cc297,00000000000..9f70da174f7
mode 100644,000000..100644
--- a/lucene/src/java/org/apache/lucene/index/ThreadAffinityDocumentsWriterThreadPool.java
+++ b/lucene/src/java/org/apache/lucene/index/ThreadAffinityDocumentsWriterThreadPool.java
@@@ -1,66 -1,0 +1,66 @@@
+package org.apache.lucene.index;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.lucene.document.Document;
+
+public class ThreadAffinityDocumentsWriterThreadPool extends DocumentsWriterThreadPool {
+ private static final class AffinityThreadState extends ThreadState {
+ int numAssignedThreads;
+
+ @Override
+ void finish() {
+ numAssignedThreads--;
+ }
+ }
-
++
+ private Map<Thread, AffinityThreadState> threadBindings = new HashMap<Thread, AffinityThreadState>();
+
- ThreadAffinityDocumentsWriterThreadPool(int maxNumThreadStates) {
++ public ThreadAffinityDocumentsWriterThreadPool(int maxNumThreadStates) {
+ super(maxNumThreadStates);
+ }
-
++
+ @Override
+ protected ThreadState selectThreadState(Thread requestingThread, DocumentsWriter documentsWriter, Document doc) {
+ AffinityThreadState threadState = threadBindings.get(requestingThread);
+ // First, find a thread state. If this thread already
+ // has affinity to a specific ThreadState, use that one
+ // again.
+ if (threadState == null) {
+ AffinityThreadState minThreadState = null;
+ for(int i=0;i<allThreadStates.length;i++) {
+ AffinityThreadState ts = (AffinityThreadState) allThreadStates[i];
+ if (minThreadState == null || ts.numAssignedThreads < minThreadState.numAssignedThreads)
+ minThreadState = ts;
+ }
+ if (minThreadState != null && (minThreadState.numAssignedThreads == 0 || allThreadStates.length >= maxNumThreadStates)) {
+ threadState = minThreadState;
+ } else {
+ threadState = addNewThreadState(documentsWriter, new AffinityThreadState());
+ }
+ threadBindings.put(requestingThread, threadState);
+ }
+ threadState.numAssignedThreads++;
-
++
+ return threadState;
+ }
-
++
+ @Override
+ protected void clearThreadBindings(ThreadState flushedThread) {
+ Iterator<Entry<Thread, AffinityThreadState>> it = threadBindings.entrySet().iterator();
+ while (it.hasNext()) {
+ Entry<Thread, AffinityThreadState> e = it.next();
+ if (e.getValue() == flushedThread) {
+ it.remove();
+ }
+ }
+ }
+
+ @Override
+ protected void clearAllThreadBindings() {
+ threadBindings.clear();
+ }
+}
diff --cc lucene/src/test/org/apache/lucene/index/TestAddIndexes.java
index 5c07abf7b91,8cafb7e110d..e407baada13
--- a/lucene/src/test/org/apache/lucene/index/TestAddIndexes.java
+++ b/lucene/src/test/org/apache/lucene/index/TestAddIndexes.java
@@@ -22,23 -24,31 +24,31 @@@ import java.util.List
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
+ import org.apache.lucene.document.Field.Index;
+ import org.apache.lucene.document.Field.Store;
+ import org.apache.lucene.document.Field.TermVector;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
+ import org.apache.lucene.index.codecs.CodecProvider;
+ import org.apache.lucene.index.codecs.mocksep.MockSepCodec;
+ import org.apache.lucene.index.codecs.simpletext.SimpleTextCodec;
+ import org.apache.lucene.index.codecs.standard.StandardCodec;
+ import org.apache.lucene.search.DocIdSetIterator;
+ import org.apache.lucene.search.PhraseQuery;
+ import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
+ import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.store.RAMDirectory;
- import org.apache.lucene.store.MockRAMDirectory;
+ import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
- import org.apache.lucene.search.DocIdSetIterator;
- import org.apache.lucene.search.PhraseQuery;
-
public class TestAddIndexes extends LuceneTestCase {
-
++
public void testSimpleCase() throws IOException {
// main directory
- Directory dir = new RAMDirectory();
+ Directory dir = newDirectory();
// two auxiliary directories
- Directory aux = new RAMDirectory();
- Directory aux2 = new RAMDirectory();
+ Directory aux = newDirectory();
+ Directory aux2 = newDirectory();
IndexWriter writer = null;
@@@ -179,13 -198,13 +198,13 @@@
// docs, so 10 pending deletes:
for (int i = 0; i < 20; i++) {
Document doc = new Document();
- doc.add(new Field("id", "" + (i % 10), Field.Store.NO, Field.Index.NOT_ANALYZED));
- doc.add(new Field("content", "bbb " + i, Field.Store.NO, Field.Index.ANALYZED));
+ doc.add(newField("id", "" + (i % 10), Field.Store.NO, Field.Index.NOT_ANALYZED));
+ doc.add(newField("content", "bbb " + i, Field.Store.NO, Field.Index.ANALYZED));
writer.updateDocument(new Term("id", "" + (i%10)), doc);
}
-
- writer.addIndexes(new Directory[] {aux});
--
++
+ writer.addIndexes(aux);
-
++
// Deletes one of the 10 added docs, leaving 9:
PhraseQuery q = new PhraseQuery();
q.add(new Term("content", "bbb"));
@@@ -537,4 -608,442 +608,442 @@@
dir2.close();
}
+ // TODO: these are also in TestIndexWriter... add a simple doc-writing method
+ // like this to LuceneTestCase?
+ private void addDoc(IndexWriter writer) throws IOException
+ {
+ Document doc = new Document();
+ doc.add(newField("content", "aaa", Field.Store.NO, Field.Index.ANALYZED));
+ writer.addDocument(doc);
+ }
-
++
+ private abstract class RunAddIndexesThreads {
+
+ Directory dir, dir2;
+ final static int NUM_INIT_DOCS = 17;
+ IndexWriter writer2;
+ final List<Throwable> failures = new ArrayList<Throwable>();
+ volatile boolean didClose;
+ final IndexReader[] readers;
+ final int NUM_COPY;
+ final static int NUM_THREADS = 5;
+ final Thread[] threads = new Thread[NUM_THREADS];
+
+ public RunAddIndexesThreads(int numCopy) throws Throwable {
+ NUM_COPY = numCopy;
+ dir = new MockDirectoryWrapper(random, new RAMDirectory());
+ IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
+ TEST_VERSION_CURRENT, new MockAnalyzer())
+ .setMaxBufferedDocs(2));
+ for (int i = 0; i < NUM_INIT_DOCS; i++)
+ addDoc(writer);
+ writer.close();
+
+ dir2 = newDirectory();
+ writer2 = new IndexWriter(dir2, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
+ writer2.setInfoStream(VERBOSE ? System.out : null);
+ writer2.commit();
-
++
+
+ readers = new IndexReader[NUM_COPY];
+ for(int i=0;i<NUM_COPY;i++)
+ readers[i] = IndexReader.open(dir, true);
+ }
+
+ void launchThreads(final int numIter) {
+
+ for(int i=0;i<NUM_THREADS;i++) {
+ threads[i] = new Thread() {
+ @Override
+ public void run() {
+ try {
+
+ final Directory[] dirs = new Directory[NUM_COPY];
+ for(int k=0;k<NUM_COPY;k++)
+ dirs[k] = new MockDirectoryWrapper(random, new RAMDirectory(dir));
+
+ int j=0;
+
+ while(true) {
+ // System.out.println(Thread.currentThread().getName() + ": iter j=" + j);
+ if (numIter > 0 && j == numIter)
+ break;
+ doBody(j++, dirs);
+ }
+ } catch (Throwable t) {
+ handle(t);
+ }
+ }
+ };
+ }
+
+ for(int i=0;i<NUM_THREADS;i++)
+ threads[i].start();
+ }
+
+ void joinThreads() throws Exception {
+ for(int i=0;i<NUM_THREADS;i++)
+ threads[i].join();
+ }
+
+ void close(boolean doWait) throws Throwable {
+ didClose = true;
+ writer2.close(doWait);
+ }
+
+ void closeDir() throws Throwable {
+ for(int i=0;i<NUM_COPY;i++)
+ readers[i].close();
+ dir2.close();
+ }
+
+ abstract void doBody(int j, Directory[] dirs) throws Throwable;
+ abstract void handle(Throwable t);
+ }
+
+ private class CommitAndAddIndexes extends RunAddIndexesThreads {
+ public CommitAndAddIndexes(int numCopy) throws Throwable {
+ super(numCopy);
+ }
+
+ @Override
+ void handle(Throwable t) {
+ t.printStackTrace(System.out);
+ synchronized(failures) {
+ failures.add(t);
+ }
+ }
+
+ @Override
+ void doBody(int j, Directory[] dirs) throws Throwable {
+ switch(j%5) {
+ case 0:
+ if (VERBOSE) {
+ System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(Dir[]) then optimize");
+ }
+ writer2.addIndexes(dirs);
+ writer2.optimize();
+ break;
+ case 1:
+ if (VERBOSE) {
+ System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(Dir[])");
+ }
+ writer2.addIndexes(dirs);
+ break;
+ case 2:
+ if (VERBOSE) {
+ System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(IndexReader[])");
+ }
+ writer2.addIndexes(readers);
+ break;
+ case 3:
+ if (VERBOSE) {
+ System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(Dir[]) then maybeMerge");
+ }
+ writer2.addIndexes(dirs);
+ writer2.maybeMerge();
+ break;
+ case 4:
+ if (VERBOSE) {
+ System.out.println(Thread.currentThread().getName() + ": TEST: commit");
+ }
+ writer2.commit();
+ }
+ }
+ }
-
++
+ // LUCENE-1335: test simultaneous addIndexes & commits
+ // from multiple threads
+ public void testAddIndexesWithThreads() throws Throwable {
+
+ final int NUM_ITER = 15;
+ final int NUM_COPY = 3;
+ CommitAndAddIndexes c = new CommitAndAddIndexes(NUM_COPY);
+ c.writer2.setInfoStream(VERBOSE ? System.out : null);
+ c.launchThreads(NUM_ITER);
+
+ for(int i=0;i<100;i++)
+ addDoc(c.writer2);
+
+ c.joinThreads();
+
+ int expectedNumDocs = 100+NUM_COPY*(4*NUM_ITER/5)*RunAddIndexesThreads.NUM_THREADS*RunAddIndexesThreads.NUM_INIT_DOCS;
+ assertEquals(expectedNumDocs, c.writer2.numDocs());
+
+ c.close(true);
+
+ assertTrue(c.failures.size() == 0);
+
+ _TestUtil.checkIndex(c.dir2);
+
+ IndexReader reader = IndexReader.open(c.dir2, true);
+ assertEquals(expectedNumDocs, reader.numDocs());
+ reader.close();
+
+ c.closeDir();
+ }
+
+ private class CommitAndAddIndexes2 extends CommitAndAddIndexes {
+ public CommitAndAddIndexes2(int numCopy) throws Throwable {
+ super(numCopy);
+ }
+
+ @Override
+ void handle(Throwable t) {
+ if (!(t instanceof AlreadyClosedException) && !(t instanceof NullPointerException)) {
+ t.printStackTrace(System.out);
+ synchronized(failures) {
+ failures.add(t);
+ }
+ }
+ }
+ }
+
+ // LUCENE-1335: test simultaneous addIndexes & close
+ public void testAddIndexesWithClose() throws Throwable {
+ final int NUM_COPY = 3;
+ CommitAndAddIndexes2 c = new CommitAndAddIndexes2(NUM_COPY);
+ //c.writer2.setInfoStream(System.out);
+ c.launchThreads(-1);
+
+ // Close w/o first stopping/joining the threads
+ c.close(true);
+ //c.writer2.close();
+
+ c.joinThreads();
+
+ _TestUtil.checkIndex(c.dir2);
+
+ c.closeDir();
+
+ assertTrue(c.failures.size() == 0);
+ }
+
+ private class CommitAndAddIndexes3 extends RunAddIndexesThreads {
+ public CommitAndAddIndexes3(int numCopy) throws Throwable {
+ super(numCopy);
+ }
+
+ @Override
+ void doBody(int j, Directory[] dirs) throws Throwable {
+ switch(j%5) {
+ case 0:
+ if (VERBOSE) {
+ System.out.println("TEST: " + Thread.currentThread().getName() + ": addIndexes + optimize");
+ }
+ writer2.addIndexes(dirs);
+ writer2.optimize();
+ break;
+ case 1:
+ if (VERBOSE) {
+ System.out.println("TEST: " + Thread.currentThread().getName() + ": addIndexes");
+ }
+ writer2.addIndexes(dirs);
+ break;
+ case 2:
+ if (VERBOSE) {
+ System.out.println("TEST: " + Thread.currentThread().getName() + ": addIndexes(IR[])");
+ }
+ writer2.addIndexes(readers);
+ break;
+ case 3:
+ if (VERBOSE) {
+ System.out.println("TEST: " + Thread.currentThread().getName() + ": optimize");
+ }
+ writer2.optimize();
+ break;
+ case 4:
+ if (VERBOSE) {
+ System.out.println("TEST: " + Thread.currentThread().getName() + ": commit");
+ }
+ writer2.commit();
+ }
+ }
+
+ @Override
+ void handle(Throwable t) {
+ boolean report = true;
+
+ if (t instanceof AlreadyClosedException || t instanceof MergePolicy.MergeAbortedException || t instanceof NullPointerException) {
+ report = !didClose;
+ } else if (t instanceof IOException) {
+ Throwable t2 = t.getCause();
+ if (t2 instanceof MergePolicy.MergeAbortedException) {
+ report = !didClose;
+ }
+ }
+ if (report) {
+ t.printStackTrace(System.out);
+ synchronized(failures) {
+ failures.add(t);
+ }
+ }
+ }
+ }
+
+ // LUCENE-1335: test simultaneous addIndexes & close
+ public void testAddIndexesWithCloseNoWait() throws Throwable {
+
+ final int NUM_COPY = 50;
+ CommitAndAddIndexes3 c = new CommitAndAddIndexes3(NUM_COPY);
+ if (VERBOSE) {
+ c.writer2.setInfoStream(System.out);
+ }
+ c.launchThreads(-1);
+
+ Thread.sleep(_TestUtil.nextInt(random, 10, 500));
+
+ // Close w/o first stopping/joining the threads
+ if (VERBOSE) {
+ System.out.println("TEST: now close(false)");
+ }
+ c.close(false);
+
+ c.joinThreads();
+
+ if (VERBOSE) {
+ System.out.println("TEST: done join threads");
+ }
+ _TestUtil.checkIndex(c.dir2);
+
+ c.closeDir();
+
+ assertTrue(c.failures.size() == 0);
+ }
+
+ // LUCENE-1335: test simultaneous addIndexes & close
+ public void testAddIndexesWithRollback() throws Throwable {
+
+ final int NUM_COPY = 50;
+ CommitAndAddIndexes3 c = new CommitAndAddIndexes3(NUM_COPY);
+ c.launchThreads(-1);
+
+ Thread.sleep(_TestUtil.nextInt(random, 100, 500));
+
+ // Close w/o first stopping/joining the threads
+ if (VERBOSE) {
+ System.out.println("TEST: now force rollback");
+ }
+ c.didClose = true;
+ c.writer2.rollback();
+
+ c.joinThreads();
+
+ _TestUtil.checkIndex(c.dir2);
+
+ c.closeDir();
+
+ assertTrue(c.failures.size() == 0);
+ }
-
++
+ private void addDocs3(IndexWriter writer, int numDocs) throws IOException {
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ doc.add(newField("content", "aaa", Field.Store.NO, Field.Index.ANALYZED));
+ doc.add(newField("id", "" + i, Field.Store.YES, Field.Index.ANALYZED));
+ writer.addDocument(doc);
+ }
+ }
+
+ public void testSimpleCaseCustomCodecProvider() throws IOException {
+ // main directory
+ Directory dir = newDirectory();
+ // two auxiliary directories
+ Directory aux = newDirectory();
+ Directory aux2 = newDirectory();
+ CodecProvider provider = new MockCodecProvider();
+ IndexWriter writer = null;
+
+ writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT,
+ new MockAnalyzer()).setOpenMode(OpenMode.CREATE).setCodecProvider(
+ provider));
+ // add 100 documents
+ addDocs3(writer, 100);
+ assertEquals(100, writer.maxDoc());
+ writer.commit();
+ writer.close();
+ _TestUtil.checkIndex(dir, provider);
+
+ writer = newWriter(
+ aux,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setOpenMode(OpenMode.CREATE).
+ setCodecProvider(provider).
+ setMaxBufferedDocs(10).
+ setMergePolicy(newLogMergePolicy(false))
+ );
+ // add 40 documents in separate files
+ addDocs(writer, 40);
+ assertEquals(40, writer.maxDoc());
+ writer.commit();
+ writer.close();
+
+ writer = newWriter(
+ aux2,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setOpenMode(OpenMode.CREATE).
+ setCodecProvider(provider)
+ );
+ // add 40 documents in compound files
+ addDocs2(writer, 50);
+ assertEquals(50, writer.maxDoc());
+ writer.commit();
+ writer.close();
+
+ // test doc count before segments are merged
+ writer = newWriter(
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setOpenMode(OpenMode.APPEND).
+ setCodecProvider(provider)
+ );
+ assertEquals(100, writer.maxDoc());
+ writer.addIndexes(aux, aux2);
+ assertEquals(190, writer.maxDoc());
+ writer.close();
+ _TestUtil.checkIndex(dir, provider);
+
+ dir.close();
+ aux.close();
+ aux2.close();
+ }
+
+ public static class MockCodecProvider extends CodecProvider {
+ public MockCodecProvider() {
+ StandardCodec standardCodec = new StandardCodec();
+ SimpleTextCodec simpleTextCodec = new SimpleTextCodec();
+ MockSepCodec mockSepCodec = new MockSepCodec();
+ register(standardCodec);
+ register(mockSepCodec);
+ register(simpleTextCodec);
+ setFieldCodec("id", simpleTextCodec.name);
+ setFieldCodec("content", mockSepCodec.name);
+ }
+ }
+
+ // LUCENE-2790: tests that the non CFS files were deleted by addIndexes
+ public void testNonCFSLeftovers() throws Exception {
+ Directory[] dirs = new Directory[2];
+ for (int i = 0; i < dirs.length; i++) {
+ dirs[i] = new RAMDirectory();
+ IndexWriter w = new IndexWriter(dirs[i], new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
+ Document d = new Document();
+ d.add(new Field("c", "v", Store.YES, Index.ANALYZED, TermVector.YES));
+ w.addDocument(d);
+ w.close();
+ }
-
++
+ IndexReader[] readers = new IndexReader[] { IndexReader.open(dirs[0]), IndexReader.open(dirs[1]) };
-
++
+ Directory dir = new RAMDirectory();
+ IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer());
+ LogMergePolicy lmp = (LogMergePolicy) conf.getMergePolicy();
+ lmp.setNoCFSRatio(1.0); // Force creation of CFS
+ IndexWriter w3 = new IndexWriter(dir, conf);
+ w3.addIndexes(readers);
+ w3.close();
-
++
+ assertEquals("Only one compound segment should exist", 3, dir.listAll().length);
+ }
-
++
}
diff --cc lucene/src/test/org/apache/lucene/index/TestByteSlices.java
index f23fac4a890,5e3a795990f..1bf7ad7dec2
--- a/lucene/src/test/org/apache/lucene/index/TestByteSlices.java
+++ b/lucene/src/test/org/apache/lucene/index/TestByteSlices.java
@@@ -14,10 -14,11 +14,9 @@@ package org.apache.lucene.index
* limitations under the License.
*/
- import java.util.Random;
- import java.util.ArrayList;
- import java.util.List;
-import java.util.concurrent.locks.ReentrantLock;
-
+ import org.apache.lucene.util.ByteBlockPool;
import org.apache.lucene.util.LuceneTestCase;
+ import org.apache.lucene.util.RecyclingByteBlockAllocator;
public class TestByteSlices extends LuceneTestCase {
@@@ -72,10 -41,10 +39,10 @@@
starts[stream] = -1;
counters[stream] = 0;
}
--
++
int num = 10000 * RANDOM_MULTIPLIER;
for (int iter = 0; iter < num; iter++) {
- int stream = r.nextInt(NUM_STREAM);
+ int stream = random.nextInt(NUM_STREAM);
if (VERBOSE)
System.out.println("write stream=" + stream);
@@@ -100,7 -69,7 +67,7 @@@
if (VERBOSE)
System.out.println(" addr now " + uptos[stream]);
}
--
++
for(int stream=0;stream<NUM_STREAM;stream++) {
if (VERBOSE)
System.out.println(" stream=" + stream + " count=" + counters[stream]);
@@@ -109,7 -78,7 +76,7 @@@
reader.init(pool, starts[stream], uptos[stream]);
for(int j=0;j<counters[stream];j++) {
reader.readVInt();
-- assertEquals(j, reader.readVInt());
++ assertEquals(j, reader.readVInt());
}
}
}
diff --cc lucene/src/test/org/apache/lucene/index/TestCodecs.java
index 6c24093f910,92b8368b5b8..b315c825c29
--- a/lucene/src/test/org/apache/lucene/index/TestCodecs.java
+++ b/lucene/src/test/org/apache/lucene/index/TestCodecs.java
@@@ -397,17 -397,13 +397,13 @@@ public class TestCodecs extends LuceneT
}
}
- public static class SepCodecs extends CodecProvider {
+ public static class MockSepCodecs extends CodecProvider {
- protected SepCodecs() {
- this.register(new SepCodec());
- }
-
- @Override
- public Codec getWriter(final SegmentWriteState state) {
- return this.lookup("Sep");
+ protected MockSepCodecs() {
+ this.register(new MockSepCodec());
+ this.setDefaultFieldCodec("MockSep");
}
-
+
}
private class Verify extends Thread {
diff --cc lucene/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java
index c3edcbaffea,9c7c3bf0846..8bb31260c9d
--- a/lucene/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java
+++ b/lucene/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java
@@@ -44,14 -43,23 +43,23 @@@ public class TestConcurrentMergeSchedul
}
@Override
- public void eval(MockRAMDirectory dir) throws IOException {
- if (doFail && Thread.currentThread().getName().equals("main")) {
+ public void eval(MockDirectoryWrapper dir) throws IOException {
+ if (doFail && (Thread.currentThread().getName().equals("main")
+ || Thread.currentThread().getName().equals("Main Thread"))) {
+ boolean isDoFlush = false;
+ boolean isClose = false;
StackTraceElement[] trace = new Exception().getStackTrace();
for (int i = 0; i < trace.length; i++) {
- if ("doFlush".equals(trace[i].getMethodName())) {
+ if ("flush".equals(trace[i].getMethodName())) {
- hitExc = true;
- throw new IOException("now failing during flush");
+ isDoFlush = true;
}
+ if ("close".equals(trace[i].getMethodName())) {
+ isClose = true;
+ }
+ }
+ if (isDoFlush && !isClose && random.nextBoolean()) {
+ hitExc = true;
+ throw new IOException(Thread.currentThread().getName() + ": now failing during flush");
}
}
}
diff --cc lucene/src/test/org/apache/lucene/index/TestDeletionPolicy.java
index 41d9aa03a79,d474cdae4c4..c9a6033ee7a
--- a/lucene/src/test/org/apache/lucene/index/TestDeletionPolicy.java
+++ b/lucene/src/test/org/apache/lucene/index/TestDeletionPolicy.java
@@@ -42,7 -40,7 +40,7 @@@ import org.apache.lucene.util.LuceneTes
*/
public class TestDeletionPolicy extends LuceneTestCase {
--
++
private void verifyCommitOrder(List<? extends IndexCommit> commits) throws IOException {
final IndexCommit firstCommit = commits.get(0);
long last = SegmentInfos.generationFromSegmentsFileName(firstCommit.getSegmentsFileName());
@@@ -131,7 -129,7 +129,7 @@@
verifyCommitOrder(commits);
doDeletes(commits, true);
}
--
++
private void doDeletes(List<? extends IndexCommit> commits, boolean isCommit) {
// Assert that we really are only called for each new
@@@ -239,7 -238,7 +238,7 @@@
// seconds of the last one's mod time, and, that I can
// open a reader on each:
long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
--
++
String fileName = IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS,
"",
gen);
@@@ -257,7 -266,7 +266,7 @@@
// OK
break;
}
--
++
dir.deleteFile(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen));
gen--;
}
@@@ -409,7 -421,7 +421,7 @@@
// Now 8 because we made another commit
assertEquals(7, IndexReader.listCommits(dir).size());
--
++
r = IndexReader.open(dir, true);
// Not optimized because we rolled it back, and now only
// 10 docs
@@@ -429,9 -441,9 +441,9 @@@
// Now open writer on the commit just before optimize,
// but this time keeping only the last commit:
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setIndexCommit(lastCommit));
+ writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setIndexCommit(lastCommit));
assertEquals(10, writer.numDocs());
--
++
// Reader still sees optimized index, because writer
// opened on the prior commit has not yet committed:
r = IndexReader.open(dir, true);
@@@ -581,7 -590,7 +590,7 @@@
lmp.setUseCompoundFile(useCompoundFile);
IndexWriter writer = new IndexWriter(dir, conf);
writer.close();
-- Term searchTerm = new Term("content", "aaa");
++ Term searchTerm = new Term("content", "aaa");
Query query = new TermQuery(searchTerm);
for(int i=0;i<N+1;i++) {
@@@ -688,7 -696,7 +696,7 @@@
lmp.setUseCompoundFile(useCompoundFile);
IndexWriter writer = new IndexWriter(dir, conf);
writer.close();
-- Term searchTerm = new Term("content", "aaa");
++ Term searchTerm = new Term("content", "aaa");
Query query = new TermQuery(searchTerm);
for(int i=0;i<N+1;i++) {
@@@ -768,7 -776,7 +776,7 @@@
}
gen--;
}
--
++
dir.close();
}
}
diff --cc lucene/src/test/org/apache/lucene/index/TestDoc.java
index 8d544fc2902,33132336d85..ef9c9ae1caa
--- a/lucene/src/test/org/apache/lucene/index/TestDoc.java
+++ b/lucene/src/test/org/apache/lucene/index/TestDoc.java
@@@ -109,11 -107,15 +107,15 @@@ public class TestDoc extends LuceneTest
public void testIndexAndMerge() throws Exception {
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw, true);
-
+
- Directory directory = FSDirectory.open(indexDir);
- IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer())
- .setOpenMode(OpenMode.CREATE));
+ Directory directory = newFSDirectory(indexDir);
+ IndexWriter writer = new IndexWriter(
+ directory,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setOpenMode(OpenMode.CREATE).
+ setMaxBufferedDocs(-1).
+ setMergePolicy(newLogMergePolicy(10))
+ );
SegmentInfo si1 = indexDoc(writer, "test.txt");
printSegment(out, si1);
@@@ -130,7 -132,7 +132,7 @@@
SegmentInfo siMerge3 = merge(siMerge, siMerge2, "merge3", false);
printSegment(out, siMerge3);
--
++
directory.close();
out.close();
sw.close();
@@@ -160,7 -166,7 +166,7 @@@
siMerge3 = merge(siMerge, siMerge2, "merge3", true);
printSegment(out, siMerge3);
--
++
directory.close();
out.close();
sw.close();
@@@ -191,14 -197,16 +197,16 @@@
merger.add(r1);
merger.add(r2);
merger.merge();
- merger.closeReaders();
-
+ r1.close();
+ r2.close();
-
++
final SegmentInfo info = new SegmentInfo(merged, si1.docCount + si2.docCount, si1.dir,
- useCompoundFile, merger.hasProx(), merger.getCodec());
-
+ useCompoundFile, merger.fieldInfos().hasProx(), merger.getSegmentCodecs(),
+ merger.fieldInfos().hasVectors());
-
++
if (useCompoundFile) {
- List<String> filesToDelete = merger.createCompoundFile(merged + ".cfs", info);
- for (final String fileToDelete : filesToDelete)
+ Collection<String> filesToDelete = merger.createCompoundFile(merged + ".cfs", info);
- for (final String fileToDelete : filesToDelete)
++ for (final String fileToDelete : filesToDelete)
si1.dir.deleteFile(fileToDelete);
}
diff --cc lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.java
index e95aac9c416,bdaa1dbe198..c4df20b4746
--- a/lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.java
@@@ -36,14 -36,21 +36,21 @@@ import java.util.*
*/
public class TestIndexFileDeleter extends LuceneTestCase {
--
++
public void testDeleteLeftoverFiles() throws IOException {
+ MockDirectoryWrapper dir = newDirectory();
+ dir.setPreventDoubleWrite(false);
+
+ LogMergePolicy mergePolicy = newLogMergePolicy(true, 10);
+ mergePolicy.setNoCFSRatio(1); // This test expects all of its segments to be in CFS
- Directory dir = new RAMDirectory();
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMaxBufferedDocs(10).
+ setMergePolicy(mergePolicy)
+ );
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer())
- .setMaxBufferedDocs(10));
int i;
for(i=0;i<35;i++) {
addDoc(writer, i);
@@@ -116,7 -123,7 +123,7 @@@
copyFile(dir, "_2_1." + normSuffix, "_1_1.f" + contentFieldIndex);
// Create a bogus separate del file for a
-- // segment that already has a separate del file:
++ // segment that already has a separate del file:
copyFile(dir, "_0_1.del", "_0_2.del");
// Create a bogus separate del file for a
@@@ -152,9 -159,9 +159,9 @@@
Arrays.sort(files);
Arrays.sort(files2);
--
++
Set<String> dif = difFiles(files, files2);
--
++
if (!Arrays.equals(files, files2)) {
fail("IndexFileDeleter failed to delete unreferenced extra files: should have deleted " + (filesPre.length-files.length) + " files but only deleted " + (filesPre.length - files2.length) + "; expected files:\n " + asString(files) + "\n actual files:\n " + asString(files2)+"\ndif: "+dif);
}
@@@ -164,7 -171,7 +171,7 @@@
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
Set<String> extra = new HashSet<String>();
--
++
for (int x=0; x < files1.length; x++) {
set1.add(files1[x]);
}
@@@ -187,7 -194,7 +194,7 @@@
}
return extra;
}
--
++
private String asString(String[] l) {
String s = "";
for(int i=0;i<l.length;i++) {
diff --cc lucene/src/test/org/apache/lucene/index/TestIndexReader.java
index f40fbb95cd9,39208d1561d..1fcebde77d4
--- a/lucene/src/test/org/apache/lucene/index/TestIndexReader.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexReader.java
@@@ -60,38 -58,26 +58,26 @@@ import org.apache.lucene.util.Bits
public class TestIndexReader extends LuceneTestCase
{
- /** Main for running test case by itself. */
- public static void main(String args[]) {
- TestRunner.run (new TestSuite(TestIndexReader.class));
- // TestRunner.run (new TestIndexReader("testBasicDelete"));
- // TestRunner.run (new TestIndexReader("testDeleteReaderWriterConflict"));
- // TestRunner.run (new TestIndexReader("testDeleteReaderReaderConflict"));
- // TestRunner.run (new TestIndexReader("testFilesOpenClose"));
- }
-
+
- public TestIndexReader(String name) {
- super(name);
- }
-
public void testCommitUserData() throws Exception {
- RAMDirectory d = new MockRAMDirectory();
+ Directory d = newDirectory();
Map<String,String> commitUserData = new HashMap<String,String>();
commitUserData.put("foo", "fighters");
--
++
// set up writer
- IndexWriter writer = new IndexWriter(d, new IndexWriterConfig(
+ IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer())
.setMaxBufferedDocs(2));
for(int i=0;i<27;i++)
addDocumentWithFields(writer);
writer.close();
--
++
IndexReader r = IndexReader.open(d, false);
r.deleteDocument(5);
r.flush(commitUserData);
r.close();
--
++
SegmentInfos sis = new SegmentInfos();
sis.read(d);
IndexReader r2 = IndexReader.open(d, false);
@@@ -127,10 -113,10 +113,10 @@@
r3.close();
d.close();
}
--
++
public void testIsCurrent() throws Exception {
- RAMDirectory d = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(d, new IndexWriterConfig(
+ Directory d = newDirectory();
- IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
++ IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()));
addDocumentWithFields(writer);
writer.close();
@@@ -186,9 -195,15 +195,15 @@@
}
// new termvector fields
for (int i = 0; i < 5*mergeFactor; i++) {
- addDocumentWithTermVectorFields(writer);
+ doc = new Document();
+ doc.add(new Field("tvnot","tvnot", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
+ doc.add(new Field("termvector","termvector", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
+ doc.add(new Field("tvoffset","tvoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS));
+ doc.add(new Field("tvposition","tvposition", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
+ doc.add(newField("tvpositionoffset","tvpositionoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
+ writer.addDocument(doc);
}
--
++
writer.close();
// verify fields again
reader = IndexReader.open(d, false);
@@@ -207,10 -222,10 +222,10 @@@
assertTrue(fieldNames.contains("tvposition"));
assertTrue(fieldNames.contains("tvoffset"));
assertTrue(fieldNames.contains("tvpositionoffset"));
--
++
// verify that only indexed fields were returned
fieldNames = reader.getFieldNames(IndexReader.FieldOption.INDEXED);
-- assertEquals(11, fieldNames.size()); // 6 original + the 5 termvector fields
++ assertEquals(11, fieldNames.size()); // 6 original + the 5 termvector fields
assertTrue(fieldNames.contains("keyword"));
assertTrue(fieldNames.contains("text"));
assertTrue(fieldNames.contains("unstored"));
@@@ -222,26 -237,26 +237,26 @@@
assertTrue(fieldNames.contains("tvposition"));
assertTrue(fieldNames.contains("tvoffset"));
assertTrue(fieldNames.contains("tvpositionoffset"));
--
++
// verify that only unindexed fields were returned
fieldNames = reader.getFieldNames(IndexReader.FieldOption.UNINDEXED);
assertEquals(2, fieldNames.size()); // the following fields
assertTrue(fieldNames.contains("unindexed"));
assertTrue(fieldNames.contains("unindexed2"));
--
-- // verify index term vector fields
++
++ // verify index term vector fields
fieldNames = reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR);
assertEquals(1, fieldNames.size()); // 1 field has term vector only
assertTrue(fieldNames.contains("termvector"));
--
++
fieldNames = reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION);
assertEquals(1, fieldNames.size()); // 4 fields are indexed with term vectors
assertTrue(fieldNames.contains("tvposition"));
--
++
fieldNames = reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_OFFSET);
assertEquals(1, fieldNames.size()); // 4 fields are indexed with term vectors
assertTrue(fieldNames.contains("tvoffset"));
--
++
fieldNames = reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION_OFFSET);
assertEquals(1, fieldNames.size()); // 4 fields are indexed with term vectors
assertTrue(fieldNames.contains("tvpositionoffset"));
@@@ -345,13 -363,13 +363,13 @@@
reader2.close();
dir.close();
}
--
++
public void testBinaryFields() throws IOException {
- Directory dir = new RAMDirectory();
+ Directory dir = newDirectory();
byte[] bin = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
-
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
--
++
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
-
++
for (int i = 0; i < 10; i++) {
addDoc(writer, "document number " + (i + 1));
addDocumentWithFields(writer);
@@@ -563,14 -582,14 +582,14 @@@
reader = IndexReader.open(dir, false);
reader.setNorm(0, "content", (float) 2.0);
reader.close();
--
++
// now open reader again & set norm for doc 0 (writes to _0_2.s0)
reader = IndexReader.open(dir, false);
reader.setNorm(0, "content", (float) 2.0);
reader.close();
assertFalse("failed to remove first generation norms file on writing second generation",
dir.fileExists("_0_1.s0"));
--
++
dir.close();
}
@@@ -593,7 -612,7 +612,7 @@@
}
rmDir(fileDirName);
}*/
--
++
public void testDeleteReaderWriterConflictOptimized() throws IOException{
deleteReaderWriterConflict(true);
}
@@@ -789,7 -795,11 +795,11 @@@
} catch(IOException e) {
// expected exception
}
- IndexWriter.unlock(dir); // this should not be done in the real world!
+ try {
- IndexWriter.unlock(dir); // this should not be done in the real world!
++ IndexWriter.unlock(dir); // this should not be done in the real world!
+ } catch (LockReleaseFailedException lrfe) {
+ writer.close();
+ }
reader.deleteDocument(0);
reader.close();
writer.close();
@@@ -852,7 -862,7 +862,7 @@@
public void testDeleteReaderReaderConflictUnoptimized() throws IOException{
deleteReaderReaderConflict(false);
}
--
++
public void testDeleteReaderReaderConflictOptimized() throws IOException{
deleteReaderReaderConflict(true);
}
@@@ -866,14 -876,14 +876,14 @@@
Term searchTerm = new Term("content", "aaa");
int START_COUNT = 157;
int END_COUNT = 144;
--
++
// First build up a starting index:
- RAMDirectory startDir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(startDir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
+ MockDirectoryWrapper startDir = newDirectory();
+ IndexWriter writer = new IndexWriter(startDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
for(int i=0;i<157;i++) {
Document d = new Document();
- d.add(new Field("id", Integer.toString(i), Field.Store.YES, Field.Index.NOT_ANALYZED));
- d.add(new Field("content", "aaa " + i, Field.Store.NO, Field.Index.ANALYZED));
+ d.add(newField("id", Integer.toString(i), Field.Store.YES, Field.Index.NOT_ANALYZED));
+ d.add(newField("content", "aaa " + i, Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(d);
if (0==i%10)
writer.commit();
@@@ -1042,8 -1052,8 +1052,8 @@@
}
public void testDocsOutOfOrderJIRA140() throws IOException {
- Directory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- Directory dir = newDirectory();
++ Directory dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
for(int i=0;i<11;i++) {
addDoc(writer, "aaa");
}
@@@ -1082,8 -1092,8 +1092,8 @@@
public void testExceptionReleaseWriteLockJIRA768() throws IOException {
- Directory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- Directory dir = newDirectory();
++ Directory dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
addDoc(writer, "aaa");
writer.close();
@@@ -1132,7 -1142,35 +1142,35 @@@
} catch (FileNotFoundException e) {
// expected
}
--
++
+ dir.close();
+ }
+
+ public void testMultiReaderDeletes() throws Exception {
+ Directory dir = newDirectory();
+ RandomIndexWriter w = new RandomIndexWriter(random, dir);
+ Document doc = new Document();
+ doc.add(newField("f", "doctor", Field.Store.NO, Field.Index.NOT_ANALYZED));
+ w.addDocument(doc);
+ doc = new Document();
+ w.commit();
+ doc.add(newField("f", "who", Field.Store.NO, Field.Index.NOT_ANALYZED));
+ w.addDocument(doc);
+ IndexReader r = new SlowMultiReaderWrapper(w.getReader());
+ w.close();
+
+ assertNull(r.getDeletedDocs());
+ r.close();
+
+ r = new SlowMultiReaderWrapper(IndexReader.open(dir, false));
+
+ assertNull(r.getDeletedDocs());
+ assertEquals(1, r.deleteDocuments(new Term("f", "doctor")));
+ assertNotNull(r.getDeletedDocs());
+ assertTrue(r.getDeletedDocs().get(0));
+ assertEquals(1, r.deleteDocuments(new Term("f", "who")));
+ assertTrue(r.getDeletedDocs().get(1));
+ r.close();
dir.close();
}
@@@ -1261,35 -1298,27 +1298,27 @@@
private void addDocumentWithTermVectorFields(IndexWriter writer) throws IOException
{
Document doc = new Document();
- doc.add(new Field("tvnot","tvnot", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
- doc.add(new Field("termvector","termvector", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
- doc.add(new Field("tvoffset","tvoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS));
- doc.add(new Field("tvposition","tvposition", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
- doc.add(new Field("tvpositionoffset","tvpositionoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
-
+ doc.add(newField("tvnot","tvnot", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
+ doc.add(newField("termvector","termvector", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
+ doc.add(newField("tvoffset","tvoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS));
+ doc.add(newField("tvposition","tvposition", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
+ doc.add(newField("tvpositionoffset","tvpositionoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
-
++
writer.addDocument(doc);
}
--
- private void addDoc(IndexWriter writer, String value) throws IOException
- {
++
+ private void addDoc(IndexWriter writer, String value) throws IOException {
Document doc = new Document();
- doc.add(new Field("content", value, Field.Store.NO, Field.Index.ANALYZED));
+ doc.add(newField("content", value, Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
}
- private void rmDir(File dir) {
- File[] files = dir.listFiles();
- for (int i = 0; i < files.length; i++) {
- files[i].delete();
- }
- dir.delete();
- }
public static void assertIndexEquals(IndexReader index1, IndexReader index2) throws IOException {
assertEquals("IndexReaders have different values for numDocs.", index1.numDocs(), index2.numDocs());
assertEquals("IndexReaders have different values for maxDoc.", index1.maxDoc(), index2.maxDoc());
assertEquals("Only one IndexReader has deletions.", index1.hasDeletions(), index2.hasDeletions());
assertEquals("Only one index is optimized.", index1.isOptimized(), index2.isOptimized());
--
++
// check field names
Collection<String> fields1 = index1.getFieldNames(FieldOption.ALL);
Collection<String> fields2 = index1.getFieldNames(FieldOption.ALL);
@@@ -1299,7 -1328,7 +1328,7 @@@
while (it1.hasNext()) {
assertEquals("Different field names.", it1.next(), it2.next());
}
--
++
// check norms
it1 = fields1.iterator();
while (it1.hasNext()) {
@@@ -1318,15 -1347,19 +1347,19 @@@
assertSame(norms1, norms2);
}
}
--
++
// check deletions
+ final Bits delDocs1 = MultiFields.getDeletedDocs(index1);
+ final Bits delDocs2 = MultiFields.getDeletedDocs(index2);
for (int i = 0; i < index1.maxDoc(); i++) {
- assertEquals("Doc " + i + " only deleted in one index.", index1.isDeleted(i), index2.isDeleted(i));
+ assertEquals("Doc " + i + " only deleted in one index.",
+ delDocs1 == null || delDocs1.get(i),
+ delDocs2 == null || delDocs2.get(i));
}
--
++
// check stored fields
for (int i = 0; i < index1.maxDoc(); i++) {
- if (!index1.isDeleted(i)) {
+ if (delDocs1 == null || !delDocs1.get(i)) {
Document doc1 = index1.document(i);
Document doc2 = index2.document(i);
List<Fieldable> fieldable1 = doc1.getFields();
@@@ -1339,10 -1372,10 +1372,10 @@@
Field curField2 = (Field) itField2.next();
assertEquals("Different fields names for doc " + i + ".", curField1.name(), curField2.name());
assertEquals("Different field values for doc " + i + ".", curField1.stringValue(), curField2.stringValue());
-- }
++ }
}
}
--
++
// check dictionary and posting lists
FieldsEnum fenum1 = MultiFields.getFields(index1).iterator();
FieldsEnum fenum2 = MultiFields.getFields(index1).iterator();
@@@ -1415,11 -1455,11 +1455,11 @@@
r.close();
r2.close();
d.close();
-- }
++ }
public void testReadOnly() throws Throwable {
- RAMDirectory d = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(d, new IndexWriterConfig(
+ Directory d = newDirectory();
+ IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()));
addDocumentWithFields(writer);
writer.commit();
@@@ -1461,8 -1504,9 +1504,9 @@@
// Make sure reopen to a single segment is still readonly:
IndexReader r3 = r2.reopen();
+ assertFalse(r3 == r2);
r2.close();
--
++
assertFalse(r == r2);
try {
@@@ -1543,21 -1589,21 +1589,21 @@@
// LUCENE-1509
public void testNoDupCommitFileNames() throws Throwable {
- Directory dir = new MockRAMDirectory();
-
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
+ Directory dir = newDirectory();
-
++
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer())
.setMaxBufferedDocs(2));
writer.addDocument(createDocument("a"));
writer.addDocument(createDocument("a"));
writer.addDocument(createDocument("a"));
writer.close();
--
++
Collection<IndexCommit> commits = IndexReader.listCommits(dir);
for (final IndexCommit commit : commits) {
Collection<String> files = commit.getFileNames();
HashSet<String> seen = new HashSet<String>();
-- for (final String fileName : files) {
++ for (final String fileName : files) {
assertTrue("file " + fileName + " was duplicated", !seen.contains(fileName));
seen.add(fileName);
}
@@@ -1745,8 -1807,8 +1807,8 @@@
// LUCENE-2046
public void testPrepareCommitIsCurrent() throws Throwable {
- Directory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
+ Directory dir = newDirectory();
- IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
++ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()));
writer.commit();
Document doc = new Document();
@@@ -1764,4 -1826,40 +1826,40 @@@
r.close();
dir.close();
}
-
++
+ // LUCENE-2753
+ public void testListCommits() throws Exception {
+ Directory dir = newDirectory();
+ SnapshotDeletionPolicy sdp = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());
- IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
++ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
+ TEST_VERSION_CURRENT, null).setIndexDeletionPolicy(sdp));
+ writer.addDocument(new Document());
+ writer.commit();
+ sdp.snapshot("c1");
+ writer.addDocument(new Document());
+ writer.commit();
+ sdp.snapshot("c2");
+ writer.addDocument(new Document());
+ writer.commit();
+ sdp.snapshot("c3");
+ writer.close();
+ long currentGen = 0;
+ for (IndexCommit ic : IndexReader.listCommits(dir)) {
+ assertTrue("currentGen=" + currentGen + " commitGen=" + ic.getGeneration(), currentGen < ic.getGeneration());
+ currentGen = ic.getGeneration();
+ }
+ dir.close();
+ }
+
+ // LUCENE-2812
+ public void testIndexExists() throws Exception {
+ Directory dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
+ writer.addDocument(new Document());
+ writer.prepareCommit();
+ assertFalse(IndexReader.indexExists(dir));
+ writer.close();
+ assertTrue(IndexReader.indexExists(dir));
+ dir.close();
+ }
}
diff --cc lucene/src/test/org/apache/lucene/index/TestIndexReaderClone.java
index 0ff9c73b27a,00f53f6c548..b58e122e86d
--- a/lucene/src/test/org/apache/lucene/index/TestIndexReaderClone.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexReaderClone.java
@@@ -33,11 -33,11 +33,11 @@@ import org.apache.lucene.util.Bits
* implemented properly
*/
public class TestIndexReaderClone extends LuceneTestCase {
-
+
public void testCloneReadOnlySegmentReader() throws Exception {
- final Directory dir1 = new MockRAMDirectory();
+ final Directory dir1 = newDirectory();
- TestIndexReaderReopen.createIndex(dir1, false);
+ TestIndexReaderReopen.createIndex(random, dir1, false);
IndexReader reader = IndexReader.open(dir1, false);
IndexReader readOnlyReader = reader.clone(true);
if (!isReadOnly(readOnlyReader)) {
@@@ -66,7 -66,7 +66,7 @@@
r2.close();
dir1.close();
}
--
++
// open non-readOnly reader1, clone to non-readOnly
// reader2, make sure we can change reader1
public void testCloneWriteToOrig() throws Exception {
@@@ -82,7 -82,7 +82,7 @@@
r2.close();
dir1.close();
}
--
++
// open non-readOnly reader1, clone to non-readOnly
// reader2, make sure we can change reader2
public void testCloneWriteToClone() throws Exception {
@@@ -104,7 -104,7 +104,7 @@@
dir1.close();
}
--
++
// create single-segment index, open non-readOnly
// SegmentReader, add docs, reopen to multireader, then do
// delete
@@@ -115,7 -115,7 +115,7 @@@
IndexReader reader1 = IndexReader.open(dir1, false);
TestIndexReaderReopen.modifyIndex(5, dir1);
--
++
IndexReader reader2 = reader1.reopen();
assertTrue(reader1 != reader2);
@@@ -207,7 -207,7 +207,7 @@@
reader2.close();
dir1.close();
}
--
++
private static boolean deleteWorked(int doc, IndexReader r) {
boolean exception = false;
try {
@@@ -218,11 -218,11 +218,11 @@@
}
return !exception;
}
--
++
public void testCloneReadOnlyDirectoryReader() throws Exception {
- final Directory dir1 = new MockRAMDirectory();
+ final Directory dir1 = newDirectory();
- TestIndexReaderReopen.createIndex(dir1, true);
+ TestIndexReaderReopen.createIndex(random, dir1, true);
IndexReader reader = IndexReader.open(dir1, false);
IndexReader readOnlyReader = reader.clone(true);
if (!isReadOnly(readOnlyReader)) {
@@@ -264,7 -267,7 +267,7 @@@
* are not the same on each reader 5. Verify the doc deleted is only in the
* cloned reader 6. Try to delete a document in the original reader, an
* exception should be thrown
-- *
++ *
* @param r1 IndexReader to perform tests on
* @throws Exception
*/
@@@ -317,11 -321,11 +321,11 @@@
// need to test norms?
dir1.close();
}
--
++
public void testSegmentReaderCloseReferencing() throws Exception {
- final Directory dir1 = new MockRAMDirectory();
- TestIndexReaderReopen.createIndex(dir1, false);
- SegmentReader origSegmentReader = SegmentReader.getOnlySegmentReader(dir1);
+ final Directory dir1 = newDirectory();
+ TestIndexReaderReopen.createIndex(random, dir1, false);
+ SegmentReader origSegmentReader = getOnlySegmentReader(IndexReader.open(dir1, false));
origSegmentReader.deleteDocument(1);
origSegmentReader.setNorm(4, "field1", 0.5f);
@@@ -336,13 -340,13 +340,13 @@@
clonedSegmentReader.close();
dir1.close();
}
--
++
public void testSegmentReaderDelDocsReferenceCounting() throws Exception {
- final Directory dir1 = new MockRAMDirectory();
- TestIndexReaderReopen.createIndex(dir1, false);
+ final Directory dir1 = newDirectory();
+ TestIndexReaderReopen.createIndex(random, dir1, false);
IndexReader origReader = IndexReader.open(dir1, false);
- SegmentReader origSegmentReader = SegmentReader.getOnlySegmentReader(origReader);
+ SegmentReader origSegmentReader = getOnlySegmentReader(origReader);
// deletedDocsRef should be null because nothing has updated yet
assertNull(origSegmentReader.deletedDocsRef);
@@@ -445,16 -450,16 +450,16 @@@
private void assertDelDocsRefCountEquals(int refCount, SegmentReader reader) {
assertEquals(refCount, reader.deletedDocsRef.get());
}
--
++
public void testCloneSubreaders() throws Exception {
- final Directory dir1 = new MockRAMDirectory();
-
- TestIndexReaderReopen.createIndex(dir1, true);
+ final Directory dir1 = newDirectory();
-
++
+ TestIndexReaderReopen.createIndex(random, dir1, true);
IndexReader reader = IndexReader.open(dir1, false);
reader.deleteDocument(1); // acquire write lock
IndexReader[] subs = reader.getSequentialSubReaders();
assert subs.length > 1;
--
++
IndexReader[] clones = new IndexReader[subs.length];
for (int x=0; x < subs.length; x++) {
clones[x] = (IndexReader) subs[x].clone();
@@@ -474,9 -479,9 +479,9 @@@
IndexReader r2 = r1.clone(false);
r1.deleteDocument(5);
r1.decRef();
--
++
r1.incRef();
--
++
r2.close();
r1.decRef();
r1.close();
diff --cc lucene/src/test/org/apache/lucene/index/TestIndexWriter.java
index 3de1996c5ed,7f84850b4d9..99f7635229f
--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java
@@@ -158,370 -151,7 +151,7 @@@ public class TestIndexWriter extends Lu
writer.addDocument(doc);
}
- /*
- Test: make sure when we run out of disk space or hit
- random IOExceptions in any of the addIndexes(*) calls
- that 1) index is not corrupt (searcher can open/search
- it) and 2) transactional semantics are followed:
- either all or none of the incoming documents were in
- fact added.
- */
- public void testAddIndexOnDiskFull() throws IOException
- {
- int START_COUNT = 57;
- int NUM_DIR = 50;
- int END_COUNT = START_COUNT + NUM_DIR*25;
-
- // Build up a bunch of dirs that have indexes which we
- // will then merge together by calling addIndexes(*):
- Directory[] dirs = new Directory[NUM_DIR];
- long inputDiskUsage = 0;
- for(int i=0;i<NUM_DIR;i++) {
- dirs[i] = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dirs[i], new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- for(int j=0;j<25;j++) {
- addDocWithIndex(writer, 25*i+j);
- }
- writer.close();
- String[] files = dirs[i].listAll();
- for(int j=0;j<files.length;j++) {
- inputDiskUsage += dirs[i].fileLength(files[j]);
- }
- }
-
- // Now, build a starting index that has START_COUNT docs. We
- // will then try to addIndexesNoOptimize into a copy of this:
- RAMDirectory startDir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(startDir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- for(int j=0;j<START_COUNT;j++) {
- addDocWithIndex(writer, j);
- }
- writer.close();
-
- // Make sure starting index seems to be working properly:
- Term searchTerm = new Term("content", "aaa");
- IndexReader reader = IndexReader.open(startDir, true);
- assertEquals("first docFreq", 57, reader.docFreq(searchTerm));
-
- IndexSearcher searcher = new IndexSearcher(reader);
- ScoreDoc[] hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs;
- assertEquals("first number of hits", 57, hits.length);
- searcher.close();
- reader.close();
-
- // Iterate with larger and larger amounts of free
- // disk space. With little free disk space,
- // addIndexes will certainly run out of space &
- // fail. Verify that when this happens, index is
- // not corrupt and index in fact has added no
- // documents. Then, we increase disk space by 2000
- // bytes each iteration. At some point there is
- // enough free disk space and addIndexes should
- // succeed and index should show all documents were
- // added.
-
- // String[] files = startDir.listAll();
- long diskUsage = startDir.sizeInBytes();
-
- long startDiskUsage = 0;
- String[] files = startDir.listAll();
- for(int i=0;i<files.length;i++) {
- startDiskUsage += startDir.fileLength(files[i]);
- }
-
- for(int iter=0;iter<3;iter++) {
-
- if (VERBOSE)
- System.out.println("TEST: iter=" + iter);
-
- // Start with 100 bytes more than we are currently using:
- long diskFree = diskUsage+100;
-
- int method = iter;
-
- boolean success = false;
- boolean done = false;
-
- String methodName;
- if (0 == method) {
- methodName = "addIndexes(Directory[]) + optimize()";
- } else if (1 == method) {
- methodName = "addIndexes(IndexReader[])";
- } else {
- methodName = "addIndexes(Directory[])";
- }
-
- while(!done) {
-
- // Make a new dir that will enforce disk usage:
- MockRAMDirectory dir = new MockRAMDirectory(startDir);
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setOpenMode(OpenMode.APPEND));
- IOException err = null;
-
- MergeScheduler ms = writer.getConfig().getMergeScheduler();
- for(int x=0;x<2;x++) {
- if (ms instanceof ConcurrentMergeScheduler)
- // This test intentionally produces exceptions
- // in the threads that CMS launches; we don't
- // want to pollute test output with these.
- if (0 == x)
- ((ConcurrentMergeScheduler) ms).setSuppressExceptions();
- else
- ((ConcurrentMergeScheduler) ms).clearSuppressExceptions();
-
- // Two loops: first time, limit disk space &
- // throw random IOExceptions; second time, no
- // disk space limit:
-
- double rate = 0.05;
- double diskRatio = ((double) diskFree)/diskUsage;
- long thisDiskFree;
-
- String testName = null;
-
- if (0 == x) {
- thisDiskFree = diskFree;
- if (diskRatio >= 2.0) {
- rate /= 2;
- }
- if (diskRatio >= 4.0) {
- rate /= 2;
- }
- if (diskRatio >= 6.0) {
- rate = 0.0;
- }
- if (VERBOSE)
- testName = "disk full test " + methodName + " with disk full at " + diskFree + " bytes";
- } else {
- thisDiskFree = 0;
- rate = 0.0;
- if (VERBOSE)
- testName = "disk full test " + methodName + " with unlimited disk space";
- }
-
- if (VERBOSE)
- System.out.println("\ncycle: " + testName);
-
- dir.setMaxSizeInBytes(thisDiskFree);
- dir.setRandomIOExceptionRate(rate, diskFree);
-
- try {
-
- if (0 == method) {
- writer.addIndexes(dirs);
- writer.optimize();
- } else if (1 == method) {
- IndexReader readers[] = new IndexReader[dirs.length];
- for(int i=0;i<dirs.length;i++) {
- readers[i] = IndexReader.open(dirs[i], true);
- }
- try {
- writer.addIndexes(readers);
- } finally {
- for(int i=0;i<dirs.length;i++) {
- readers[i].close();
- }
- }
- } else {
- writer.addIndexes(dirs);
- }
-
- success = true;
- if (VERBOSE) {
- System.out.println(" success!");
- }
-
- if (0 == x) {
- done = true;
- }
-
- } catch (IOException e) {
- success = false;
- err = e;
- if (VERBOSE) {
- System.out.println(" hit IOException: " + e);
- e.printStackTrace(System.out);
- }
-
- if (1 == x) {
- e.printStackTrace(System.out);
- fail(methodName + " hit IOException after disk space was freed up");
- }
- }
-
- // Make sure all threads from
- // ConcurrentMergeScheduler are done
- _TestUtil.syncConcurrentMerges(writer);
-
- if (VERBOSE) {
- System.out.println(" now test readers");
- }
-
- // Finally, verify index is not corrupt, and, if
- // we succeeded, we see all docs added, and if we
- // failed, we see either all docs or no docs added
- // (transactional semantics):
- try {
- reader = IndexReader.open(dir, true);
- } catch (IOException e) {
- e.printStackTrace(System.out);
- fail(testName + ": exception when creating IndexReader: " + e);
- }
- int result = reader.docFreq(searchTerm);
- if (success) {
- if (result != START_COUNT) {
- fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT);
- }
- } else {
- // On hitting exception we still may have added
- // all docs:
- if (result != START_COUNT && result != END_COUNT) {
- err.printStackTrace(System.out);
- fail(testName + ": method did throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT + " or " + END_COUNT);
- }
- }
-
- searcher = new IndexSearcher(reader);
- try {
- hits = searcher.search(new TermQuery(searchTerm), null, END_COUNT).scoreDocs;
- } catch (IOException e) {
- e.printStackTrace(System.out);
- fail(testName + ": exception when searching: " + e);
- }
- int result2 = hits.length;
- if (success) {
- if (result2 != result) {
- fail(testName + ": method did not throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result);
- }
- } else {
- // On hitting exception we still may have added
- // all docs:
- if (result2 != result) {
- err.printStackTrace(System.out);
- fail(testName + ": method did throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result);
- }
- }
-
- searcher.close();
- reader.close();
- if (VERBOSE) {
- System.out.println(" count is " + result);
- }
-
- if (done || result == END_COUNT) {
- break;
- }
- }
-
- if (VERBOSE) {
- System.out.println(" start disk = " + startDiskUsage + "; input disk = " + inputDiskUsage + "; max used = " + dir.getMaxUsedSizeInBytes());
- }
-
- if (done) {
- // Javadocs state that temp free Directory space
- // required is at most 2X total input size of
- // indices so let's make sure:
- assertTrue("max free Directory space required exceeded 1X the total input index sizes during " + methodName +
- ": max temp usage = " + (dir.getMaxUsedSizeInBytes()-startDiskUsage) + " bytes; " +
- "starting disk usage = " + startDiskUsage + " bytes; " +
- "input index disk usage = " + inputDiskUsage + " bytes",
- (dir.getMaxUsedSizeInBytes()-startDiskUsage) < 2*(startDiskUsage + inputDiskUsage));
- }
-
- // Make sure we don't hit disk full during close below:
- dir.setMaxSizeInBytes(0);
- dir.setRandomIOExceptionRate(0.0, 0);
-
- writer.close();
-
- // Wait for all BG threads to finish else
- // dir.close() will throw IOException because
- // there are still open files
- _TestUtil.syncConcurrentMerges(ms);
-
- dir.close();
-
- // Try again with 5000 more bytes of free space:
- diskFree += 5000;
- }
- }
-
- startDir.close();
- }
-
- /*
- * Make sure IndexWriter cleans up on hitting a disk
- * full exception in addDocument.
- */
- public void testAddDocumentOnDiskFull() throws IOException {
-
- for(int pass=0;pass<2;pass++) {
- if (VERBOSE)
- System.out.println("TEST: pass=" + pass);
- boolean doAbort = pass == 1;
- long diskFree = 200;
- while(true) {
- if (VERBOSE)
- System.out.println("TEST: cycle: diskFree=" + diskFree);
- MockRAMDirectory dir = new MockRAMDirectory();
- dir.setMaxSizeInBytes(diskFree);
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
-
- MergeScheduler ms = writer.getConfig().getMergeScheduler();
- if (ms instanceof ConcurrentMergeScheduler)
- // This test intentionally produces exceptions
- // in the threads that CMS launches; we don't
- // want to pollute test output with these.
- ((ConcurrentMergeScheduler) ms).setSuppressExceptions();
-
- boolean hitError = false;
- try {
- for(int i=0;i<200;i++) {
- addDoc(writer);
- }
- } catch (IOException e) {
- if (VERBOSE) {
- System.out.println("TEST: exception on addDoc");
- e.printStackTrace(System.out);
- }
- hitError = true;
- }
-
- if (hitError) {
- if (doAbort) {
- writer.rollback();
- } else {
- try {
- writer.close();
- } catch (IOException e) {
- if (VERBOSE) {
- System.out.println("TEST: exception on close");
- e.printStackTrace(System.out);
- }
- dir.setMaxSizeInBytes(0);
- writer.close();
- }
- }
-
- _TestUtil.syncConcurrentMerges(ms);
-
- assertNoUnreferencedFiles(dir, "after disk full during addDocument");
-
- // Make sure reader can open the index:
- IndexReader.open(dir, true).close();
-
- dir.close();
-
+
- // Now try again w/ more space:
- diskFree += 500;
- } else {
- _TestUtil.syncConcurrentMerges(writer);
- dir.close();
- break;
- }
- }
- }
- }
public static void assertNoUnreferencedFiles(Directory dir, String message) throws IOException {
String[] startFiles = dir.listAll();
@@@ -625,9 -259,13 +259,13 @@@
* required.
*/
public void testOptimizeTempSpaceUsage() throws IOException {
-
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
+
+ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10));
+ if (VERBOSE) {
+ System.out.println("TEST: config1=" + writer.getConfig());
+ }
-
++
for(int j=0;j<500;j++) {
addDocWithIndex(writer, j);
}
@@@ -665,142 -319,30 +319,30 @@@
// reader holds it open (this fails pre lock-less
// commits on windows):
public void testCreateWithReader() throws IOException {
- File indexDir = _TestUtil.getTempDir("lucenetestindexwriter");
-
- try {
- Directory dir = FSDirectory.open(indexDir);
-
- // add one document & close writer
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- addDoc(writer);
- writer.close();
-
- // now open reader:
- IndexReader reader = IndexReader.open(dir, true);
- assertEquals("should be one document", reader.numDocs(), 1);
+ Directory dir = newDirectory();
- // now open index for create:
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setOpenMode(OpenMode.CREATE));
- assertEquals("should be zero documents", writer.maxDoc(), 0);
- addDoc(writer);
- writer.close();
-
- assertEquals("should be one document", reader.numDocs(), 1);
- IndexReader reader2 = IndexReader.open(dir, true);
- assertEquals("should be one document", reader2.numDocs(), 1);
- reader.close();
- reader2.close();
- } finally {
- rmDir(indexDir);
- }
- }
-
- // Simulate a writer that crashed while writing segments
- // file: make sure we can still open the index (ie,
- // gracefully fallback to the previous segments file),
- // and that we can add to the index:
- public void testSimulatedCrashedWriter() throws IOException {
- Directory dir = new RAMDirectory();
-
- IndexWriter writer = null;
-
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
-
- // add 100 documents
- for (int i = 0; i < 100; i++) {
- addDoc(writer);
- }
-
- // close
- writer.close();
-
- long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
- assertTrue("segment generation should be > 0 but got " + gen, gen > 0);
-
- // Make the next segments file, with last byte
- // missing, to simulate a writer that crashed while
- // writing segments file:
- String fileNameIn = SegmentInfos.getCurrentSegmentFileName(dir);
- String fileNameOut = IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS,
- "",
- 1+gen);
- IndexInput in = dir.openInput(fileNameIn);
- IndexOutput out = dir.createOutput(fileNameOut);
- long length = in.length();
- for(int i=0;i<length-1;i++) {
- out.writeByte(in.readByte());
- }
- in.close();
- out.close();
-
- IndexReader reader = null;
- try {
- reader = IndexReader.open(dir, true);
- } catch (Exception e) {
- fail("reader failed to open on a crashed index");
- }
- reader.close();
-
- try {
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setOpenMode(OpenMode.CREATE));
- } catch (Exception e) {
- e.printStackTrace(System.out);
- fail("writer failed to open on a crashed index");
- }
-
- // add 100 documents
- for (int i = 0; i < 100; i++) {
- addDoc(writer);
- }
-
- // close
- writer.close();
- }
-
- // Simulate a corrupt index by removing last byte of
- // latest segments file and make sure we get an
- // IOException trying to open the index:
- public void testSimulatedCorruptIndex1() throws IOException {
- Directory dir = new RAMDirectory();
-
- IndexWriter writer = null;
-
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
+ // add one document & close writer
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()));
+ addDoc(writer);
+ writer.close();
- // add 100 documents
- for (int i = 0; i < 100; i++) {
- addDoc(writer);
- }
+ // now open reader:
+ IndexReader reader = IndexReader.open(dir, true);
+ assertEquals("should be one document", reader.numDocs(), 1);
- // close
- writer.close();
+ // now open index for create:
+ writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setOpenMode(OpenMode.CREATE));
+ assertEquals("should be zero documents", writer.maxDoc(), 0);
+ addDoc(writer);
+ writer.close();
- long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
- assertTrue("segment generation should be > 0 but got " + gen, gen > 0);
-
- String fileNameIn = SegmentInfos.getCurrentSegmentFileName(dir);
- String fileNameOut = IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS,
- "",
- 1+gen);
- IndexInput in = dir.openInput(fileNameIn);
- IndexOutput out = dir.createOutput(fileNameOut);
- long length = in.length();
- for(int i=0;i<length-1;i++) {
- out.writeByte(in.readByte());
- }
- in.close();
- out.close();
- dir.deleteFile(fileNameIn);
+ assertEquals("should be one document", reader.numDocs(), 1);
+ IndexReader reader2 = IndexReader.open(dir, true);
+ assertEquals("should be one document", reader2.numDocs(), 1);
+ reader.close();
+ reader2.close();
-
+
- IndexReader reader = null;
- try {
- reader = IndexReader.open(dir, true);
- fail("reader did not hit IOException on opening a corrupt index");
- } catch (Exception e) {
- }
- if (reader != null) {
- reader.close();
- }
+ dir.close();
}
public void testChangesAfterClose() throws IOException {
@@@ -868,14 -370,14 +370,14 @@@
* these docs until writer is closed.
*/
public void testCommitOnClose() throws IOException {
- Directory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- Directory dir = newDirectory();
++ Directory dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()));
for (int i = 0; i < 14; i++) {
addDoc(writer);
}
writer.close();
-- Term searchTerm = new Term("content", "aaa");
++ Term searchTerm = new Term("content", "aaa");
IndexSearcher searcher = new IndexSearcher(dir, false);
ScoreDoc[] hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs;
assertEquals("first number of hits", 14, hits.length);
@@@ -914,14 -418,14 +418,14 @@@
* and add docs to it.
*/
public void testCommitOnCloseAbort() throws IOException {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10));
- MockDirectoryWrapper dir = newDirectory();
++ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10));
for (int i = 0; i < 14; i++) {
addDoc(writer);
}
writer.close();
-- Term searchTerm = new Term("content", "aaa");
++ Term searchTerm = new Term("content", "aaa");
IndexSearcher searcher = new IndexSearcher(dir, false);
ScoreDoc[] hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs;
assertEquals("first number of hits", 14, hits.length);
@@@ -949,10 -453,10 +453,10 @@@
hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs;
assertEquals("saw changes after writer.abort", 14, hits.length);
searcher.close();
--
++
// Now make sure we can re-open the index, add docs,
// and all is good:
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer())
+ writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer())
.setOpenMode(OpenMode.APPEND).setMaxBufferedDocs(10));
// On abort, writer in fact may write to the same
@@@ -986,8 -490,14 +490,14 @@@
* measure max temp disk space used.
*/
public void testCommitOnCloseDiskUsage() throws IOException {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- MockDirectoryWrapper dir = newDirectory();
++ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMaxBufferedDocs(10).
+ setReaderPooling(false).
+ setMergePolicy(newLogMergePolicy(10))
+ );
for(int j=0;j<30;j++) {
addDocWithIndex(writer, j);
}
@@@ -1029,8 -548,17 +548,17 @@@
* and close().
*/
public void testCommitOnCloseOptimize() throws IOException {
- RAMDirectory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10));
- MockDirectoryWrapper dir = newDirectory();
++ MockDirectoryWrapper dir = newDirectory();
+ // Must disable throwing exc on double-write: this
+ // test uses IW.rollback which easily results in
+ // writing to same file more than once
+ dir.setPreventDoubleWrite(false);
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMaxBufferedDocs(10).
+ setMergePolicy(newLogMergePolicy(10))
+ );
for(int j=0;j<17;j++) {
addDocWithIndex(writer, j);
}
@@@ -1072,8 -615,8 +615,8 @@@
}
public void testIndexNoDocuments() throws IOException {
- RAMDirectory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- MockDirectoryWrapper dir = newDirectory();
++ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()));
writer.commit();
writer.close();
@@@ -1093,16 -637,16 +637,16 @@@
}
public void testManyFields() throws IOException {
- RAMDirectory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10));
- MockDirectoryWrapper dir = newDirectory();
++ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10));
for(int j=0;j<100;j++) {
Document doc = new Document();
- doc.add(new Field("a"+j, "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));
- doc.add(new Field("b"+j, "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));
- doc.add(new Field("c"+j, "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));
- doc.add(new Field("d"+j, "aaa", Field.Store.YES, Field.Index.ANALYZED));
- doc.add(new Field("e"+j, "aaa", Field.Store.YES, Field.Index.ANALYZED));
- doc.add(new Field("f"+j, "aaa", Field.Store.YES, Field.Index.ANALYZED));
+ doc.add(newField("a"+j, "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));
+ doc.add(newField("b"+j, "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));
+ doc.add(newField("c"+j, "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));
+ doc.add(newField("d"+j, "aaa", Field.Store.YES, Field.Index.ANALYZED));
+ doc.add(newField("e"+j, "aaa", Field.Store.YES, Field.Index.ANALYZED));
+ doc.add(newField("f"+j, "aaa", Field.Store.YES, Field.Index.ANALYZED));
writer.addDocument(doc);
}
writer.close();
@@@ -1123,8 -667,13 +667,13 @@@
}
public void testSmallRAMBuffer() throws IOException {
- RAMDirectory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setRAMBufferSizeMB(0.000001));
- MockDirectoryWrapper dir = newDirectory();
++ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setRAMBufferSizeMB(0.000001).
+ setMergePolicy(newLogMergePolicy(10))
+ );
int lastNumFile = dir.listAll().length;
for(int j=0;j<9;j++) {
Document doc = new Document();
@@@ -1140,135 -689,9 +689,9 @@@
dir.close();
}
- /**
- * Make sure it's OK to change RAM buffer size and // maxBufferedDocs in a
- * write session
- *
- * @deprecated after all the setters on IW go away (4.0), this test can be
- * removed because changing ram buffer settings during a write
- * session won't be possible.
- */
- public void testChangingRAMBuffer() throws IOException {
- RAMDirectory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10).setRAMBufferSizeMB(
- IndexWriterConfig.DISABLE_AUTO_FLUSH));
-
- int lastFlushCount = -1;
- for(int j=1;j<52;j++) {
- Document doc = new Document();
- doc.add(new Field("field", "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));
- writer.addDocument(doc);
- _TestUtil.syncConcurrentMerges(writer);
- int flushCount = writer.getFlushCount();
- if (j == 1)
- lastFlushCount = flushCount;
- else if (j < 10)
- // No new files should be created
- assertEquals(flushCount, lastFlushCount);
- else if (10 == j) {
- assertTrue(flushCount > lastFlushCount);
- lastFlushCount = flushCount;
- writer.setRAMBufferSizeMB(0.000001);
- writer.setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
- } else if (j < 20) {
- assertTrue(flushCount > lastFlushCount);
- lastFlushCount = flushCount;
- } else if (20 == j) {
- writer.setRAMBufferSizeMB(16);
- writer.setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
- lastFlushCount = flushCount;
- } else if (j < 30) {
- assertEquals(flushCount, lastFlushCount);
- } else if (30 == j) {
- writer.setRAMBufferSizeMB(0.000001);
- writer.setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
- } else if (j < 40) {
- assertTrue(flushCount> lastFlushCount);
- lastFlushCount = flushCount;
- } else if (40 == j) {
- writer.setMaxBufferedDocs(10);
- writer.setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);
- lastFlushCount = flushCount;
- } else if (j < 50) {
- assertEquals(flushCount, lastFlushCount);
- writer.setMaxBufferedDocs(10);
- writer.setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);
- } else if (50 == j) {
- assertTrue(flushCount > lastFlushCount);
- }
- }
- writer.close();
- dir.close();
- }
-
- /**
- * @deprecated after setters on IW go away, this test can be deleted because
- * changing those settings on IW won't be possible.
- */
- public void testChangingRAMBuffer2() throws IOException {
- RAMDirectory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10).setMaxBufferedDeleteTerms(
- 10).setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH));
-
- for(int j=1;j<52;j++) {
- Document doc = new Document();
- doc.add(new Field("field", "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));
- writer.addDocument(doc);
- }
-
- int lastFlushCount = -1;
- for(int j=1;j<52;j++) {
- writer.deleteDocuments(new Term("field", "aaa" + j));
- _TestUtil.syncConcurrentMerges(writer);
- int flushCount = writer.getFlushCount();
- if (j == 1)
- lastFlushCount = flushCount;
- else if (j < 10) {
- // No new files should be created
- assertEquals(flushCount, lastFlushCount);
- } else if (10 == j) {
- assertTrue(flushCount > lastFlushCount);
- lastFlushCount = flushCount;
- writer.setRAMBufferSizeMB(0.000001);
- writer.setMaxBufferedDeleteTerms(1);
- } else if (j < 20) {
- assertTrue(flushCount > lastFlushCount);
- lastFlushCount = flushCount;
- } else if (20 == j) {
- writer.setRAMBufferSizeMB(16);
- writer.setMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH);
- lastFlushCount = flushCount;
- } else if (j < 30) {
- assertEquals(flushCount, lastFlushCount);
- } else if (30 == j) {
- writer.setRAMBufferSizeMB(0.000001);
- writer.setMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH);
- writer.setMaxBufferedDeleteTerms(1);
- } else if (j < 40) {
- assertTrue(flushCount> lastFlushCount);
- lastFlushCount = flushCount;
- } else if (40 == j) {
- writer.setMaxBufferedDeleteTerms(10);
- writer.setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);
- lastFlushCount = flushCount;
- } else if (j < 50) {
- assertEquals(flushCount, lastFlushCount);
- writer.setMaxBufferedDeleteTerms(10);
- writer.setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);
- } else if (50 == j) {
- assertTrue(flushCount > lastFlushCount);
- }
- }
- writer.close();
- dir.close();
- }
-
public void testDiverseDocs() throws IOException {
- RAMDirectory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setRAMBufferSizeMB(0.5));
- Random rand = newRandom();
- MockDirectoryWrapper dir = newDirectory();
++ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setRAMBufferSizeMB(0.5));
for(int i=0;i<3;i++) {
// First, docs where every term is unique (heavy on
// Posting instances)
@@@ -1314,12 -737,12 +737,12 @@@
}
public void testEnablingNorms() throws IOException {
- RAMDirectory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10));
- MockDirectoryWrapper dir = newDirectory();
++ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10));
// Enable norms for only 1 doc, pre flush
for(int j=0;j<10;j++) {
Document doc = new Document();
- Field f = new Field("field", "aaa", Field.Store.YES, Field.Index.ANALYZED);
- Field f = newField("field", "aaa", Field.Store.YES, Field.Index.ANALYZED);
++ Field f = newField("field", "aaa", Field.Store.YES, Field.Index.ANALYZED);
if (j != 8) {
f.setOmitNorms(true);
}
@@@ -1340,7 -763,7 +763,7 @@@
// Enable norms for only 1 doc, post flush
for(int j=0;j<27;j++) {
Document doc = new Document();
- Field f = new Field("field", "aaa", Field.Store.YES, Field.Index.ANALYZED);
- Field f = newField("field", "aaa", Field.Store.YES, Field.Index.ANALYZED);
++ Field f = newField("field", "aaa", Field.Store.YES, Field.Index.ANALYZED);
if (j != 26) {
f.setOmitNorms(true);
}
@@@ -1360,8 -783,8 +783,8 @@@
}
public void testHighFreqTerm() throws IOException {
- RAMDirectory dir = new RAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
- MockDirectoryWrapper dir = newDirectory();
++ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxFieldLength(100000000).setRAMBufferSizeMB(0.01));
// Massive doc that has 128 K a's
StringBuilder b = new StringBuilder(1024*1024);
@@@ -1409,15 -833,15 +833,15 @@@
return myLockFactory.makeLock(name);
}
}
--
- Directory dir = new MyRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
++
+ Directory dir = new MyRAMDirectory(new RAMDirectory());
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()));
for (int i = 0; i < 100; i++) {
addDoc(writer);
}
writer.close();
-- Term searchTerm = new Term("content", "aaa");
++ Term searchTerm = new Term("content", "aaa");
IndexSearcher searcher = new IndexSearcher(dir, false);
ScoreDoc[] hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs;
assertEquals("did not get right number of hits", 100, hits.length);
@@@ -1500,7 -938,7 +938,7 @@@
infos.read(dir);
assertEquals(2, infos.size());
}
-- }
++ }
dir.close();
}
@@@ -1523,71 -951,13 +951,13 @@@
*
*/
public void testBadSegment() throws IOException {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(
+ Directory dir = newDirectory();
+ IndexWriter iw = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()));
--
- Document document = new Document();
- document.add(new Field("tvtest", "", Store.NO, Index.ANALYZED, TermVector.YES));
- iw.addDocument(document);
- iw.close();
- dir.close();
- }
+
- // LUCENE-1008
- public void testNoTermVectorAfterTermVector() throws IOException {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()));
Document document = new Document();
- document.add(new Field("tvtest", "a b c", Field.Store.NO, Field.Index.ANALYZED,
- Field.TermVector.YES));
- iw.addDocument(document);
- document = new Document();
- document.add(new Field("tvtest", "x y z", Field.Store.NO, Field.Index.ANALYZED,
- Field.TermVector.NO));
- iw.addDocument(document);
- // Make first segment
- iw.commit();
-
- document.add(new Field("tvtest", "a b c", Field.Store.NO, Field.Index.ANALYZED,
- Field.TermVector.YES));
- iw.addDocument(document);
- // Make 2nd segment
- iw.commit();
-
- iw.optimize();
- iw.close();
- dir.close();
- }
-
- // LUCENE-1010
- public void testNoTermVectorAfterTermVectorMerge() throws IOException {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()));
- Document document = new Document();
- document.add(new Field("tvtest", "a b c", Field.Store.NO, Field.Index.ANALYZED,
- Field.TermVector.YES));
- iw.addDocument(document);
- iw.commit();
-
- document = new Document();
- document.add(new Field("tvtest", "x y z", Field.Store.NO, Field.Index.ANALYZED,
- Field.TermVector.NO));
- iw.addDocument(document);
- // Make first segment
- iw.commit();
-
- iw.optimize();
-
- document.add(new Field("tvtest", "a b c", Field.Store.NO, Field.Index.ANALYZED,
- Field.TermVector.YES));
+ document.add(newField("tvtest", "", Store.NO, Index.ANALYZED, TermVector.YES));
iw.addDocument(document);
- // Make 2nd segment
- iw.commit();
- iw.optimize();
-
iw.close();
dir.close();
}
@@@ -2571,263 -1196,45 +1196,45 @@@
Term t = new Term("field", "x");
assertEquals(1, reader.docFreq(t));
reader.close();
- dir.close();
- }
-
- // LUCENE-1044: Simulate checksum error in segments_N
- public void testSegmentsChecksumError() throws IOException {
- Directory dir = new MockRAMDirectory();
-
- IndexWriter writer = null;
-
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
-
- // add 100 documents
- for (int i = 0; i < 100; i++) {
- addDoc(writer);
- }
-
- // close
- writer.close();
-
- long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
- assertTrue("segment generation should be > 0 but got " + gen, gen > 0);
-
- final String segmentsFileName = SegmentInfos.getCurrentSegmentFileName(dir);
- IndexInput in = dir.openInput(segmentsFileName);
- IndexOutput out = dir.createOutput(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", 1+gen));
- out.copyBytes(in, in.length()-1);
- byte b = in.readByte();
- out.writeByte((byte) (1+b));
- out.close();
- in.close();
-
- IndexReader reader = null;
- try {
- reader = IndexReader.open(dir, true);
- } catch (IOException e) {
- e.printStackTrace(System.out);
- fail("segmentInfos failed to retry fallback to correct segments_N file");
- }
- reader.close();
- }
-
- // LUCENE-1044: test writer.commit() when ac=false
- public void testForceCommit() throws IOException {
- Directory dir = new MockRAMDirectory();
-
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer())
- .setMaxBufferedDocs(2));
- ((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(5);
- writer.commit();
-
- for (int i = 0; i < 23; i++)
- addDoc(writer);
-
- IndexReader reader = IndexReader.open(dir, true);
- assertEquals(0, reader.numDocs());
- writer.commit();
- IndexReader reader2 = reader.reopen();
- assertEquals(0, reader.numDocs());
- assertEquals(23, reader2.numDocs());
- reader.close();
-
- for (int i = 0; i < 17; i++)
- addDoc(writer);
- assertEquals(23, reader2.numDocs());
- reader2.close();
- reader = IndexReader.open(dir, true);
- assertEquals(23, reader.numDocs());
- reader.close();
- writer.commit();
-
- reader = IndexReader.open(dir, true);
- assertEquals(40, reader.numDocs());
- reader.close();
- writer.close();
- dir.close();
- }
-
- // Throws IOException during MockRAMDirectory.sync
- private static class FailOnlyInSync extends MockRAMDirectory.Failure {
- boolean didFail;
- @Override
- public void eval(MockRAMDirectory dir) throws IOException {
- if (doFail) {
- StackTraceElement[] trace = new Exception().getStackTrace();
- for (int i = 0; i < trace.length; i++) {
- if (doFail && "org.apache.lucene.store.MockRAMDirectory".equals(trace[i].getClassName()) && "sync".equals(trace[i].getMethodName())) {
- didFail = true;
- throw new IOException("now failing on purpose during sync");
- }
- }
- }
- }
- }
-
- // LUCENE-1044: test exception during sync
- public void testExceptionDuringSync() throws IOException {
- MockRAMDirectory dir = new MockRAMDirectory();
- FailOnlyInSync failure = new FailOnlyInSync();
- dir.failOn(failure);
-
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2));
- failure.setDoFail();
- ((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(5);
-
- for (int i = 0; i < 23; i++) {
- addDoc(writer);
- if ((i-1)%2 == 0) {
- try {
- writer.commit();
- } catch (IOException ioe) {
- // expected
- }
- }
- }
-
- ((ConcurrentMergeScheduler) writer.getConfig().getMergeScheduler()).sync();
- assertTrue(failure.didFail);
- failure.clearDoFail();
- writer.close();
-
- IndexReader reader = IndexReader.open(dir, true);
- assertEquals(23, reader.numDocs());
- reader.close();
- dir.close();
- }
-
- // LUCENE-1168
- public void testTermVectorCorruption() throws IOException {
-
- Directory dir = new MockRAMDirectory();
- for(int iter=0;iter<2;iter++) {
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer())
- .setMaxBufferedDocs(2).setRAMBufferSizeMB(
- IndexWriterConfig.DISABLE_AUTO_FLUSH).setMergeScheduler(
- new SerialMergeScheduler()).setMergePolicy(
- new LogDocMergePolicy()));
-
- Document document = new Document();
-
- Field storedField = new Field("stored", "stored", Field.Store.YES,
- Field.Index.NO);
- document.add(storedField);
- writer.addDocument(document);
- writer.addDocument(document);
-
- document = new Document();
- document.add(storedField);
- Field termVectorField = new Field("termVector", "termVector",
- Field.Store.NO, Field.Index.NOT_ANALYZED,
- Field.TermVector.WITH_POSITIONS_OFFSETS);
-
- document.add(termVectorField);
- writer.addDocument(document);
- writer.optimize();
- writer.close();
-
- IndexReader reader = IndexReader.open(dir, true);
- for(int i=0;i<reader.numDocs();i++) {
- reader.document(i);
- reader.getTermFreqVectors(i);
- }
- reader.close();
-
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT,
- new MockAnalyzer()).setMaxBufferedDocs(2)
- .setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)
- .setMergeScheduler(new SerialMergeScheduler()).setMergePolicy(
- new LogDocMergePolicy()));
-
- Directory[] indexDirs = {new MockRAMDirectory(dir)};
- writer.addIndexes(indexDirs);
- writer.optimize();
- writer.close();
- }
- dir.close();
- }
-
- // LUCENE-1168
- public void testTermVectorCorruption2() throws IOException {
- Directory dir = new MockRAMDirectory();
- for(int iter=0;iter<2;iter++) {
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer())
- .setMaxBufferedDocs(2).setRAMBufferSizeMB(
- IndexWriterConfig.DISABLE_AUTO_FLUSH).setMergeScheduler(
- new SerialMergeScheduler()).setMergePolicy(
- new LogDocMergePolicy()));
-
- Document document = new Document();
-
- Field storedField = new Field("stored", "stored", Field.Store.YES,
- Field.Index.NO);
- document.add(storedField);
- writer.addDocument(document);
- writer.addDocument(document);
-
- document = new Document();
- document.add(storedField);
- Field termVectorField = new Field("termVector", "termVector",
- Field.Store.NO, Field.Index.NOT_ANALYZED,
- Field.TermVector.WITH_POSITIONS_OFFSETS);
- document.add(termVectorField);
- writer.addDocument(document);
- writer.optimize();
- writer.close();
-
- IndexReader reader = IndexReader.open(dir, true);
- assertTrue(reader.getTermFreqVectors(0)==null);
- assertTrue(reader.getTermFreqVectors(1)==null);
- assertTrue(reader.getTermFreqVectors(2)!=null);
- reader.close();
- }
- dir.close();
- }
-
- // LUCENE-1168
- public void testTermVectorCorruption3() throws IOException {
- Directory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer())
- .setMaxBufferedDocs(2).setRAMBufferSizeMB(
- IndexWriterConfig.DISABLE_AUTO_FLUSH).setMergeScheduler(
- new SerialMergeScheduler()).setMergePolicy(new LogDocMergePolicy()));
-
- Document document = new Document();
-
- document = new Document();
- Field storedField = new Field("stored", "stored", Field.Store.YES,
- Field.Index.NO);
- document.add(storedField);
- Field termVectorField = new Field("termVector", "termVector",
- Field.Store.NO, Field.Index.NOT_ANALYZED,
- Field.TermVector.WITH_POSITIONS_OFFSETS);
- document.add(termVectorField);
- for(int i=0;i<10;i++)
- writer.addDocument(document);
- writer.close();
+ dir.close();
+ }
- writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT,
- new MockAnalyzer()).setMaxBufferedDocs(2)
- .setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)
- .setMergeScheduler(new SerialMergeScheduler()).setMergePolicy(
- new LogDocMergePolicy()));
- for(int i=0;i<6;i++)
- writer.addDocument(document);
+ // LUCENE-1044: test writer.commit() when ac=false
+ public void testForceCommit() throws IOException {
+ Directory dir = newDirectory();
+
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMaxBufferedDocs(2).
+ setMergePolicy(newLogMergePolicy(5))
+ );
+ writer.commit();
-
+
- writer.optimize();
- writer.close();
+ for (int i = 0; i < 23; i++)
+ addDoc(writer);
IndexReader reader = IndexReader.open(dir, true);
- for(int i=0;i<10;i++) {
- reader.getTermFreqVectors(i);
- reader.document(i);
- }
+ assertEquals(0, reader.numDocs());
+ writer.commit();
+ IndexReader reader2 = reader.reopen();
+ assertEquals(0, reader.numDocs());
+ assertEquals(23, reader2.numDocs());
reader.close();
+
+ for (int i = 0; i < 17; i++)
+ addDoc(writer);
+ assertEquals(23, reader2.numDocs());
+ reader2.close();
+ reader = IndexReader.open(dir, true);
+ assertEquals(23, reader.numDocs());
+ reader.close();
+ writer.commit();
+
+ reader = IndexReader.open(dir, true);
+ assertEquals(40, reader.numDocs());
+ reader.close();
+ writer.close();
dir.close();
}
@@@ -2857,8 -1264,8 +1264,8 @@@
// LUCENE-325: test expungeDeletes, when 2 singular merges
// are required
public void testExpungeDeletes() throws IOException {
- Directory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
+ Directory dir = newDirectory();
- IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
++ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer())
.setMaxBufferedDocs(2).setRAMBufferSizeMB(
IndexWriterConfig.DISABLE_AUTO_FLUSH));
@@@ -3119,13 -1427,13 +1427,13 @@@
public void doAfterFlush() {
afterWasCalled = true;
}
--
++
@Override
protected void doBeforeFlush() throws IOException {
beforeWasCalled = true;
}
}
--
++
// LUCENE-1222
public void testDoBeforeAfterFlush() throws IOException {
@@@ -3154,58 -1462,8 +1462,8 @@@
dir.close();
}
- private static class FailOnlyInCommit extends MockRAMDirectory.Failure {
-
- boolean fail1, fail2;
- @Override
- public void eval(MockRAMDirectory dir) throws IOException {
- StackTraceElement[] trace = new Exception().getStackTrace();
- boolean isCommit = false;
- boolean isDelete = false;
- for (int i = 0; i < trace.length; i++) {
- if ("org.apache.lucene.index.SegmentInfos".equals(trace[i].getClassName()) && "prepareCommit".equals(trace[i].getMethodName()))
- isCommit = true;
- if ("org.apache.lucene.store.MockRAMDirectory".equals(trace[i].getClassName()) && "deleteFile".equals(trace[i].getMethodName()))
- isDelete = true;
- }
-
- if (isCommit) {
- if (!isDelete) {
- fail1 = true;
- throw new RuntimeException("now fail first");
- } else {
- fail2 = true;
- throw new IOException("now fail during delete");
- }
- }
- }
- }
--
+
- // LUCENE-1214
- public void testExceptionsDuringCommit() throws Throwable {
- MockRAMDirectory dir = new MockRAMDirectory();
- FailOnlyInCommit failure = new FailOnlyInCommit();
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- Document doc = new Document();
- doc.add(new Field("field", "a field", Field.Store.YES,
- Field.Index.ANALYZED));
- w.addDocument(doc);
- dir.failOn(failure);
- try {
- w.close();
- fail();
- } catch (IOException ioe) {
- fail("expected only RuntimeException");
- } catch (RuntimeException re) {
- // Expected
- }
- assertTrue(failure.fail1 && failure.fail2);
- w.rollback();
- dir.close();
- }
-
final String[] utf8Data = new String[] {
// unpaired low surrogate
"ab\udc17cd", "ab\ufffdcd",
@@@ -3275,7 -1533,7 +1533,7 @@@
}
UnicodeUtil.UTF16toUTF8(chars, 0, len, utf8);
--
++
String s1 = new String(chars, 0, len);
String s2 = new String(utf8.bytes, 0, utf8.length, "UTF-8");
assertEquals("codepoint " + ch, s1, s2);
@@@ -3334,7 -1590,7 +1590,7 @@@
expected[i++] = 0xfffd;
expected[i] = buffer[i] = (char) nextInt(0x800, 0xd800);
hasIllegal = true;
-- } else
++ } else
expected[i] = buffer[i] = (char) nextInt(0x800, 0xd800);
} else {
expected[i] = buffer[i] = ' ';
@@@ -3434,10 -1687,10 +1687,10 @@@
final TokenStream tokens = new TokenStream() {
final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);
--
++
final Iterator<String> terms = Arrays.asList("a","b","c").iterator();
boolean first = true;
--
++
@Override
public boolean incrementToken() {
if (!terms.hasNext()) return false;
@@@ -3485,12 -1738,16 +1738,16 @@@
// LUCENE-1274: test writer.prepareCommit()
public void testPrepareCommit() throws IOException {
- Directory dir = new MockRAMDirectory();
-
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2));
- ((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(5);
+ Directory dir = newDirectory();
+
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMaxBufferedDocs(2).
+ setMergePolicy(newLogMergePolicy(5))
+ );
writer.commit();
--
++
for (int i = 0; i < 23; i++)
addDoc(writer);
@@@ -3536,13 -1793,17 +1793,17 @@@
// LUCENE-1274: test writer.prepareCommit()
public void testPrepareCommitRollback() throws IOException {
- MockRAMDirectory dir = new MockRAMDirectory();
+ MockDirectoryWrapper dir = newDirectory();
dir.setPreventDoubleWrite(false);
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2));
- ((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(5);
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMaxBufferedDocs(2).
+ setMergePolicy(newLogMergePolicy(5))
+ );
writer.commit();
--
++
for (int i = 0; i < 23; i++)
addDoc(writer);
@@@ -3919,7 -1870,7 +1870,7 @@@
byte[] b = new byte[50];
for(int i=0;i<50;i++)
b[i] = (byte) (i+77);
--
++
Document doc = new Document();
Field f = new Field("binary", b, 10, 17);
byte[] bx = f.getBinaryValue();
@@@ -3956,15 -1907,15 +1907,15 @@@
// commit(Map) never called for this index
assertEquals(0, r.getCommitUserData().size());
r.close();
--
- w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2));
++
+ w = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2));
for(int j=0;j<17;j++)
addDoc(w);
Map<String,String> data = new HashMap<String,String>();
data.put("label", "test1");
w.commit(data);
w.close();
--
++
assertEquals("test1", IndexReader.getCommitUserData(dir).get("label"));
r = IndexReader.open(dir, true);
@@@ -3976,266 -1927,25 +1927,25 @@@
w.close();
assertEquals("test1", IndexReader.getCommitUserData(dir).get("label"));
--
- dir.close();
- }
-
- public void testOptimizeExceptions() throws IOException {
- RAMDirectory startDir = new MockRAMDirectory();
- IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2);
- ((LogMergePolicy) conf.getMergePolicy()).setMergeFactor(100);
- IndexWriter w = new IndexWriter(startDir, conf);
- for(int i=0;i<27;i++)
- addDoc(w);
- w.close();
-
- for(int i=0;i<200;i++) {
- MockRAMDirectory dir = new MockRAMDirectory(startDir);
- conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer());
- ((ConcurrentMergeScheduler) conf.getMergeScheduler()).setSuppressExceptions();
- w = new IndexWriter(dir, conf);
- dir.setRandomIOExceptionRate(0.5, 100);
- try {
- w.optimize();
- } catch (IOException ioe) {
- if (ioe.getCause() == null)
- fail("optimize threw IOException without root cause");
- }
- w.close();
- dir.close();
- }
- }
-
- // LUCENE-1429
- public void testOutOfMemoryErrorCausesCloseToFail() throws Exception {
-
- final List<Throwable> thrown = new ArrayList<Throwable>();
-
- final IndexWriter writer = new IndexWriter(new MockRAMDirectory(),
- new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer())) {
- @Override
- public void message(final String message) {
- if (message.startsWith("now flush at close") && 0 == thrown.size()) {
- thrown.add(null);
- throw new OutOfMemoryError("fake OOME at " + message);
- }
- }
- };
-
- // need to set an info stream so message is called
- writer.setInfoStream(new PrintStream(new ByteArrayOutputStream()));
- try {
- writer.close();
- fail("OutOfMemoryError expected");
- }
- catch (final OutOfMemoryError expected) {}
-
- // throws IllegalStateEx w/o bug fix
- writer.close();
- }
-
- // LUCENE-1442
- public void testDoubleOffsetCounting() throws Exception {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()));
- Document doc = new Document();
- Field f = new Field("field", "abcd", Field.Store.NO, Field.Index.NOT_ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f);
- doc.add(f);
- Field f2 = new Field("field", "", Field.Store.NO, Field.Index.NOT_ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f2);
- doc.add(f);
- w.addDocument(doc);
- w.close();
-
- IndexReader r = IndexReader.open(dir, true);
- TermVectorOffsetInfo[] termOffsets = ((TermPositionVector) r.getTermFreqVector(0, "field")).getOffsets(0);
-
- // Token "" occurred once
- assertEquals(1, termOffsets.length);
- assertEquals(8, termOffsets[0].getStartOffset());
- assertEquals(8, termOffsets[0].getEndOffset());
-
- // Token "abcd" occurred three times
- termOffsets = ((TermPositionVector) r.getTermFreqVector(0, "field")).getOffsets(1);
- assertEquals(3, termOffsets.length);
- assertEquals(0, termOffsets[0].getStartOffset());
- assertEquals(4, termOffsets[0].getEndOffset());
- assertEquals(4, termOffsets[1].getStartOffset());
- assertEquals(8, termOffsets[1].getEndOffset());
- assertEquals(8, termOffsets[2].getStartOffset());
- assertEquals(12, termOffsets[2].getEndOffset());
- r.close();
- dir.close();
- }
-
- // LUCENE-1442
- public void testDoubleOffsetCounting2() throws Exception {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- Document doc = new Document();
- Field f = new Field("field", "abcd", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f);
- doc.add(f);
- w.addDocument(doc);
- w.close();
-
- IndexReader r = IndexReader.open(dir, true);
- TermVectorOffsetInfo[] termOffsets = ((TermPositionVector) r.getTermFreqVector(0, "field")).getOffsets(0);
- assertEquals(2, termOffsets.length);
- assertEquals(0, termOffsets[0].getStartOffset());
- assertEquals(4, termOffsets[0].getEndOffset());
- assertEquals(5, termOffsets[1].getStartOffset());
- assertEquals(9, termOffsets[1].getEndOffset());
- r.close();
- dir.close();
- }
-
- // LUCENE-1448
- public void testEndOffsetPositionCharAnalyzer() throws Exception {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- Document doc = new Document();
- Field f = new Field("field", "abcd ", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f);
- doc.add(f);
- w.addDocument(doc);
- w.close();
-
- IndexReader r = IndexReader.open(dir, true);
- TermVectorOffsetInfo[] termOffsets = ((TermPositionVector) r.getTermFreqVector(0, "field")).getOffsets(0);
- assertEquals(2, termOffsets.length);
- assertEquals(0, termOffsets[0].getStartOffset());
- assertEquals(4, termOffsets[0].getEndOffset());
- assertEquals(8, termOffsets[1].getStartOffset());
- assertEquals(12, termOffsets[1].getEndOffset());
- r.close();
- dir.close();
- }
+
- // LUCENE-1448
- public void testEndOffsetPositionWithCachingTokenFilter() throws Exception {
- MockRAMDirectory dir = new MockRAMDirectory();
- Analyzer analyzer = new MockAnalyzer();
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
- Document doc = new Document();
- TokenStream stream = new CachingTokenFilter(analyzer.tokenStream("field", new StringReader("abcd ")));
- Field f = new Field("field", stream, Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f);
- doc.add(f);
- w.addDocument(doc);
- w.close();
-
- IndexReader r = IndexReader.open(dir, true);
- TermVectorOffsetInfo[] termOffsets = ((TermPositionVector) r.getTermFreqVector(0, "field")).getOffsets(0);
- assertEquals(2, termOffsets.length);
- assertEquals(0, termOffsets[0].getStartOffset());
- assertEquals(4, termOffsets[0].getEndOffset());
- assertEquals(8, termOffsets[1].getStartOffset());
- assertEquals(12, termOffsets[1].getEndOffset());
- r.close();
- dir.close();
- }
-
- // LUCENE-1448
- public void testEndOffsetPositionStopFilter() throws Exception {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer(MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET, true)));
- Document doc = new Document();
- Field f = new Field("field", "abcd the", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f);
- doc.add(f);
- w.addDocument(doc);
- w.close();
-
- IndexReader r = IndexReader.open(dir, true);
- TermVectorOffsetInfo[] termOffsets = ((TermPositionVector) r.getTermFreqVector(0, "field")).getOffsets(0);
- assertEquals(2, termOffsets.length);
- assertEquals(0, termOffsets[0].getStartOffset());
- assertEquals(4, termOffsets[0].getEndOffset());
- assertEquals(9, termOffsets[1].getStartOffset());
- assertEquals(13, termOffsets[1].getEndOffset());
- r.close();
- dir.close();
- }
-
- // LUCENE-1448
- public void testEndOffsetPositionStandard() throws Exception {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()));
- Document doc = new Document();
- Field f = new Field("field", "abcd the ", Field.Store.NO,
- Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
- Field f2 = new Field("field", "crunch man", Field.Store.NO,
- Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f);
- doc.add(f2);
- w.addDocument(doc);
- w.close();
-
- IndexReader r = IndexReader.open(dir, true);
- TermPositionVector tpv = ((TermPositionVector) r.getTermFreqVector(0, "field"));
- TermVectorOffsetInfo[] termOffsets = tpv.getOffsets(0);
- assertEquals(1, termOffsets.length);
- assertEquals(0, termOffsets[0].getStartOffset());
- assertEquals(4, termOffsets[0].getEndOffset());
- termOffsets = tpv.getOffsets(1);
- assertEquals(11, termOffsets[0].getStartOffset());
- assertEquals(17, termOffsets[0].getEndOffset());
- termOffsets = tpv.getOffsets(2);
- assertEquals(18, termOffsets[0].getStartOffset());
- assertEquals(21, termOffsets[0].getEndOffset());
- r.close();
dir.close();
}
- // LUCENE-1448
- public void testEndOffsetPositionStandardEmptyField() throws Exception {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()));
- Document doc = new Document();
- Field f = new Field("field", "", Field.Store.NO,
- Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
- Field f2 = new Field("field", "crunch man", Field.Store.NO,
- Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f);
- doc.add(f2);
- w.addDocument(doc);
- w.close();
-
- IndexReader r = IndexReader.open(dir, true);
- TermPositionVector tpv = ((TermPositionVector) r.getTermFreqVector(0, "field"));
- TermVectorOffsetInfo[] termOffsets = tpv.getOffsets(0);
- assertEquals(1, termOffsets.length);
- assertEquals(0, termOffsets[0].getStartOffset());
- assertEquals(6, termOffsets[0].getEndOffset());
- termOffsets = tpv.getOffsets(1);
- assertEquals(7, termOffsets[0].getStartOffset());
- assertEquals(10, termOffsets[0].getEndOffset());
- r.close();
- dir.close();
- }
- // LUCENE-1448
- public void testEndOffsetPositionStandardEmptyField2() throws Exception {
- MockRAMDirectory dir = new MockRAMDirectory();
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()));
+ // LUCENE-2529
+ public void testPositionIncrementGapEmptyField() throws Exception {
+ Directory dir = newDirectory();
+ MockAnalyzer analyzer = new MockAnalyzer();
+ analyzer.setPositionIncrementGap( 100 );
- IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(
++ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(
+ TEST_VERSION_CURRENT, analyzer));
Document doc = new Document();
-
- Field f = new Field("field", "abcd", Field.Store.NO,
- Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
+ Field f = newField("field", "", Field.Store.NO,
+ Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS);
+ Field f2 = newField("field", "crunch man", Field.Store.NO,
+ Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS);
doc.add(f);
- doc.add(new Field("field", "", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
-
- Field f2 = new Field("field", "crunch", Field.Store.NO,
- Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
doc.add(f2);
-
w.addDocument(doc);
w.close();
@@@ -4255,13 -1964,11 +1964,11 @@@
// LUCENE-1468 -- make sure opening an IndexWriter with
// create=true does not remove non-index files
--
++
public void testOtherFiles() throws Throwable {
- File indexDir = new File(TEMP_DIR, "otherfiles");
- Directory dir = FSDirectory.open(indexDir);
+ Directory dir = newDirectory();
try {
// Create my own random file:
-
IndexOutput out = dir.createOutput("myrandomfile");
out.writeByte((byte) 42);
out.close();
@@@ -4316,9 -2022,9 +2022,9 @@@
@Override
public void run() {
- RAMDirectory dir = new RAMDirectory();
+ // LUCENE-2239: won't work with NIOFS/MMAP
- Directory dir = new MockDirectoryWrapper(random, new RAMDirectory());
++ Directory dir = new MockDirectoryWrapper(random, new RAMDirectory());
IndexWriter w = null;
- boolean first = true;
while(!finish) {
try {
@@@ -4326,8 -2032,8 +2032,8 @@@
if (w != null) {
w.close();
}
- IndexWriterConfig conf = new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2);
- IndexWriterConfig conf = newIndexWriterConfig(
++ IndexWriterConfig conf = newIndexWriterConfig(
+ TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2);
((LogMergePolicy) conf.getMergePolicy()).setMergeFactor(2);
w = new IndexWriter(dir, conf);
@@@ -4404,6 -2100,11 +2100,11 @@@
e.printStackTrace(System.out);
}
}
- try {
++ try {
+ dir.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
++ } catch (IOException e) {
++ throw new RuntimeException(e);
+ }
}
}
@@@ -4411,7 -2112,13 +2112,13 @@@
IndexerThreadInterrupt t = new IndexerThreadInterrupt();
t.setDaemon(true);
t.start();
-
+
+ // Force class loader to load ThreadInterruptedException
+ // up front... else we can see a false failure if 2nd
+ // interrupt arrives while class loader is trying to
+ // init this class (in servicing a first interrupt):
+ assertTrue(new ThreadInterruptedException(new InterruptedException()).getCause() instanceof InterruptedException);
-
++
// issue 100 interrupts to child thread
int i = 0;
while(i < 100) {
@@@ -4449,12 -2152,12 +2152,12 @@@
doc.add(f);
doc.add(f2);
w.addDocument(doc);
--
++
// add 2 docs to test in-memory merging
f.setTokenStream(new MockTokenizer(new StringReader("doc2field1"), MockTokenizer.WHITESPACE, false));
f2.setTokenStream(new MockTokenizer(new StringReader("doc2field2"), MockTokenizer.WHITESPACE, false));
w.addDocument(doc);
--
++
// force segment flush so we can force a segment merge with doc3 later.
w.commit();
@@@ -4476,7 -2180,7 +2180,7 @@@
assertTrue(ir.document(0).getFieldable("binary").isBinary());
assertTrue(ir.document(1).getFieldable("binary").isBinary());
assertTrue(ir.document(2).getFieldable("binary").isBinary());
--
++
assertEquals("value", ir.document(0).get("string"));
assertEquals("value", ir.document(1).get("string"));
assertEquals("value", ir.document(2).get("string"));
@@@ -4546,8 -2250,8 +2250,8 @@@
}
public void testNoDocsIndex() throws Throwable {
- Directory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
+ Directory dir = newDirectory();
- IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
++ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()));
LogMergePolicy lmp = (LogMergePolicy) writer.getConfig().getMergePolicy();
lmp.setUseCompoundFile(false);
@@@ -4559,7 -2263,7 +2263,7 @@@
_TestUtil.checkIndex(dir);
dir.close();
}
--
++
// LUCENE-2095: make sure with multiple threads commit
// doesn't return until all changes are in fact in the
// index
@@@ -4743,13 -2449,14 +2449,14 @@@
StringBuilder s = new StringBuilder();
// must be > 256
for(int i=0;i<300;i++) {
- s.append(' ').append(""+i);
+ s.append(' ').append(i);
}
Document d = new Document();
- Field f = new Field("field", s.toString(), Field.Store.NO, Field.Index.ANALYZED);
+ Field f = newField("field", s.toString(), Field.Store.NO, Field.Index.ANALYZED);
d.add(f);
w.addDocument(d);
- IndexReader r = w.getReader(2).getSequentialSubReaders()[0];
-
++
+ IndexReader r = w.getReader().getSequentialSubReaders()[0];
TermsEnum t = r.fields().terms("field").iterator();
int count = 0;
while(t.next() != null) {
@@@ -4825,25 -2539,25 +2539,25 @@@
public void testDeleteUnsedFiles2() throws Exception {
// Validates that iw.deleteUnusedFiles() also deletes unused index commits
// in case a deletion policy which holds onto commits is used.
- Directory dir = new MockRAMDirectory();
+ Directory dir = newDirectory();
SnapshotDeletionPolicy sdp = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
- IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
++ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer())
.setIndexDeletionPolicy(sdp));
--
++
// First commit
Document doc = new Document();
- doc.add(new Field("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
+ doc.add(newField("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
writer.addDocument(doc);
writer.commit();
assertEquals(1, IndexReader.listCommits(dir).size());
// Keep that commit
sdp.snapshot("id");
--
++
// Second commit - now KeepOnlyLastCommit cannot delete the prev commit.
doc = new Document();
- doc.add(new Field("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
+ doc.add(newField("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
writer.addDocument(doc);
writer.commit();
assertEquals(2, IndexReader.listCommits(dir).size());
@@@ -4852,10 -2566,11 +2566,11 @@@
sdp.release("id");
writer.deleteUnusedFiles();
assertEquals(1, IndexReader.listCommits(dir).size());
--
++
writer.close();
+ dir.close();
}
--
++
private static class FlushCountingIndexWriter extends IndexWriter {
int flushCount;
public FlushCountingIndexWriter(Directory dir, IndexWriterConfig iwc) throws IOException {
@@@ -4900,7 -2618,7 +2618,7 @@@
w.close();
dir.close();
}
--
++
public void testNoCommits() throws Exception {
// Tests that if we don't call commit(), the directory has 0 commits. This has
// changed since LUCENE-2386, where before IW would always commit on a fresh
@@@ -4920,35 -2639,47 +2639,47 @@@
public void testEmptyFSDirWithNoLock() throws Exception {
// Tests that if FSDir is opened w/ a NoLockFactory (or SingleInstanceLF),
-- // then IndexWriter ctor succeeds. Previously (LUCENE-2386) it failed
++ // then IndexWriter ctor succeeds. Previously (LUCENE-2386) it failed
// when listAll() was called in IndexFileDeleter.
- FSDirectory dir = FSDirectory.open(new File(TEMP_DIR, "emptyFSDirNoLock"), NoLockFactory.getNoLockFactory());
- new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer())).close();
+ Directory dir = newFSDirectory(new File(TEMP_DIR, "emptyFSDirNoLock"), NoLockFactory.getNoLockFactory());
+ new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer())).close();
+ dir.close();
}
public void testEmptyDirRollback() throws Exception {
// Tests that if IW is created over an empty Directory, some documents are
-- // indexed, flushed (but not committed) and then IW rolls back, then no
++ // indexed, flushed (but not committed) and then IW rolls back, then no
// files are left in the Directory.
- Directory dir = new MockRAMDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
+ Directory dir = newDirectory();
- IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
++ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer())
.setMaxBufferedDocs(2));
- // Creating over empty dir should not create any files.
- assertEquals(0, dir.listAll().length);
+ String[] files = dir.listAll();
+
+ // Creating over empty dir should not create any files,
+ // or, at most the write.lock file
+ final int extraFileCount;
+ if (files.length == 1) {
+ assertEquals("write.lock", files[0]);
+ extraFileCount = 1;
+ } else {
+ assertEquals(0, files.length);
+ extraFileCount = 0;
+ }
+
Document doc = new Document();
// create as many files as possible
- doc.add(new Field("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
+ doc.add(newField("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
writer.addDocument(doc);
// Adding just one document does not call flush yet.
- assertEquals("only the stored and term vector files should exist in the directory", 5, dir.listAll().length);
-
+ assertEquals("only the stored and term vector files should exist in the directory", 5 + extraFileCount, dir.listAll().length);
-
++
doc = new Document();
- doc.add(new Field("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
+ doc.add(newField("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
writer.addDocument(doc);
// The second document should cause a flush.
- assertTrue("flush should have occurred and files created", dir.listAll().length > 0);
-
+ assertTrue("flush should have occurred and files created", dir.listAll().length > 5 + extraFileCount);
-
++
// After rollback, IW should remove all files
writer.rollback();
assertEquals("no files should exist in the directory after rollback", 0, dir.listAll().length);
@@@ -4959,28 -2691,23 +2691,23 @@@
}
public void testNoSegmentFile() throws IOException {
- File tempDir = _TestUtil.getTempDir("noSegmentFile");
- try {
- Directory dir = FSDirectory.open(tempDir);
- dir.setLockFactory(NoLockFactory.getNoLockFactory());
- IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2));
+ Directory dir = newDirectory();
+ dir.setLockFactory(NoLockFactory.getNoLockFactory());
- IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(
++ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(
+ TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2));
-
+
- Document doc = new Document();
- doc.add(new Field("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
- w.addDocument(doc);
- w.addDocument(doc);
- IndexWriter w2 = new IndexWriter(dir, new IndexWriterConfig(
- TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2)
- .setOpenMode(OpenMode.CREATE));
+ Document doc = new Document();
+ doc.add(newField("c", "val", Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
+ w.addDocument(doc);
+ w.addDocument(doc);
- IndexWriter w2 = new IndexWriter(dir, newIndexWriterConfig(
++ IndexWriter w2 = new IndexWriter(dir, newIndexWriterConfig(
+ TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2)
+ .setOpenMode(OpenMode.CREATE));
-
+
- w2.close();
- // If we don't do that, the test fails on Windows
- w.rollback();
- dir.close();
- } finally {
- _TestUtil.rmDir(tempDir);
- }
+ w2.close();
+ // If we don't do that, the test fails on Windows
+ w.rollback();
+ dir.close();
}
public void testFutureCommit() throws Exception {
@@@ -5012,10 -2739,10 +2739,10 @@@
assertNotNull(commit);
- w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setIndexDeletionPolicy(NoDeletionPolicy.INSTANCE).setIndexCommit(commit));
+ w = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setIndexDeletionPolicy(NoDeletionPolicy.INSTANCE).setIndexCommit(commit));
assertEquals(1, w.numDocs());
--
++
// commit IndexWriter to "third"
w.addDocument(doc);
commitData.put("tag", "third");
@@@ -5058,4 -2785,126 +2785,126 @@@
dir.close();
}
+
+ public void testRandomStoredFields() throws IOException {
+ Directory dir = newDirectory();
+ Random rand = random;
+ RandomIndexWriter w = new RandomIndexWriter(rand, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(_TestUtil.nextInt(rand, 5, 20)));
+ //w.w.setInfoStream(System.out);
+ //w.w.setUseCompoundFile(false);
+ if (VERBOSE) {
+ w.w.setInfoStream(System.out);
+ }
+ final int docCount = 200*RANDOM_MULTIPLIER;
+ final int fieldCount = _TestUtil.nextInt(rand, 1, 5);
-
++
+ final List<Integer> fieldIDs = new ArrayList<Integer>();
+
+ Field idField = newField("id", "", Field.Store.YES, Field.Index.NOT_ANALYZED);
+
+ for(int i=0;i<fieldCount;i++) {
+ fieldIDs.add(i);
+ }
+
+ final Map<String,Document> docs = new HashMap<String,Document>();
-
++
+ if (VERBOSE) {
+ System.out.println("TEST: build index docCount=" + docCount);
+ }
+
+ for(int i=0;i<docCount;i++) {
+ Document doc = new Document();
+ doc.add(idField);
+ final String id = ""+i;
+ idField.setValue(id);
+ docs.put(id, doc);
+
+ for(int field: fieldIDs) {
+ final String s;
+ if (rand.nextInt(4) != 3) {
+ s = _TestUtil.randomUnicodeString(rand, 1000);
+ doc.add(newField("f"+field, s, Field.Store.YES, Field.Index.NO));
+ } else {
+ s = null;
+ }
+ }
+ w.addDocument(doc);
+ if (rand.nextInt(50) == 17) {
+ // mixup binding of field name -> Number every so often
+ Collections.shuffle(fieldIDs);
+ }
+ if (rand.nextInt(5) == 3 && i > 0) {
+ final String delID = ""+rand.nextInt(i);
+ if (VERBOSE) {
+ System.out.println("TEST: delete doc " + delID);
+ }
+ w.deleteDocuments(new Term("id", delID));
+ docs.remove(delID);
+ }
+ }
+
+ if (VERBOSE) {
+ System.out.println("TEST: " + docs.size() + " docs in index; now load fields");
+ }
+ if (docs.size() > 0) {
+ String[] idsList = docs.keySet().toArray(new String[docs.size()]);
+
+ for(int x=0;x<2;x++) {
+ IndexReader r = w.getReader();
+ IndexSearcher s = new IndexSearcher(r);
+
+ if (VERBOSE) {
+ System.out.println("TEST: cycle x=" + x + " r=" + r);
+ }
+
+ for(int iter=0;iter<1000*RANDOM_MULTIPLIER;iter++) {
+ String testID = idsList[rand.nextInt(idsList.length)];
+ TopDocs hits = s.search(new TermQuery(new Term("id", testID)), 1);
+ assertEquals(1, hits.totalHits);
+ Document doc = r.document(hits.scoreDocs[0].doc);
+ Document docExp = docs.get(testID);
+ for(int i=0;i<fieldCount;i++) {
+ assertEquals("doc " + testID + ", field f" + fieldCount + " is wrong", docExp.get("f"+i), doc.get("f"+i));
+ }
+ }
+ r.close();
+ w.optimize();
+ }
+ }
+ w.close();
+ dir.close();
+ }
+
+ public void testNoUnwantedTVFiles() throws Exception {
+
+ Directory dir = newDirectory();
+ IndexWriter indexWriter = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setRAMBufferSizeMB(0.01));
+ ((LogMergePolicy) indexWriter.getConfig().getMergePolicy()).setUseCompoundFile(false);
+
+ String BIG="alskjhlaksjghlaksjfhalksvjepgjioefgjnsdfjgefgjhelkgjhqewlrkhgwlekgrhwelkgjhwelkgrhwlkejg";
+ BIG=BIG+BIG+BIG+BIG;
+
+ for (int i=0; i<2; i++) {
+ Document doc = new Document();
+ doc.add(new Field("id", Integer.toString(i)+BIG, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
+ doc.add(new Field("str", Integer.toString(i)+BIG, Field.Store.YES, Field.Index.NOT_ANALYZED));
+ doc.add(new Field("str2", Integer.toString(i)+BIG, Field.Store.YES, Field.Index.ANALYZED));
+ doc.add(new Field("str3", Integer.toString(i)+BIG, Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));
+ indexWriter.addDocument(doc);
+ }
+
+ indexWriter.close();
+
+ _TestUtil.checkIndex(dir);
+
+ assertNoUnreferencedFiles(dir, "no tv files");
+ String[] files = dir.listAll();
+ for(String file : files) {
+ assertTrue(!file.endsWith(IndexFileNames.VECTORS_FIELDS_EXTENSION));
+ assertTrue(!file.endsWith(IndexFileNames.VECTORS_INDEX_EXTENSION));
+ assertTrue(!file.endsWith(IndexFileNames.VECTORS_DOCUMENTS_EXTENSION));
+ }
+
+ dir.close();
+ }
}
diff --cc lucene/src/test/org/apache/lucene/index/TestIndexWriterConfig.java
index 858763c63c8,29ea32d42fa..557fddf17dc
--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriterConfig.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriterConfig.java
@@@ -17,11 -17,8 +17,6 @@@ package org.apache.lucene.index
* limitations under the License.
*/
- import static org.junit.Assert.assertEquals;
- import static org.junit.Assert.assertNull;
- import static org.junit.Assert.assertTrue;
- import static org.junit.Assert.fail;
-import static org.junit.Assert.*;
--
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@@@ -30,29 -27,29 +25,28 @@@ import java.util.HashSet
import java.util.Set;
import org.apache.lucene.analysis.MockAnalyzer;
-import org.apache.lucene.index.DocumentsWriter.IndexingChain;
+import org.apache.lucene.index.DocumentsWriterPerThread.IndexingChain;
import org.apache.lucene.index.IndexWriter.IndexReaderWarmer;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
- import org.apache.lucene.index.codecs.CodecProvider;
import org.apache.lucene.search.DefaultSimilarity;
import org.apache.lucene.search.Similarity;
- import org.apache.lucene.util.LuceneTestCaseJ4;
-import org.apache.lucene.store.Directory;
+ import org.apache.lucene.util.LuceneTestCase;
import org.junit.Test;
- public class TestIndexWriterConfig extends LuceneTestCaseJ4 {
+ public class TestIndexWriterConfig extends LuceneTestCase {
private static final class MySimilarity extends DefaultSimilarity {
// Does not implement anything - used only for type checking on IndexWriterConfig.
}
--
++
private static final class MyIndexingChain extends IndexingChain {
// Does not implement anything - used only for type checking on IndexWriterConfig.
@Override
- DocConsumer getChain(DocumentsWriter documentsWriter) {
+ DocConsumer getChain(DocumentsWriterPerThread documentsWriter) {
return null;
}
--
++
}
private static final class MyWarmer extends IndexReaderWarmer {
@@@ -61,9 -58,9 +55,9 @@@
@Override
public void warm(IndexReader reader) throws IOException {
}
--
++
}
--
++
@Test
public void testDefaults() throws Exception {
IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer());
@@@ -81,14 -78,12 +75,13 @@@
assertEquals(IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB, conf.getRAMBufferSizeMB(), 0.0);
assertEquals(IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS, conf.getMaxBufferedDocs());
assertEquals(IndexWriterConfig.DEFAULT_READER_POOLING, conf.getReaderPooling());
- assertTrue(DocumentsWriter.defaultIndexingChain == conf.getIndexingChain());
+ assertTrue(DocumentsWriterPerThread.defaultIndexingChain == conf.getIndexingChain());
assertNull(conf.getMergedSegmentWarmer());
- assertEquals(IndexWriterConfig.DEFAULT_CODEC_PROVIDER, CodecProvider.getDefault());
assertEquals(IndexWriterConfig.DEFAULT_MAX_THREAD_STATES, conf.getMaxThreadStates());
assertEquals(IndexWriterConfig.DEFAULT_READER_TERMS_INDEX_DIVISOR, conf.getReaderTermsIndexDivisor());
assertEquals(LogByteSizeMergePolicy.class, conf.getMergePolicy().getClass());
-
+ assertEquals(ThreadAffinityDocumentsWriterThreadPool.class, conf.getIndexerThreadPool().getClass());
-
++
// Sanity check - validate that all getters are covered.
Set<String> getters = new HashSet<String>();
getters.add("getAnalyzer");
@@@ -127,12 -121,12 +120,12 @@@
if (m.getDeclaringClass() == IndexWriterConfig.class
&& m.getName().startsWith("set")
&& !Modifier.isStatic(m.getModifiers())) {
-- assertEquals("method " + m.getName() + " does not return IndexWriterConfig",
++ assertEquals("method " + m.getName() + " does not return IndexWriterConfig",
IndexWriterConfig.class, m.getReturnType());
}
}
}
--
++
@Test
public void testConstants() throws Exception {
// Tests that the values of the constants does not change
@@@ -147,7 -141,7 +140,7 @@@
assertEquals(8, IndexWriterConfig.DEFAULT_MAX_THREAD_STATES);
assertEquals(IndexReader.DEFAULT_TERMS_INDEX_DIVISOR, IndexWriterConfig.DEFAULT_READER_TERMS_INDEX_DIVISOR);
}
--
++
@Test
public void testToString() throws Exception {
String str = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).toString();
@@@ -164,15 -158,15 +157,15 @@@
assertTrue(f.getName() + " not found in toString", str.indexOf(f.getName()) != -1);
}
}
--
++
@Test
public void testClone() throws Exception {
IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer());
IndexWriterConfig clone = (IndexWriterConfig) conf.clone();
--
++
// Clone is shallow since not all parameters are cloneable.
assertTrue(conf.getIndexDeletionPolicy() == clone.getIndexDeletionPolicy());
--
++
conf.setMergeScheduler(new SerialMergeScheduler());
assertEquals(ConcurrentMergeScheduler.class, clone.getMergeScheduler().getClass());
}
@@@ -180,14 -174,14 +173,14 @@@
@Test
public void testInvalidValues() throws Exception {
IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer());
--
++
// Test IndexDeletionPolicy
assertEquals(KeepOnlyLastCommitDeletionPolicy.class, conf.getIndexDeletionPolicy().getClass());
conf.setIndexDeletionPolicy(new SnapshotDeletionPolicy(null));
assertEquals(SnapshotDeletionPolicy.class, conf.getIndexDeletionPolicy().getClass());
conf.setIndexDeletionPolicy(null);
assertEquals(KeepOnlyLastCommitDeletionPolicy.class, conf.getIndexDeletionPolicy().getClass());
--
++
// Test MergeScheduler
assertEquals(ConcurrentMergeScheduler.class, conf.getMergeScheduler().getClass());
conf.setMergeScheduler(new SerialMergeScheduler());
@@@ -207,8 -201,8 +200,8 @@@
conf.setIndexingChain(new MyIndexingChain());
assertEquals(MyIndexingChain.class, conf.getIndexingChain().getClass());
conf.setIndexingChain(null);
- assertTrue(DocumentsWriter.defaultIndexingChain == conf.getIndexingChain());
-
+ assertTrue(DocumentsWriterPerThread.defaultIndexingChain == conf.getIndexingChain());
-
++
try {
conf.setMaxBufferedDeleteTerms(0);
fail("should not have succeeded to set maxBufferedDeleteTerms to 0");
@@@ -243,11 -237,11 +236,11 @@@
}
assertEquals(IndexWriterConfig.DEFAULT_MAX_THREAD_STATES, conf.getMaxThreadStates());
- conf.setMaxThreadStates(5);
+ conf.setIndexerThreadPool(new ThreadAffinityDocumentsWriterThreadPool(5));
assertEquals(5, conf.getMaxThreadStates());
- conf.setMaxThreadStates(0);
+ conf.setIndexerThreadPool(new ThreadAffinityDocumentsWriterThreadPool(0));
assertEquals(IndexWriterConfig.DEFAULT_MAX_THREAD_STATES, conf.getMaxThreadStates());
--
++
// Test MergePolicy
assertEquals(LogByteSizeMergePolicy.class, conf.getMergePolicy().getClass());
conf.setMergePolicy(new LogDocMergePolicy());
diff --cc lucene/src/test/org/apache/lucene/index/TestIndexWriterDelete.java
index 7710392df2a,617a6b8d4a6..78ca5225c6b
--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriterDelete.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriterDelete.java
@@@ -27,11 -27,13 +27,13 @@@ import org.apache.lucene.search.IndexSe
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
- import org.apache.lucene.store.MockRAMDirectory;
+ import org.apache.lucene.store.MockDirectoryWrapper;
+ import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.LuceneTestCase;
+ import org.apache.lucene.util._TestUtil;
public class TestIndexWriterDelete extends LuceneTestCase {
-
+
// test the simple case
public void testSimpleCase() throws IOException {
String[] keywords = { "1", "2" };
@@@ -213,7 -222,7 +222,7 @@@
IndexReader reader = IndexReader.open(dir, true);
assertEquals(7, reader.numDocs());
reader.close();
--
++
id = 0;
modifier.deleteDocuments(new Term("id", String.valueOf(++id)));
modifier.deleteDocuments(new Term("id", String.valueOf(++id)));
@@@ -286,51 -295,51 +295,51 @@@
// test rollback of deleteAll()
public void testDeleteAllRollback() throws IOException {
- Directory dir = new MockRAMDirectory();
- IndexWriter modifier = new IndexWriter(dir, new IndexWriterConfig(
+ Directory dir = newDirectory();
+ IndexWriter modifier = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(MockTokenizer.WHITESPACE, false)).setMaxBufferedDocs(2)
.setMaxBufferedDeleteTerms(2));
--
++
int id = 0;
int value = 100;
--
++
for (int i = 0; i < 7; i++) {
addDoc(modifier, ++id, value);
}
modifier.commit();
--
++
addDoc(modifier, ++id, value);
IndexReader reader = IndexReader.open(dir, true);
assertEquals(7, reader.numDocs());
reader.close();
--
++
// Delete all
-- modifier.deleteAll();
++ modifier.deleteAll();
// Roll it back
modifier.rollback();
modifier.close();
--
++
// Validate that the docs are still there
reader = IndexReader.open(dir, true);
assertEquals(7, reader.numDocs());
reader.close();
--
++
dir.close();
}
// test deleteAll() w/ near real-time reader
public void testDeleteAllNRT() throws IOException {
- Directory dir = new MockRAMDirectory();
- IndexWriter modifier = new IndexWriter(dir, new IndexWriterConfig(
+ Directory dir = newDirectory();
+ IndexWriter modifier = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(MockTokenizer.WHITESPACE, false)).setMaxBufferedDocs(2)
.setMaxBufferedDeleteTerms(2));
--
++
int id = 0;
int value = 100;
--
++
for (int i = 0; i < 7; i++) {
addDoc(modifier, ++id, value);
}
@@@ -342,24 -351,24 +351,24 @@@
addDoc(modifier, ++id, value);
addDoc(modifier, ++id, value);
--
++
// Delete all
-- modifier.deleteAll();
++ modifier.deleteAll();
reader = modifier.getReader();
assertEquals(0, reader.numDocs());
reader.close();
--
++
// Roll it back
modifier.rollback();
modifier.close();
--
++
// Validate that the docs are still there
reader = IndexReader.open(dir, true);
assertEquals(7, reader.numDocs());
reader.close();
--
++
dir.close();
}
@@@ -592,12 -621,14 +621,14 @@@
// This test tests that buffered deletes are cleared when
// an Exception is hit during flush.
public void testErrorAfterApplyDeletes() throws IOException {
--
- MockRAMDirectory.Failure failure = new MockRAMDirectory.Failure() {
++
+ MockDirectoryWrapper.Failure failure = new MockDirectoryWrapper.Failure() {
boolean sawMaybe = false;
boolean failed = false;
+ Thread thread;
@Override
- public MockRAMDirectory.Failure reset() {
+ public MockDirectoryWrapper.Failure reset() {
+ thread = Thread.currentThread();
sawMaybe = false;
failed = false;
return this;
@@@ -724,11 -785,11 +785,11 @@@
// a segment is written are cleaned up if there's an i/o error
public void testErrorInDocsWriterAdd() throws IOException {
--
- MockRAMDirectory.Failure failure = new MockRAMDirectory.Failure() {
++
+ MockDirectoryWrapper.Failure failure = new MockDirectoryWrapper.Failure() {
boolean failed = false;
@Override
- public MockRAMDirectory.Failure reset() {
+ public MockDirectoryWrapper.Failure reset() {
failed = false;
return this;
}
diff --cc lucene/src/test/org/apache/lucene/index/TestIndexWriterOnJRECrash.java
index 00000000000,3a8b0c86c7e..4ad1a458f8e
mode 000000,100644..100644
--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriterOnJRECrash.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriterOnJRECrash.java
@@@ -1,0 -1,158 +1,158 @@@
+ 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.BufferedInputStream;
+ import java.io.File;
+ import java.io.IOException;
+ import java.io.InputStream;
+ import java.lang.reflect.Field;
+ import java.lang.reflect.Method;
+ import java.util.ArrayList;
+ import java.util.List;
+
+ import org.apache.lucene.store.Directory;
+ import org.apache.lucene.util.Constants;
+ import org.apache.lucene.util._TestUtil;
+
+ /**
+ * Runs TestNRTThreads in a separate process, crashes the JRE in the middle
+ * of execution, then runs checkindex to make sure its not corrupt.
+ */
+ public class TestIndexWriterOnJRECrash extends TestNRTThreads {
+ private File tempDir;
-
++
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ tempDir = File.createTempFile("jrecrash", "tmp", TEMP_DIR);
+ tempDir.delete();
+ tempDir.mkdir();
+ }
-
++
+ @Override
+ public void testNRTThreads() throws Exception {
+ String vendor = Constants.JAVA_VENDOR;
- assumeTrue(vendor + " JRE not supported.",
++ assumeTrue(vendor + " JRE not supported.",
+ vendor.startsWith("Sun") || vendor.startsWith("IBM") || vendor.startsWith("Apple"));
-
++
+ // if we are not the fork
+ if (System.getProperty("tests.crashmode") == null) {
+ // try up to 10 times to create an index
+ for (int i = 0; i < 10; i++) {
+ forkTest();
+ // if we succeeded in finding an index, we are done.
+ if (checkIndexes(tempDir))
+ return;
+ }
+ } else {
+ // we are the fork, setup a crashing thread
+ final int crashTime = _TestUtil.nextInt(random, 500, 4000);
+ Thread t = new Thread() {
+ @Override
+ public void run() {
+ try {
+ Thread.sleep(crashTime);
+ } catch (InterruptedException e) {}
+ crashJRE();
+ }
+ };
+ t.setPriority(Thread.MAX_PRIORITY);
+ t.start();
+ // run the test until we crash.
+ for (int i = 0; i < 1000; i++) {
+ super.testNRTThreads();
+ }
+ }
+ }
-
++
+ /** fork ourselves in a new jvm. sets -Dtests.crashmode=true */
+ public void forkTest() throws Exception {
+ List<String> cmd = new ArrayList<String>();
- cmd.add(System.getProperty("java.home")
++ cmd.add(System.getProperty("java.home")
+ + System.getProperty("file.separator")
+ + "bin"
+ + System.getProperty("file.separator")
+ + "java");
+ cmd.add("-Xmx512m");
+ cmd.add("-Dtests.crashmode=true");
+ cmd.add("-DtempDir=" + tempDir.getPath());
+ cmd.add("-Dtests.seed=" + random.nextLong() + ":" + random.nextLong());
+ cmd.add("-ea");
+ cmd.add("-cp");
+ cmd.add(System.getProperty("java.class.path"));
+ cmd.add("org.junit.runner.JUnitCore");
+ cmd.add(getClass().getName());
+ ProcessBuilder pb = new ProcessBuilder(cmd);
+ pb.directory(TEMP_DIR);
+ pb.redirectErrorStream(true);
+ Process p = pb.start();
+ InputStream is = p.getInputStream();
+ BufferedInputStream isl = new BufferedInputStream(is);
+ byte buffer[] = new byte[1024];
+ int len = 0;
+ if (VERBOSE) System.err.println(">>> Begin subprocess output");
+ while ((len = isl.read(buffer)) != -1) {
+ if (VERBOSE) {
+ System.err.write(buffer, 0, len);
+ }
+ }
+ if (VERBOSE) System.err.println("<<< End subprocess output");
+ p.waitFor();
+ }
-
++
+ /**
+ * Recursively looks for indexes underneath <code>file</code>,
+ * and runs checkindex on them. returns true if it found any indexes.
+ */
+ public boolean checkIndexes(File file) throws IOException {
+ if (file.isDirectory()) {
+ Directory dir = newFSDirectory(file);
+ if (IndexReader.indexExists(dir)) {
+ if (VERBOSE) {
+ System.err.println("Checking index: " + file);
+ }
+ _TestUtil.checkIndex(dir);
+ dir.close();
+ return true;
+ }
+ dir.close();
+ for (File f : file.listFiles())
+ if (checkIndexes(f))
+ return true;
+ }
+ return false;
+ }
-
++
+ /**
+ * currently, this only works/tested on Sun and IBM.
+ */
+ public void crashJRE() {
+ try {
+ Class<?> clazz = Class.forName("sun.misc.Unsafe");
+ // we should use getUnsafe instead, harmony implements it, etc.
+ Field field = clazz.getDeclaredField("theUnsafe");
+ field.setAccessible(true);
+ Object o = field.get(null);
+ Method m = clazz.getMethod("putAddress", long.class, long.class);
+ m.invoke(o, 0L, 0L);
+ } catch (Exception e) { e.printStackTrace(); }
+ fail();
+ }
+ }
diff --cc lucene/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java
index 00000000000,c8d7fdfdd43..20e1cda5801
mode 000000,100644..100644
--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java
@@@ -1,0 -1,401 +1,401 @@@
+ 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 org.apache.lucene.analysis.MockAnalyzer;
+ import org.apache.lucene.document.Document;
+ import org.apache.lucene.document.Field;
+ import org.apache.lucene.store.AlreadyClosedException;
+ import org.apache.lucene.store.Directory;
+ import org.apache.lucene.store.MockDirectoryWrapper;
+ import org.apache.lucene.util.Bits;
+ import org.apache.lucene.util.BytesRef;
+ import org.apache.lucene.util.LuceneTestCase;
+ import org.apache.lucene.util.ThreadInterruptedException;
+
+ /**
+ * MultiThreaded IndexWriter tests
+ */
+ public class TestIndexWriterWithThreads extends LuceneTestCase {
+
+ // Used by test cases below
+ private class IndexerThread extends Thread {
+
+ boolean diskFull;
+ Throwable error;
+ AlreadyClosedException ace;
+ IndexWriter writer;
+ boolean noErrors;
+ volatile int addCount;
+
+ public IndexerThread(IndexWriter writer, boolean noErrors) {
+ this.writer = writer;
+ this.noErrors = noErrors;
+ }
+
+ @Override
+ public void run() {
+
+ final Document doc = new Document();
+ doc.add(newField("field", "aaa bbb ccc ddd eee fff ggg hhh iii jjj", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
+
+ int idUpto = 0;
+ int fullCount = 0;
+ final long stopTime = System.currentTimeMillis() + 200;
+
+ do {
+ try {
+ writer.updateDocument(new Term("id", ""+(idUpto++)), doc);
+ addCount++;
+ } catch (IOException ioe) {
+ //System.out.println(Thread.currentThread().getName() + ": hit exc");
+ //ioe.printStackTrace(System.out);
+ if (ioe.getMessage().startsWith("fake disk full at") ||
+ ioe.getMessage().equals("now failing on purpose")) {
+ diskFull = true;
+ try {
+ Thread.sleep(1);
+ } catch (InterruptedException ie) {
+ throw new ThreadInterruptedException(ie);
+ }
+ if (fullCount++ >= 5)
+ break;
+ } else {
+ if (noErrors) {
+ System.out.println(Thread.currentThread().getName() + ": ERROR: unexpected IOException:");
+ ioe.printStackTrace(System.out);
+ error = ioe;
+ }
+ break;
+ }
+ } catch (Throwable t) {
+ //t.printStackTrace(System.out);
+ if (noErrors) {
+ System.out.println(Thread.currentThread().getName() + ": ERROR: unexpected Throwable:");
+ t.printStackTrace(System.out);
+ error = t;
+ }
+ break;
+ }
+ } while(System.currentTimeMillis() < stopTime);
+ }
+ }
+
+ // LUCENE-1130: make sure immediate disk full on creating
+ // an IndexWriter (hit during DW.ThreadState.init()), with
+ // multiple threads, is OK:
+ public void testImmediateDiskFullWithThreads() throws Exception {
+
+ int NUM_THREADS = 3;
+
+ for(int iter=0;iter<10;iter++) {
+ if (VERBOSE) {
+ System.out.println("\nTEST: iter=" + iter);
+ }
+ MockDirectoryWrapper dir = newDirectory();
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMaxBufferedDocs(2).
+ setMergeScheduler(new ConcurrentMergeScheduler()).
+ setMergePolicy(newLogMergePolicy(4))
+ );
+ ((ConcurrentMergeScheduler) writer.getConfig().getMergeScheduler()).setSuppressExceptions();
+ dir.setMaxSizeInBytes(4*1024+20*iter);
+ writer.setInfoStream(VERBOSE ? System.out : null);
+
+ IndexerThread[] threads = new IndexerThread[NUM_THREADS];
+
+ for(int i=0;i<NUM_THREADS;i++)
+ threads[i] = new IndexerThread(writer, true);
+
+ for(int i=0;i<NUM_THREADS;i++)
+ threads[i].start();
+
+ for(int i=0;i<NUM_THREADS;i++) {
+ // Without fix for LUCENE-1130: one of the
+ // threads will hang
+ threads[i].join();
+ assertTrue("hit unexpected Throwable", threads[i].error == null);
+ }
+
+ // Make sure once disk space is avail again, we can
+ // cleanly close:
+ dir.setMaxSizeInBytes(0);
+ writer.close(false);
+ dir.close();
+ }
+ }
-
++
+
+ // LUCENE-1130: make sure we can close() even while
+ // threads are trying to add documents. Strictly
+ // speaking, this isn't valid us of Lucene's APIs, but we
+ // still want to be robust to this case:
+ public void testCloseWithThreads() throws Exception {
+ int NUM_THREADS = 3;
+
+ for(int iter=0;iter<7;iter++) {
+ Directory dir = newDirectory();
+
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMaxBufferedDocs(10).
+ setMergeScheduler(new ConcurrentMergeScheduler()).
+ setMergePolicy(newLogMergePolicy(4))
+ );
+ ((ConcurrentMergeScheduler) writer.getConfig().getMergeScheduler()).setSuppressExceptions();
+
+ IndexerThread[] threads = new IndexerThread[NUM_THREADS];
+
+ for(int i=0;i<NUM_THREADS;i++)
+ threads[i] = new IndexerThread(writer, false);
+
+ for(int i=0;i<NUM_THREADS;i++)
+ threads[i].start();
+
+ boolean done = false;
+ while(!done) {
+ Thread.sleep(100);
+ for(int i=0;i<NUM_THREADS;i++)
+ // only stop when at least one thread has added a doc
+ if (threads[i].addCount > 0) {
+ done = true;
+ break;
+ }
+ }
+
+ writer.close(false);
+
+ // Make sure threads that are adding docs are not hung:
+ for(int i=0;i<NUM_THREADS;i++) {
+ // Without fix for LUCENE-1130: one of the
+ // threads will hang
+ threads[i].join();
+ if (threads[i].isAlive())
+ fail("thread seems to be hung");
+ }
+
+ // Quick test to make sure index is not corrupt:
+ IndexReader reader = IndexReader.open(dir, true);
+ DocsEnum tdocs = MultiFields.getTermDocsEnum(reader,
+ MultiFields.getDeletedDocs(reader),
+ "field",
+ new BytesRef("aaa"));
+ int count = 0;
+ while(tdocs.nextDoc() != DocsEnum.NO_MORE_DOCS) {
+ count++;
+ }
+ assertTrue(count > 0);
+ reader.close();
-
++
+ dir.close();
+ }
+ }
+
+ // Runs test, with multiple threads, using the specific
+ // failure to trigger an IOException
+ public void _testMultipleThreadsFailure(MockDirectoryWrapper.Failure failure) throws Exception {
+
+ int NUM_THREADS = 3;
+
+ for(int iter=0;iter<2;iter++) {
+ MockDirectoryWrapper dir = newDirectory();
+
+ IndexWriter writer = new IndexWriter(
+ dir,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMaxBufferedDocs(2).
+ setMergeScheduler(new ConcurrentMergeScheduler()).
+ setMergePolicy(newLogMergePolicy(4))
+ );
+ ((ConcurrentMergeScheduler) writer.getConfig().getMergeScheduler()).setSuppressExceptions();
+
+ IndexerThread[] threads = new IndexerThread[NUM_THREADS];
+
+ for(int i=0;i<NUM_THREADS;i++)
+ threads[i] = new IndexerThread(writer, true);
+
+ for(int i=0;i<NUM_THREADS;i++)
+ threads[i].start();
+
+ Thread.sleep(10);
+
+ dir.failOn(failure);
+ failure.setDoFail();
+
+ for(int i=0;i<NUM_THREADS;i++) {
+ threads[i].join();
+ assertTrue("hit unexpected Throwable", threads[i].error == null);
+ }
+
+ boolean success = false;
+ try {
+ writer.close(false);
+ success = true;
+ } catch (IOException ioe) {
+ failure.clearDoFail();
+ writer.close(false);
+ }
+
+ if (success) {
+ IndexReader reader = IndexReader.open(dir, true);
+ final Bits delDocs = MultiFields.getDeletedDocs(reader);
+ for(int j=0;j<reader.maxDoc();j++) {
+ if (delDocs == null || !delDocs.get(j)) {
+ reader.document(j);
+ reader.getTermFreqVectors(j);
+ }
+ }
+ reader.close();
+ }
+
+ dir.close();
+ }
+ }
+
+ // Runs test, with one thread, using the specific failure
+ // to trigger an IOException
+ public void _testSingleThreadFailure(MockDirectoryWrapper.Failure failure) throws IOException {
+ MockDirectoryWrapper dir = newDirectory();
+
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer())
+ .setMaxBufferedDocs(2).setMergeScheduler(new ConcurrentMergeScheduler()));
+ final Document doc = new Document();
+ doc.add(newField("field", "aaa bbb ccc ddd eee fff ggg hhh iii jjj", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
+
+ for(int i=0;i<6;i++)
+ writer.addDocument(doc);
+
+ dir.failOn(failure);
+ failure.setDoFail();
+ try {
+ writer.addDocument(doc);
+ writer.addDocument(doc);
+ writer.commit();
+ fail("did not hit exception");
+ } catch (IOException ioe) {
+ }
+ failure.clearDoFail();
+ writer.addDocument(doc);
+ writer.close(false);
+ dir.close();
+ }
+
+ // Throws IOException during FieldsWriter.flushDocument and during DocumentsWriter.abort
+ private static class FailOnlyOnAbortOrFlush extends MockDirectoryWrapper.Failure {
+ private boolean onlyOnce;
+ public FailOnlyOnAbortOrFlush(boolean onlyOnce) {
+ this.onlyOnce = onlyOnce;
+ }
+ @Override
+ public void eval(MockDirectoryWrapper dir) throws IOException {
+ if (doFail) {
+ StackTraceElement[] trace = new Exception().getStackTrace();
+ boolean sawAbortOrFlushDoc = false;
+ boolean sawClose = false;
+ for (int i = 0; i < trace.length; i++) {
+ if ("abort".equals(trace[i].getMethodName()) ||
- "flushDocument".equals(trace[i].getMethodName())) {
++ "finishDocument".equals(trace[i].getMethodName())) {
+ sawAbortOrFlushDoc = true;
+ }
+ if ("close".equals(trace[i].getMethodName())) {
+ sawClose = true;
+ }
+ }
+ if (sawAbortOrFlushDoc && !sawClose) {
+ if (onlyOnce)
+ doFail = false;
+ //System.out.println(Thread.currentThread().getName() + ": now fail");
+ //new Throwable().printStackTrace(System.out);
+ throw new IOException("now failing on purpose");
+ }
+ }
+ }
+ }
+
+
+
+ // LUCENE-1130: make sure initial IOException, and then 2nd
+ // IOException during rollback(), is OK:
+ public void testIOExceptionDuringAbort() throws IOException {
+ _testSingleThreadFailure(new FailOnlyOnAbortOrFlush(false));
+ }
+
+ // LUCENE-1130: make sure initial IOException, and then 2nd
+ // IOException during rollback(), is OK:
+ public void testIOExceptionDuringAbortOnlyOnce() throws IOException {
+ _testSingleThreadFailure(new FailOnlyOnAbortOrFlush(true));
+ }
+
+ // LUCENE-1130: make sure initial IOException, and then 2nd
+ // IOException during rollback(), with multiple threads, is OK:
+ public void testIOExceptionDuringAbortWithThreads() throws Exception {
+ _testMultipleThreadsFailure(new FailOnlyOnAbortOrFlush(false));
+ }
+
+ // LUCENE-1130: make sure initial IOException, and then 2nd
+ // IOException during rollback(), with multiple threads, is OK:
+ public void testIOExceptionDuringAbortWithThreadsOnlyOnce() throws Exception {
+ _testMultipleThreadsFailure(new FailOnlyOnAbortOrFlush(true));
+ }
+
+ // Throws IOException during DocumentsWriter.writeSegment
+ private static class FailOnlyInWriteSegment extends MockDirectoryWrapper.Failure {
+ private boolean onlyOnce;
+ public FailOnlyInWriteSegment(boolean onlyOnce) {
+ this.onlyOnce = onlyOnce;
+ }
+ @Override
+ public void eval(MockDirectoryWrapper dir) throws IOException {
+ if (doFail) {
+ StackTraceElement[] trace = new Exception().getStackTrace();
+ for (int i = 0; i < trace.length; i++) {
+ if ("flush".equals(trace[i].getMethodName()) && "org.apache.lucene.index.DocFieldProcessor".equals(trace[i].getClassName())) {
+ if (onlyOnce)
+ doFail = false;
+ throw new IOException("now failing on purpose");
+ }
+ }
+ }
+ }
+ }
+
+ // LUCENE-1130: test IOException in writeSegment
+ public void testIOExceptionDuringWriteSegment() throws IOException {
+ _testSingleThreadFailure(new FailOnlyInWriteSegment(false));
+ }
+
+ // LUCENE-1130: test IOException in writeSegment
+ public void testIOExceptionDuringWriteSegmentOnlyOnce() throws IOException {
+ _testSingleThreadFailure(new FailOnlyInWriteSegment(true));
+ }
+
+ // LUCENE-1130: test IOException in writeSegment, with threads
+ public void testIOExceptionDuringWriteSegmentWithThreads() throws Exception {
+ _testMultipleThreadsFailure(new FailOnlyInWriteSegment(false));
+ }
+
+ // LUCENE-1130: test IOException in writeSegment, with threads
+ public void testIOExceptionDuringWriteSegmentWithThreadsOnlyOnce() throws Exception {
+ _testMultipleThreadsFailure(new FailOnlyInWriteSegment(true));
+ }
+ }
diff --cc lucene/src/test/org/apache/lucene/index/TestLazyBug.java
index fc8ccb32871,58681ab847f..b5466a952ae
--- a/lucene/src/test/org/apache/lucene/index/TestLazyBug.java
+++ b/lucene/src/test/org/apache/lucene/index/TestLazyBug.java
@@@ -36,7 -28,7 +28,7 @@@ import org.apache.lucene.util.LuceneTes
/**
-- * Test demonstrating EOF bug on the last field of the last doc
++ * Test demonstrating EOF bug on the last field of the last doc
* if other docs have allready been accessed.
*/
public class TestLazyBug extends LuceneTestCase {
@@@ -54,10 -46,10 +46,10 @@@
"this string is a bigger string, mary had a little lamb, little lamb, little lamb!"
};
- private static Set<String> dataset = new HashSet<String>(Arrays.asList(data));
-
+ private static Set<String> dataset = asSet(data);
-
++
private static String MAGIC_FIELD = "f"+(NUM_FIELDS/3);
--
++
private static FieldSelector SELECTOR = new FieldSelector() {
public FieldSelectorResult accept(String f) {
if (f.equals(MAGIC_FIELD)) {
@@@ -66,23 -58,22 +58,21 @@@
return FieldSelectorResult.LAZY_LOAD;
}
};
--
- private Directory makeIndex() throws RuntimeException {
- Directory dir = new RAMDirectory();
- private Directory makeIndex() throws Exception {
++
++ private Directory makeIndex() throws Exception {
+ Directory dir = newDirectory();
try {
- Random r = newRandom();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()));
LogMergePolicy lmp = (LogMergePolicy) writer.getConfig().getMergePolicy();
lmp.setUseCompoundFile(false);
-
-
for (int d = 1; d <= NUM_DOCS; d++) {
Document doc = new Document();
for (int f = 1; f <= NUM_FIELDS; f++ ) {
- doc.add(new Field("f"+f,
- doc.add(newField("f"+f,
-- data[f % data.length]
- + '#' + data[r.nextInt(data.length)],
- + '#' + data[random.nextInt(data.length)],
-- Field.Store.YES,
++ doc.add(newField("f"+f,
++ data[f % data.length]
++ + '#' + data[random.nextInt(data.length)],
++ Field.Store.YES,
Field.Index.ANALYZED));
}
writer.addDocument(doc);
@@@ -93,14 -84,14 +83,14 @@@
}
return dir;
}
--
++
public void doTest(int[] docs) throws Exception {
Directory dir = makeIndex();
IndexReader reader = IndexReader.open(dir, true);
for (int i = 0; i < docs.length; i++) {
Document d = reader.document(docs[i], SELECTOR);
d.get(MAGIC_FIELD);
--
++
List<Fieldable> fields = d.getFields();
for (Iterator<Fieldable> fi = fields.iterator(); fi.hasNext(); ) {
Fieldable f=null;
@@@ -110,7 -101,7 +100,7 @@@
String fval = f.stringValue();
assertNotNull(docs[i]+" FIELD: "+fname, fval);
String[] vals = fval.split("#");
-- if (!dataset.contains(vals[0]) || !dataset.contains(vals[1])) {
++ if (!dataset.contains(vals[0]) || !dataset.contains(vals[1])) {
fail("FIELD:"+fname+",VAL:"+fval);
}
} catch (Exception e) {
@@@ -124,7 -116,7 +115,7 @@@
public void testLazyWorks() throws Exception {
doTest(new int[] { 399 });
}
--
++
public void testLazyAlsoWorks() throws Exception {
doTest(new int[] { 399, 150 });
}
diff --cc lucene/src/test/org/apache/lucene/index/TestLazyProxSkipping.java
index 72a3c2d1353,fd1dc5647a6..257718cecdd
--- a/lucene/src/test/org/apache/lucene/index/TestLazyProxSkipping.java
+++ b/lucene/src/test/org/apache/lucene/index/TestLazyProxSkipping.java
@@@ -39,7 -42,7 +42,7 @@@ import org.apache.lucene.util.BytesRef
public class TestLazyProxSkipping extends LuceneTestCase {
private Searcher searcher;
private int seeksCounter = 0;
--
++
private String field = "tokens";
private String term1 = "xx";
private String term2 = "yy";
@@@ -55,14 -62,19 +62,19 @@@
}
return ii;
}
-
++
}
--
++
private void createIndex(int numHits) throws IOException {
int numDocs = 500;
--
- Directory directory = new SeekCountingDirectory();
- IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(10));
- ((LogMergePolicy) writer.getConfig().getMergePolicy()).setUseCompoundFile(false);
++
+ Directory directory = new SeekCountingDirectory(new RAMDirectory());
+ IndexWriter writer = new IndexWriter(
+ directory,
+ newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(MockTokenizer.WHITESPACE, true, false)).
+ setMaxBufferedDocs(10).
+ setMergePolicy(newLogMergePolicy(false))
+ );
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
String content;
@@@ -77,54 -89,56 +89,56 @@@
content = this.term3 + " " + this.term2;
}
- doc.add(new Field(this.field, content, Field.Store.YES, Field.Index.ANALYZED));
+ doc.add(newField(this.field, content, Field.Store.YES, Field.Index.ANALYZED));
writer.addDocument(doc);
}
--
++
// make sure the index has only a single segment
writer.optimize();
writer.close();
-
- SegmentReader reader = SegmentReader.getOnlySegmentReader(directory);
- this.searcher = new IndexSearcher(reader);
+ SegmentReader reader = getOnlySegmentReader(IndexReader.open(directory, false));
+
- this.searcher = new IndexSearcher(reader);
++ this.searcher = new IndexSearcher(reader);
}
--
++
private ScoreDoc[] search() throws IOException {
// create PhraseQuery "term1 term2" and search
PhraseQuery pq = new PhraseQuery();
pq.add(new Term(this.field, this.term1));
pq.add(new Term(this.field, this.term2));
-- return this.searcher.search(pq, null, 1000).scoreDocs;
++ return this.searcher.search(pq, null, 1000).scoreDocs;
}
--
++
private void performTest(int numHits) throws IOException {
createIndex(numHits);
this.seeksCounter = 0;
ScoreDoc[] hits = search();
// verify that the right number of docs was found
assertEquals(numHits, hits.length);
--
++
// check if the number of calls of seek() does not exceed the number of hits
assertTrue(this.seeksCounter > 0);
assertTrue("seeksCounter=" + this.seeksCounter + " numHits=" + numHits, this.seeksCounter <= numHits + 1);
}
-
-
++
public void testLazySkipping() throws IOException {
- // test whether only the minimum amount of seeks() are performed
+ assumeFalse("This test cannot run with SimpleText codec", CodecProvider.getDefault().getFieldCodec(this.field).equals("SimpleText"));
+ // test whether only the minimum amount of seeks()
+ // are performed
performTest(5);
performTest(10);
}
--
++
public void testSeek() throws IOException {
- Directory directory = new RAMDirectory();
- IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
+ Directory directory = newDirectory();
+ IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()));
for (int i = 0; i < 10; i++) {
Document doc = new Document();
- doc.add(new Field(this.field, "a b", Field.Store.YES, Field.Index.ANALYZED));
+ doc.add(newField(this.field, "a b", Field.Store.YES, Field.Index.ANALYZED));
writer.addDocument(doc);
}
--
++
writer.close();
IndexReader reader = IndexReader.open(directory, true);
@@@ -149,56 -163,57 +163,57 @@@
assertEquals(tp.docID(), i);
assertEquals(tp.nextPosition(), 0);
}
-
-
+ reader.close();
+ directory.close();
-
++
}
--
++
// Simply extends IndexInput in a way that we are able to count the number
// of invocations of seek()
class SeeksCountingStream extends IndexInput {
-- private IndexInput input;
--
--
++ private IndexInput input;
++
++
SeeksCountingStream(IndexInput input) {
this.input = input;
-- }
--
++ }
++
@Override
public byte readByte() throws IOException {
return this.input.readByte();
}
--
++
@Override
public void readBytes(byte[] b, int offset, int len) throws IOException {
-- this.input.readBytes(b, offset, len);
++ this.input.readBytes(b, offset, len);
}
--
++
@Override
public void close() throws IOException {
this.input.close();
}
--
++
@Override
public long getFilePointer() {
return this.input.getFilePointer();
}
--
++
@Override
public void seek(long pos) throws IOException {
TestLazyProxSkipping.this.seeksCounter++;
this.input.seek(pos);
}
--
++
@Override
public long length() {
return this.input.length();
}
--
++
@Override
public Object clone() {
return new SeeksCountingStream((IndexInput) this.input.clone());
}
--
++
}
}
diff --cc lucene/src/test/org/apache/lucene/index/TestNRTReaderWithThreads.java
index 8f2809ceb09,b544f027126..6cf41636a25
--- a/lucene/src/test/org/apache/lucene/index/TestNRTReaderWithThreads.java
+++ b/lucene/src/test/org/apache/lucene/index/TestNRTReaderWithThreads.java
@@@ -42,7 -43,7 +43,7 @@@ public class TestNRTReaderWithThreads e
indexThreads[x] = new RunThread(x % 2, writer);
indexThreads[x].setName("Thread " + x);
indexThreads[x].start();
-- }
++ }
long startTime = System.currentTimeMillis();
long duration = 1000;
while ((System.currentTimeMillis() - startTime) < duration) {
@@@ -75,7 -76,8 +76,8 @@@
int delCount = 0;
int addCount = 0;
int type;
+ final Random r = new Random(random.nextLong());
-
+
public RunThread(int type, IndexWriter writer) {
this.type = type;
this.writer = writer;
diff --cc lucene/src/test/org/apache/lucene/index/TestNRTThreads.java
index 00000000000,39ae987f383..5aa6f92ab9d
mode 000000,100644..100644
--- a/lucene/src/test/org/apache/lucene/index/TestNRTThreads.java
+++ b/lucene/src/test/org/apache/lucene/index/TestNRTThreads.java
@@@ -1,0 -1,369 +1,369 @@@
+ 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.File;
+ import java.io.IOException;
+ import java.util.ArrayList;
+ import java.util.Collections;
+ import java.util.List;
+ import java.util.Set;
+ import java.util.concurrent.atomic.AtomicBoolean;
+ import java.util.concurrent.atomic.AtomicInteger;
+
+ import org.apache.lucene.analysis.MockAnalyzer;
+ import org.apache.lucene.document.Document;
+ import org.apache.lucene.index.codecs.CodecProvider;
+ import org.apache.lucene.search.IndexSearcher;
+ import org.apache.lucene.search.PhraseQuery;
+ import org.apache.lucene.search.Query;
+ import org.apache.lucene.search.Sort;
+ import org.apache.lucene.search.SortField;
+ import org.apache.lucene.search.TermQuery;
+ import org.apache.lucene.search.TopDocs;
+ import org.apache.lucene.store.FSDirectory;
+ import org.apache.lucene.store.MockDirectoryWrapper;
+ import org.apache.lucene.util.Bits;
+ import org.apache.lucene.util.BytesRef;
+ import org.apache.lucene.util.LineFileDocs;
+ import org.apache.lucene.util.LuceneTestCase;
+ import org.apache.lucene.util._TestUtil;
+ import org.junit.Test;
+
+ import static org.junit.Assert.*;
+ import static org.junit.Assume.*;
+
+ // TODO
+ // - mix in optimize, addIndexes
+ // - randomoly mix in non-congruent docs
+
+ public class TestNRTThreads extends LuceneTestCase {
+
+ @Test
+ public void testNRTThreads() throws Exception {
+
+ final long t0 = System.currentTimeMillis();
+
+ if (CodecProvider.getDefault().getDefaultFieldCodec().equals("SimpleText")) {
+ // no
+ CodecProvider.getDefault().setDefaultFieldCodec("Standard");
+ }
+
+ final LineFileDocs docs = new LineFileDocs(true);
+ final File tempDir = _TestUtil.getTempDir("nrtopenfiles");
+ final MockDirectoryWrapper dir = new MockDirectoryWrapper(random, FSDirectory.open(tempDir));
+ final IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer());
+ conf.setMergedSegmentWarmer(new IndexWriter.IndexReaderWarmer() {
+ @Override
+ public void warm(IndexReader reader) throws IOException {
+ if (VERBOSE) {
+ System.out.println("TEST: now warm merged reader=" + reader);
+ }
+ final int maxDoc = reader.maxDoc();
+ final Bits delDocs = reader.getDeletedDocs();
+ int sum = 0;
+ final int inc = Math.max(1, maxDoc/50);
+ for(int docID=0;docID<maxDoc;docID += inc) {
+ if (delDocs == null || !delDocs.get(docID)) {
+ final Document doc = reader.document(docID);
+ sum += doc.getFields().size();
+ }
+ }
+
+ sum += new IndexSearcher(reader).search(new TermQuery(new Term("body", "united")), 10).totalHits;
+
+ if (VERBOSE) {
+ System.out.println("TEST: warm visited " + sum + " fields");
+ }
+ }
+ });
+
+ final IndexWriter writer = new IndexWriter(dir, conf);
+ if (VERBOSE) {
+ writer.setInfoStream(System.out);
+ }
+ MergeScheduler ms = writer.getConfig().getMergeScheduler();
+ if (ms instanceof ConcurrentMergeScheduler) {
+ // try to keep max file open count down
+ ((ConcurrentMergeScheduler) ms).setMaxThreadCount(1);
+ ((ConcurrentMergeScheduler) ms).setMaxMergeCount(1);
+ }
+ LogMergePolicy lmp = (LogMergePolicy) writer.getConfig().getMergePolicy();
+ if (lmp.getMergeFactor() > 5) {
+ lmp.setMergeFactor(5);
+ }
+
+ final int NUM_INDEX_THREADS = 2;
+ final int NUM_SEARCH_THREADS = 3;
+ final int RUN_TIME_SEC = LuceneTestCase.TEST_NIGHTLY ? 300 : 5;
+
+ final AtomicBoolean failed = new AtomicBoolean();
+ final AtomicInteger addCount = new AtomicInteger();
+ final AtomicInteger delCount = new AtomicInteger();
+
+ final List<String> delIDs = Collections.synchronizedList(new ArrayList<String>());
+
+ final long stopTime = System.currentTimeMillis() + RUN_TIME_SEC*1000;
+ Thread[] threads = new Thread[NUM_INDEX_THREADS];
+ for(int thread=0;thread<NUM_INDEX_THREADS;thread++) {
+ threads[thread] = new Thread() {
+ @Override
+ public void run() {
+ final List<String> toDeleteIDs = new ArrayList<String>();
+ while(System.currentTimeMillis() < stopTime && !failed.get()) {
+ try {
+ Document doc = docs.nextDoc();
+ if (doc == null) {
+ break;
+ }
+ if (random.nextBoolean()) {
+ if (VERBOSE) {
+ //System.out.println(Thread.currentThread().getName() + ": add doc id:" + doc.get("id"));
+ }
+ writer.addDocument(doc);
+ } else {
+ // we use update but it never replaces a
+ // prior doc
+ if (VERBOSE) {
+ //System.out.println(Thread.currentThread().getName() + ": update doc id:" + doc.get("id"));
+ }
+ writer.updateDocument(new Term("id", doc.get("id")), doc);
+ }
+ if (random.nextInt(5) == 3) {
+ if (VERBOSE) {
+ //System.out.println(Thread.currentThread().getName() + ": buffer del id:" + doc.get("id"));
+ }
+ toDeleteIDs.add(doc.get("id"));
+ }
+ if (random.nextInt(50) == 17) {
+ if (VERBOSE) {
+ System.out.println(Thread.currentThread().getName() + ": apply " + toDeleteIDs.size() + " deletes");
+ }
+ for(String id : toDeleteIDs) {
+ writer.deleteDocuments(new Term("id", id));
+ }
+ final int count = delCount.addAndGet(toDeleteIDs.size());
+ if (VERBOSE) {
+ System.out.println(Thread.currentThread().getName() + ": tot " + count + " deletes");
+ }
+ delIDs.addAll(toDeleteIDs);
+ toDeleteIDs.clear();
+ }
+ addCount.getAndIncrement();
+ } catch (Exception exc) {
+ System.out.println(Thread.currentThread().getName() + ": hit exc");
+ exc.printStackTrace();
+ failed.set(true);
+ throw new RuntimeException(exc);
+ }
+ }
+ if (VERBOSE) {
+ System.out.println(Thread.currentThread().getName() + ": indexing done");
+ }
+ }
+ };
+ threads[thread].setDaemon(true);
+ threads[thread].start();
+ }
+
+ if (VERBOSE) {
+ System.out.println("TEST: DONE start indexing threads [" + (System.currentTimeMillis()-t0) + " ms]");
+ }
+
+ // let index build up a bit
+ Thread.sleep(100);
+
+ IndexReader r = IndexReader.open(writer);
+ boolean any = false;
+
+ // silly starting guess:
+ final AtomicInteger totTermCount = new AtomicInteger(100);
+
+ while(System.currentTimeMillis() < stopTime && !failed.get()) {
+ if (random.nextBoolean()) {
+ if (VERBOSE) {
+ System.out.println("TEST: now reopen r=" + r);
+ }
+ final IndexReader r2 = r.reopen();
+ if (r != r2) {
+ r.close();
+ r = r2;
+ }
+ } else {
+ if (VERBOSE) {
+ System.out.println("TEST: now close reader=" + r);
+ }
+ r.close();
+ writer.commit();
+ final Set<String> openDeletedFiles = dir.getOpenDeletedFiles();
+ if (openDeletedFiles.size() > 0) {
+ System.out.println("OBD files: " + openDeletedFiles);
+ }
+ any |= openDeletedFiles.size() > 0;
+ //assertEquals("open but deleted: " + openDeletedFiles, 0, openDeletedFiles.size());
+ if (VERBOSE) {
+ System.out.println("TEST: now open");
+ }
+ r = IndexReader.open(writer);
+ }
+ if (VERBOSE) {
+ System.out.println("TEST: got new reader=" + r);
+ }
+ //System.out.println("numDocs=" + r.numDocs() + "
+ //openDelFileCount=" + dir.openDeleteFileCount());
+
+ smokeTestReader(r);
+
+ if (r.numDocs() > 0) {
+
+ final IndexSearcher s = new IndexSearcher(r);
+
+ // run search threads
+ final long searchStopTime = System.currentTimeMillis() + 500;
+ final Thread[] searchThreads = new Thread[NUM_SEARCH_THREADS];
+ final AtomicInteger totHits = new AtomicInteger();
+ for(int thread=0;thread<NUM_SEARCH_THREADS;thread++) {
+ searchThreads[thread] = new Thread() {
+ @Override
+ public void run() {
+ try {
+ TermsEnum termsEnum = MultiFields.getTerms(s.getIndexReader(), "body").iterator();
+ int seenTermCount = 0;
+ int shift;
+ int trigger;
+ if (totTermCount.get() == 0) {
+ shift = 0;
+ trigger = 1;
+ } else {
+ shift = random.nextInt(totTermCount.get()/10);
+ trigger = totTermCount.get()/10;
+ }
+ while(System.currentTimeMillis() < searchStopTime) {
+ BytesRef term = termsEnum.next();
+ if (term == null) {
+ if (seenTermCount == 0) {
+ break;
+ }
+ totTermCount.set(seenTermCount);
+ seenTermCount = 0;
+ trigger = totTermCount.get()/10;
+ //System.out.println("trigger " + trigger);
+ shift = random.nextInt(totTermCount.get()/10);
+ termsEnum.seek(new BytesRef(""));
+ continue;
+ }
+ seenTermCount++;
+ // search 10 terms
+ if (trigger == 0) {
+ trigger = 1;
+ }
+ if ((seenTermCount + shift) % trigger == 0) {
+ //if (VERBOSE) {
+ //System.out.println(Thread.currentThread().getName() + " now search body:" + term.utf8ToString());
+ //}
+ totHits.addAndGet(runQuery(s, new TermQuery(new Term("body", term))));
+ }
+ }
+ if (VERBOSE) {
+ System.out.println(Thread.currentThread().getName() + ": search done");
+ }
+ } catch (Throwable t) {
+ failed.set(true);
+ t.printStackTrace(System.out);
+ throw new RuntimeException(t);
+ }
+ }
+ };
+ searchThreads[thread].setDaemon(true);
+ searchThreads[thread].start();
+ }
+
+ for(int thread=0;thread<NUM_SEARCH_THREADS;thread++) {
+ searchThreads[thread].join();
+ }
+
+ if (VERBOSE) {
+ System.out.println("TEST: DONE search: totHits=" + totHits);
+ }
+ } else {
+ Thread.sleep(100);
+ }
+ }
+
+ if (VERBOSE) {
+ System.out.println("TEST: all searching done [" + (System.currentTimeMillis()-t0) + " ms]");
+ }
+
+ //System.out.println("numDocs=" + r.numDocs() + " openDelFileCount=" + dir.openDeleteFileCount());
+ r.close();
+ final Set<String> openDeletedFiles = dir.getOpenDeletedFiles();
+ if (openDeletedFiles.size() > 0) {
+ System.out.println("OBD files: " + openDeletedFiles);
+ }
+ any |= openDeletedFiles.size() > 0;
+
+ assertFalse("saw non-zero open-but-deleted count", any);
+ if (VERBOSE) {
+ System.out.println("TEST: now join");
+ }
+ for(int thread=0;thread<NUM_INDEX_THREADS;thread++) {
+ threads[thread].join();
+ }
+ if (VERBOSE) {
+ System.out.println("TEST: done join [" + (System.currentTimeMillis()-t0) + " ms]; addCount=" + addCount + " delCount=" + delCount);
+ }
-
++
+ final IndexReader r2 = writer.getReader();
+ final IndexSearcher s = new IndexSearcher(r2);
+ for(String id : delIDs) {
+ final TopDocs hits = s.search(new TermQuery(new Term("id", id)), 1);
+ if (hits.totalHits != 0) {
+ fail("doc id=" + id + " is supposed to be deleted, but got docID=" + hits.scoreDocs[0].doc);
+ }
+ }
+ assertEquals("index=" + writer.segString() + " addCount=" + addCount + " delCount=" + delCount, addCount.get() - delCount.get(), r2.numDocs());
+ r2.close();
+
+ writer.commit();
+ assertEquals("index=" + writer.segString() + " addCount=" + addCount + " delCount=" + delCount, addCount.get() - delCount.get(), writer.numDocs());
-
++
+ writer.close(false);
+ dir.close();
+ _TestUtil.rmDir(tempDir);
+ docs.close();
+ if (VERBOSE) {
+ System.out.println("TEST: done [" + (System.currentTimeMillis()-t0) + " ms]");
+ }
+ }
+
+ private int runQuery(IndexSearcher s, Query q) throws Exception {
+ s.search(q, 10);
+ return s.search(q, null, 10, new Sort(new SortField("title", SortField.STRING))).totalHits;
+ }
+
+ private void smokeTestReader(IndexReader r) throws Exception {
+ IndexSearcher s = new IndexSearcher(r);
+ runQuery(s, new TermQuery(new Term("body", "united")));
+ runQuery(s, new TermQuery(new Term("titleTokenized", "states")));
+ PhraseQuery pq = new PhraseQuery();
+ pq.add(new Term("body", "united"));
+ pq.add(new Term("body", "states"));
+ runQuery(s, pq);
+ s.close();
+ }
+ }
diff --cc lucene/src/test/org/apache/lucene/index/TestPerFieldCodecSupport.java
index 00000000000,0062ea973e3..8c7222ec17f
mode 000000,100644..100644
--- a/lucene/src/test/org/apache/lucene/index/TestPerFieldCodecSupport.java
+++ b/lucene/src/test/org/apache/lucene/index/TestPerFieldCodecSupport.java
@@@ -1,0 -1,296 +1,296 @@@
+ 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.List;
+
+ import org.apache.lucene.analysis.MockAnalyzer;
+ import org.apache.lucene.document.Document;
+ import org.apache.lucene.document.Field;
+ import org.apache.lucene.document.Field.Index;
+ import org.apache.lucene.index.CheckIndex.Status;
+ import org.apache.lucene.index.CheckIndex.Status.SegmentInfoStatus;
+ import org.apache.lucene.index.IndexWriterConfig.OpenMode;
+ import org.apache.lucene.index.codecs.Codec;
+ import org.apache.lucene.index.codecs.CodecProvider;
+ import org.apache.lucene.index.codecs.mockintblock.MockFixedIntBlockCodec;
+ import org.apache.lucene.index.codecs.mockintblock.MockVariableIntBlockCodec;
+ import org.apache.lucene.index.codecs.mocksep.MockSepCodec;
+ import org.apache.lucene.index.codecs.pulsing.PulsingCodec;
+ import org.apache.lucene.index.codecs.simpletext.SimpleTextCodec;
+ import org.apache.lucene.index.codecs.standard.StandardCodec;
+ import org.apache.lucene.search.IndexSearcher;
+ import org.apache.lucene.search.TermQuery;
+ import org.apache.lucene.search.TopDocs;
+ import org.apache.lucene.store.Directory;
+ import org.apache.lucene.util.LuceneTestCase;
+ import org.apache.lucene.util._TestUtil;
+ import org.junit.Test;
+
+ /**
- *
++ *
+ *
+ */
+ public class TestPerFieldCodecSupport extends LuceneTestCase {
+
+ private IndexWriter newWriter(Directory dir, IndexWriterConfig conf)
+ throws IOException {
+ LogDocMergePolicy logByteSizeMergePolicy = new LogDocMergePolicy();
+ logByteSizeMergePolicy.setUseCompoundFile(false); // make sure we use plain
+ // files
+ conf.setMergePolicy(logByteSizeMergePolicy);
+
+ final IndexWriter writer = new IndexWriter(dir, conf);
+ return writer;
+ }
+
+ private void addDocs(IndexWriter writer, int numDocs) throws IOException {
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ doc.add(newField("content", "aaa", Field.Store.NO, Field.Index.ANALYZED));
+ writer.addDocument(doc);
+ }
+ }
+
+ private void addDocs2(IndexWriter writer, int numDocs) throws IOException {
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ doc.add(newField("content", "bbb", Field.Store.NO, Field.Index.ANALYZED));
+ writer.addDocument(doc);
+ }
+ }
+
+ private void addDocs3(IndexWriter writer, int numDocs) throws IOException {
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ doc.add(newField("content", "ccc", Field.Store.NO, Field.Index.ANALYZED));
+ doc.add(newField("id", "" + i, Field.Store.YES, Field.Index.ANALYZED));
+ writer.addDocument(doc);
+ }
+ }
+
+ /*
+ * Test is hetrogenous index segements are merge sucessfully
+ */
+ @Test
+ public void testMergeUnusedPerFieldCodec() throws IOException {
+ Directory dir = newDirectory();
+ CodecProvider provider = new MockCodecProvider();
+ IndexWriterConfig iwconf = newIndexWriterConfig(TEST_VERSION_CURRENT,
+ new MockAnalyzer()).setOpenMode(OpenMode.CREATE).setCodecProvider(
+ provider);
+ IndexWriter writer = newWriter(dir, iwconf);
+ addDocs(writer, 10);
+ writer.commit();
+ addDocs3(writer, 10);
+ writer.commit();
+ addDocs2(writer, 10);
+ writer.commit();
+ assertEquals(30, writer.maxDoc());
+ _TestUtil.checkIndex(dir, provider);
+ writer.optimize();
+ assertEquals(30, writer.maxDoc());
+ writer.close();
+ dir.close();
+ }
+
+ /*
+ * Test is hetrogenous index segements are merge sucessfully
+ */
+ @Test
+ public void testChangeCodecAndMerge() throws IOException {
+ Directory dir = newDirectory();
+ CodecProvider provider = new MockCodecProvider();
+ IndexWriterConfig iwconf = newIndexWriterConfig(TEST_VERSION_CURRENT,
+ new MockAnalyzer()).setOpenMode(OpenMode.CREATE).setCodecProvider(provider);
+ iwconf.setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
+ ((LogMergePolicy) iwconf.getMergePolicy()).setMergeFactor(10);
+ IndexWriter writer = newWriter(dir, iwconf);
+
+ addDocs(writer, 10);
+ writer.commit();
+ assertQuery(new Term("content", "aaa"), dir, 10, provider);
+ addDocs3(writer, 10);
+ writer.commit();
+ writer.close();
+
+ assertQuery(new Term("content", "ccc"), dir, 10, provider);
+ assertQuery(new Term("content", "aaa"), dir, 10, provider);
+ assertCodecPerField(_TestUtil.checkIndex(dir, provider), "content",
+ provider.lookup("MockSep"));
+
+ iwconf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer())
+ .setOpenMode(OpenMode.APPEND).setCodecProvider(provider);
+ ((LogMergePolicy) iwconf.getMergePolicy()).setUseCompoundFile(false);
+ ((LogMergePolicy) iwconf.getMergePolicy()).setMergeFactor(10);
+ iwconf.setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
+
+ provider = new MockCodecProvider2(); // uses standard for field content
+ iwconf.setCodecProvider(provider);
+ writer = newWriter(dir, iwconf);
+ // swap in new codec for currently written segments
+ addDocs2(writer, 10);
+ writer.commit();
+ Codec origContentCodec = provider.lookup("MockSep");
+ Codec newContentCodec = provider.lookup("Standard");
+ assertHybridCodecPerField(_TestUtil.checkIndex(dir, provider), "content",
+ origContentCodec, origContentCodec, newContentCodec);
+ assertEquals(30, writer.maxDoc());
+ assertQuery(new Term("content", "bbb"), dir, 10, provider);
+ assertQuery(new Term("content", "ccc"), dir, 10, provider);
+ assertQuery(new Term("content", "aaa"), dir, 10, provider);
+
+ addDocs2(writer, 10);
+ writer.commit();
+ assertQuery(new Term("content", "ccc"), dir, 10, provider);
+ assertQuery(new Term("content", "bbb"), dir, 20, provider);
+ assertQuery(new Term("content", "aaa"), dir, 10, provider);
+ assertEquals(40, writer.maxDoc());
+
+ writer.optimize();
+ assertEquals(40, writer.maxDoc());
+ writer.close();
+ assertCodecPerFieldOptimized(_TestUtil.checkIndex(dir, provider),
+ "content", newContentCodec);
+ assertQuery(new Term("content", "ccc"), dir, 10, provider);
+ assertQuery(new Term("content", "bbb"), dir, 20, provider);
+ assertQuery(new Term("content", "aaa"), dir, 10, provider);
+
+ dir.close();
+ }
+
+ public void assertCodecPerFieldOptimized(Status checkIndex, String field,
+ Codec codec) {
+ assertEquals(1, checkIndex.segmentInfos.size());
+ final CodecProvider provider = checkIndex.segmentInfos.get(0).codec.provider;
+ assertEquals(codec, provider.lookup(provider.getFieldCodec(field)));
+
+ }
+
+ public void assertCodecPerField(Status checkIndex, String field, Codec codec) {
+ for (SegmentInfoStatus info : checkIndex.segmentInfos) {
+ final CodecProvider provider = info.codec.provider;
+ assertEquals(codec, provider.lookup(provider.getFieldCodec(field)));
+ }
+ }
+
+ public void assertHybridCodecPerField(Status checkIndex, String field,
+ Codec... codec) throws IOException {
+ List<SegmentInfoStatus> segmentInfos = checkIndex.segmentInfos;
+ assertEquals(segmentInfos.size(), codec.length);
+ for (int i = 0; i < codec.length; i++) {
+ SegmentCodecs codecInfo = segmentInfos.get(i).codec;
+ FieldInfos fieldInfos = new FieldInfos(checkIndex.dir, IndexFileNames
+ .segmentFileName(segmentInfos.get(i).name, "",
+ IndexFileNames.FIELD_INFOS_EXTENSION));
+ FieldInfo fieldInfo = fieldInfos.fieldInfo(field);
+ assertEquals("faild for segment index: " + i, codec[i],
+ codecInfo.codecs[fieldInfo.codecId]);
+ }
+ }
+
+ public void assertQuery(Term t, Directory dir, int num, CodecProvider codecs)
+ throws CorruptIndexException, IOException {
+ IndexReader reader = IndexReader.open(dir, null, true,
+ IndexReader.DEFAULT_TERMS_INDEX_DIVISOR, codecs);
+ IndexSearcher searcher = new IndexSearcher(reader);
+ TopDocs search = searcher.search(new TermQuery(t), num + 10);
+ assertEquals(num, search.totalHits);
+ searcher.close();
+ reader.close();
+
+ }
+
+ public static class MockCodecProvider extends CodecProvider {
+
+ public MockCodecProvider() {
+ StandardCodec standardCodec = new StandardCodec();
+ setDefaultFieldCodec(standardCodec.name);
+ SimpleTextCodec simpleTextCodec = new SimpleTextCodec();
+ MockSepCodec mockSepCodec = new MockSepCodec();
+ register(standardCodec);
+ register(mockSepCodec);
+ register(simpleTextCodec);
+ setFieldCodec("id", simpleTextCodec.name);
+ setFieldCodec("content", mockSepCodec.name);
+ }
+ }
+
+ public static class MockCodecProvider2 extends CodecProvider {
+
+ public MockCodecProvider2() {
+ StandardCodec standardCodec = new StandardCodec();
+ setDefaultFieldCodec(standardCodec.name);
+ SimpleTextCodec simpleTextCodec = new SimpleTextCodec();
+ MockSepCodec mockSepCodec = new MockSepCodec();
+ register(standardCodec);
+ register(mockSepCodec);
+ register(simpleTextCodec);
+ setFieldCodec("id", simpleTextCodec.name);
+ setFieldCodec("content", standardCodec.name);
+ }
+ }
+
+ /*
+ * Test per field codec support - adding fields with random codecs
+ */
+ @Test
+ public void testStressPerFieldCodec() throws IOException {
+ Directory dir = newDirectory(random);
+ Index[] indexValue = new Index[] { Index.ANALYZED, Index.ANALYZED_NO_NORMS,
+ Index.NOT_ANALYZED, Index.NOT_ANALYZED_NO_NORMS };
+ final int docsPerRound = 97;
+ for (int i = 0; i < 5; i++) {
+ CodecProvider provider = new CodecProvider();
+ Codec[] codecs = new Codec[] { new StandardCodec(),
+ new SimpleTextCodec(), new MockSepCodec(),
+ new PulsingCodec(1 + random.nextInt(10)),
+ new MockVariableIntBlockCodec(1 + random.nextInt(10)),
+ new MockFixedIntBlockCodec(1 + random.nextInt(10)) };
+ for (Codec codec : codecs) {
+ provider.register(codec);
+ }
+ for (int j = 0; j < 30 * RANDOM_MULTIPLIER; j++) {
+ provider.setFieldCodec("" + j, codecs[random.nextInt(codecs.length)].name);
+ }
+ IndexWriterConfig config = newIndexWriterConfig(random,
+ TEST_VERSION_CURRENT, new MockAnalyzer());
+ config.setOpenMode(OpenMode.CREATE_OR_APPEND);
+ config.setCodecProvider(provider);
+ IndexWriter writer = newWriter(dir, config);
+ for (int j = 0; j < docsPerRound; j++) {
+ final Document doc = new Document();
+ for (int k = 0; k < 30 * RANDOM_MULTIPLIER; k++) {
+ Field field = newField("" + k, _TestUtil
+ .randomRealisticUnicodeString(random, 128), indexValue[random
+ .nextInt(indexValue.length)]);
+ doc.add(field);
+ }
+ writer.addDocument(doc);
+ }
+ if (random.nextBoolean()) {
+ writer.optimize();
+ }
+ writer.commit();
+ assertEquals((i + 1) * docsPerRound, writer.maxDoc());
+ writer.close();
+ _TestUtil.checkIndex(dir, provider);
+ }
+ dir.close();
+ }
-}
++}
diff --cc lucene/src/test/org/apache/lucene/index/TestPerSegmentDeletes.java
index 00000000000,294f11058ae..e79308880a7
mode 000000,100644..100644
--- a/lucene/src/test/org/apache/lucene/index/TestPerSegmentDeletes.java
+++ b/lucene/src/test/org/apache/lucene/index/TestPerSegmentDeletes.java
@@@ -1,0 -1,293 +1,293 @@@
+ 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.List;
+ import java.util.Random;
+ import java.util.Set;
+
+ import org.apache.lucene.analysis.MockAnalyzer;
+ import org.apache.lucene.index.TermsEnum.SeekStatus;
+ import org.apache.lucene.store.Directory;
+ import org.apache.lucene.store.MockDirectoryWrapper;
+ import org.apache.lucene.store.RAMDirectory;
+ import org.apache.lucene.util.ArrayUtil;
+ import org.apache.lucene.util.Bits;
+ import org.apache.lucene.util.BytesRef;
+ import org.apache.lucene.util.LuceneTestCase;
+ import org.apache.lucene.util.Version;
+
+ public class TestPerSegmentDeletes extends LuceneTestCase {
+ public void testDeletes1() throws Exception {
+ //IndexWriter.debug2 = System.out;
+ Directory dir = new MockDirectoryWrapper(new Random(random.nextLong()), new RAMDirectory());
+ IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_CURRENT,
+ new MockAnalyzer());
+ iwc.setMergeScheduler(new SerialMergeScheduler());
+ iwc.setMaxBufferedDocs(5000);
+ iwc.setRAMBufferSizeMB(100);
+ RangeMergePolicy fsmp = new RangeMergePolicy(false);
+ iwc.setMergePolicy(fsmp);
+ IndexWriter writer = new IndexWriter(dir, iwc);
+ for (int x = 0; x < 5; x++) {
+ writer.addDocument(TestIndexWriterReader.createDocument(x, "1", 2));
+ //System.out.println("numRamDocs(" + x + ")" + writer.numRamDocs());
+ }
+ //System.out.println("commit1");
+ writer.commit();
+ assertEquals(1, writer.segmentInfos.size());
+ for (int x = 5; x < 10; x++) {
+ writer.addDocument(TestIndexWriterReader.createDocument(x, "2", 2));
+ //System.out.println("numRamDocs(" + x + ")" + writer.numRamDocs());
+ }
+ //System.out.println("commit2");
+ writer.commit();
+ assertEquals(2, writer.segmentInfos.size());
+
+ for (int x = 10; x < 15; x++) {
+ writer.addDocument(TestIndexWriterReader.createDocument(x, "3", 2));
+ //System.out.println("numRamDocs(" + x + ")" + writer.numRamDocs());
+ }
-
++
+ writer.deleteDocuments(new Term("id", "1"));
-
++
+ writer.deleteDocuments(new Term("id", "11"));
+
- // flushing without applying deletes means
++ // flushing without applying deletes means
+ // there will still be deletes in the segment infos
+ writer.flush(false, false);
+ assertTrue(writer.bufferedDeletes.any());
-
++
+ // get reader flushes pending deletes
+ // so there should not be anymore
+ IndexReader r1 = writer.getReader();
+ assertFalse(writer.bufferedDeletes.any());
+ r1.close();
-
++
+ // delete id:2 from the first segment
+ // merge segments 0 and 1
+ // which should apply the delete id:2
+ writer.deleteDocuments(new Term("id", "2"));
+ writer.flush(false, false);
+ fsmp.doMerge = true;
+ fsmp.start = 0;
+ fsmp.length = 2;
+ writer.maybeMerge();
-
++
+ assertEquals(2, writer.segmentInfos.size());
-
++
+ // id:2 shouldn't exist anymore because
+ // it's been applied in the merge and now it's gone
+ IndexReader r2 = writer.getReader();
+ int[] id2docs = toDocsArray(new Term("id", "2"), null, r2);
+ assertTrue(id2docs == null);
+ r2.close();
-
++
+ /**
+ // added docs are in the ram buffer
+ for (int x = 15; x < 20; x++) {
+ writer.addDocument(TestIndexWriterReader.createDocument(x, "4", 2));
+ System.out.println("numRamDocs(" + x + ")" + writer.numRamDocs());
+ }
+ assertTrue(writer.numRamDocs() > 0);
+ // delete from the ram buffer
+ writer.deleteDocuments(new Term("id", Integer.toString(13)));
-
++
+ Term id3 = new Term("id", Integer.toString(3));
-
++
+ // delete from the 1st segment
+ writer.deleteDocuments(id3);
-
++
+ assertTrue(writer.numRamDocs() > 0);
-
++
+ //System.out
+ // .println("segdels1:" + writer.docWriter.deletesToString());
-
++
+ //assertTrue(writer.docWriter.segmentDeletes.size() > 0);
-
++
+ // we cause a merge to happen
+ fsmp.doMerge = true;
+ fsmp.start = 0;
+ fsmp.length = 2;
+ System.out.println("maybeMerge "+writer.segmentInfos);
-
++
+ SegmentInfo info0 = writer.segmentInfos.get(0);
+ SegmentInfo info1 = writer.segmentInfos.get(1);
-
++
+ writer.maybeMerge();
+ System.out.println("maybeMerge after "+writer.segmentInfos);
+ // there should be docs in RAM
+ assertTrue(writer.numRamDocs() > 0);
-
++
+ // assert we've merged the 1 and 2 segments
+ // and still have a segment leftover == 2
+ assertEquals(2, writer.segmentInfos.size());
+ assertFalse(segThere(info0, writer.segmentInfos));
+ assertFalse(segThere(info1, writer.segmentInfos));
-
++
+ //System.out.println("segdels2:" + writer.docWriter.deletesToString());
-
++
+ //assertTrue(writer.docWriter.segmentDeletes.size() > 0);
-
++
+ IndexReader r = writer.getReader();
+ IndexReader r1 = r.getSequentialSubReaders()[0];
+ printDelDocs(r1.getDeletedDocs());
+ int[] docs = toDocsArray(id3, null, r);
+ System.out.println("id3 docs:"+Arrays.toString(docs));
+ // there shouldn't be any docs for id:3
+ assertTrue(docs == null);
+ r.close();
-
++
+ part2(writer, fsmp);
+ **/
+ // System.out.println("segdels2:"+writer.docWriter.segmentDeletes.toString());
+ //System.out.println("close");
+ writer.close();
+ dir.close();
+ }
-
++
+ /**
+ static boolean hasPendingDeletes(SegmentInfos infos) {
+ for (SegmentInfo info : infos) {
+ if (info.deletes.any()) {
+ return true;
+ }
+ }
+ return false;
+ }
+ **/
+ void part2(IndexWriter writer, RangeMergePolicy fsmp) throws Exception {
+ for (int x = 20; x < 25; x++) {
+ writer.addDocument(TestIndexWriterReader.createDocument(x, "5", 2));
+ //System.out.println("numRamDocs(" + x + ")" + writer.numRamDocs());
+ }
+ writer.flush(false, false);
+ for (int x = 25; x < 30; x++) {
+ writer.addDocument(TestIndexWriterReader.createDocument(x, "5", 2));
+ //System.out.println("numRamDocs(" + x + ")" + writer.numRamDocs());
+ }
+ writer.flush(false, false);
-
++
+ //System.out.println("infos3:"+writer.segmentInfos);
-
++
+ Term delterm = new Term("id", "8");
+ writer.deleteDocuments(delterm);
+ //System.out.println("segdels3:" + writer.docWriter.deletesToString());
-
++
+ fsmp.doMerge = true;
+ fsmp.start = 1;
+ fsmp.length = 2;
+ writer.maybeMerge();
-
- // deletes for info1, the newly created segment from the
++
++ // deletes for info1, the newly created segment from the
+ // merge should have no deletes because they were applied in
+ // the merge
+ //SegmentInfo info1 = writer.segmentInfos.get(1);
+ //assertFalse(exists(info1, writer.docWriter.segmentDeletes));
-
++
+ //System.out.println("infos4:"+writer.segmentInfos);
+ //System.out.println("segdels4:" + writer.docWriter.deletesToString());
+ }
-
++
+ boolean segThere(SegmentInfo info, SegmentInfos infos) {
+ for (SegmentInfo si : infos) {
- if (si.name.equals(info.name)) return true;
++ if (si.name.equals(info.name)) return true;
+ }
+ return false;
+ }
-
++
+ public static void printDelDocs(Bits bits) {
+ if (bits == null) return;
+ for (int x = 0; x < bits.length(); x++) {
+ System.out.println(x + ":" + bits.get(x));
+ }
+ }
-
++
+ public static int[] toDocsArray(Term term, Bits bits, IndexReader reader)
+ throws IOException {
+ Fields fields = MultiFields.getFields(reader);
+ Terms cterms = fields.terms(term.field);
+ TermsEnum ctermsEnum = cterms.iterator();
+ SeekStatus ss = ctermsEnum.seek(new BytesRef(term.text()), false);
+ if (ss.equals(SeekStatus.FOUND)) {
+ DocsEnum docsEnum = ctermsEnum.docs(bits, null);
+ return toArray(docsEnum);
+ }
+ return null;
+ }
-
++
+ public static int[] toArray(DocsEnum docsEnum) throws IOException {
+ List<Integer> docs = new ArrayList<Integer>();
+ while (docsEnum.nextDoc() != DocsEnum.NO_MORE_DOCS) {
+ int docID = docsEnum.docID();
+ docs.add(docID);
+ }
+ return ArrayUtil.toIntArray(docs);
+ }
-
++
+ public class RangeMergePolicy extends MergePolicy {
+ boolean doMerge = false;
+ int start;
+ int length;
-
++
+ private final boolean useCompoundFile;
-
++
+ private RangeMergePolicy(boolean useCompoundFile) {
+ this.useCompoundFile = useCompoundFile;
+ }
-
++
+ @Override
+ public void close() {}
-
++
+ public MergeSpecification findMerges(SegmentInfos segmentInfos)
+ throws CorruptIndexException, IOException {
+ MergeSpecification ms = new MergeSpecification();
+ if (doMerge) {
+ SegmentInfos mergeInfos = new SegmentInfos();
+ for (int x=start; x < (start+length); x++) {
+ mergeInfos.add(segmentInfos.get(x));
+ }
+ OneMerge om = new OneMerge(mergeInfos);
+ ms.add(om);
+ doMerge = false;
+ return ms;
+ }
+ return null;
+ }
-
++
+ @Override
+ public MergeSpecification findMergesForOptimize(SegmentInfos segmentInfos,
+ int maxSegmentCount, Set<SegmentInfo> segmentsToOptimize)
+ throws CorruptIndexException, IOException {
+ return null;
+ }
-
++
+ @Override
+ public MergeSpecification findMergesToExpungeDeletes(
+ SegmentInfos segmentInfos) throws CorruptIndexException, IOException {
+ return null;
+ }
-
++
+ @Override
+ public boolean useCompoundFile(SegmentInfos segments, SegmentInfo newSegment) {
+ return useCompoundFile;
+ }
+ }
+ }
diff --cc lucene/src/test/org/apache/lucene/index/TestSegmentMerger.java
index 36abeee5c15,618df0de0b4..01055716398
--- a/lucene/src/test/org/apache/lucene/index/TestSegmentMerger.java
+++ b/lucene/src/test/org/apache/lucene/index/TestSegmentMerger.java
@@@ -56,7 -53,17 +53,17 @@@ public class TestSegmentMerger extends
reader1 = SegmentReader.get(true, info1, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);
reader2 = SegmentReader.get(true, info2, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);
}
-
+
+ @Override
+ public void tearDown() throws Exception {
+ reader1.close();
+ reader2.close();
+ mergedDir.close();
+ merge1Dir.close();
+ merge2Dir.close();
+ super.tearDown();
+ }
+
public void test() {
assertTrue(mergedDir != null);
assertTrue(merge1Dir != null);
@@@ -64,18 -71,18 +71,17 @@@
assertTrue(reader1 != null);
assertTrue(reader2 != null);
}
--
-- public void testMerge() throws IOException {
- SegmentMerger merger = new SegmentMerger(mergedDir, IndexWriter.DEFAULT_TERM_INDEX_INTERVAL, mergedSegment, null, CodecProvider.getDefault(), null);
++
++ public void testMerge() throws IOException {
+ SegmentMerger merger = new SegmentMerger(mergedDir, IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL, mergedSegment, null, CodecProvider.getDefault(), null, new FieldInfos());
merger.add(reader1);
merger.add(reader2);
int docsMerged = merger.merge();
- merger.closeReaders();
assertTrue(docsMerged == 2);
//Should be able to open a new SegmentReader against the new directory
- SegmentReader mergedReader = SegmentReader.get(false, mergedDir, new SegmentInfo(mergedSegment, docsMerged, mergedDir, false,
- merger.hasProx(), merger.getCodec()), BufferedIndexInput.BUFFER_SIZE, true, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR, null);
-
+ SegmentReader mergedReader = SegmentReader.get(false, mergedDir, new SegmentInfo(mergedSegment, docsMerged, mergedDir, false, merger.fieldInfos().hasProx(),
+ merger.getSegmentCodecs(), merger.fieldInfos().hasVectors()),
+ BufferedIndexInput.BUFFER_SIZE, true, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);
-
assertTrue(mergedReader != null);
assertTrue(mergedReader.numDocs() == 2);
Document newDoc1 = mergedReader.document(0);
@@@ -85,19 -92,19 +91,19 @@@
Document newDoc2 = mergedReader.document(1);
assertTrue(newDoc2 != null);
assertTrue(DocHelper.numFields(newDoc2) == DocHelper.numFields(doc2) - DocHelper.unstored.size());
--
++
DocsEnum termDocs = MultiFields.getTermDocsEnum(mergedReader,
MultiFields.getDeletedDocs(mergedReader),
DocHelper.TEXT_FIELD_2_KEY,
new BytesRef("field"));
assertTrue(termDocs != null);
assertTrue(termDocs.nextDoc() != DocsEnum.NO_MORE_DOCS);
--
++
Collection<String> stored = mergedReader.getFieldNames(IndexReader.FieldOption.INDEXED_WITH_TERMVECTOR);
assertTrue(stored != null);
//System.out.println("stored size: " + stored.size());
assertTrue("We do not have 3 fields that were indexed with term vector",stored.size() == 3);
--
++
TermFreqVector vector = mergedReader.getTermFreqVector(0, DocHelper.TEXT_FIELD_2_KEY);
assertTrue(vector != null);
BytesRef [] terms = vector.getTerms();
@@@ -108,7 -115,7 +114,7 @@@
assertTrue(freqs != null);
//System.out.println("Freqs size: " + freqs.length);
assertTrue(vector instanceof TermPositionVector == true);
--
++
for (int i = 0; i < terms.length; i++) {
String term = terms[i].utf8ToString();
int freq = freqs[i];
@@@ -118,5 -125,6 +124,6 @@@
}
TestSegmentReader.checkNorms(mergedReader);
- }
+ mergedReader.close();
- }
++ }
}
diff --cc lucene/src/test/org/apache/lucene/index/TestSizeBoundedOptimize.java
index 00000000000,75455ac93c8..41001d035ac
mode 000000,100644..100644
--- a/lucene/src/test/org/apache/lucene/index/TestSizeBoundedOptimize.java
+++ b/lucene/src/test/org/apache/lucene/index/TestSizeBoundedOptimize.java
@@@ -1,0 -1,368 +1,368 @@@
+ 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 org.apache.lucene.document.Document;
+ import org.apache.lucene.store.Directory;
+ import org.apache.lucene.store.RAMDirectory;
+ import org.apache.lucene.util.LuceneTestCase;
+
+ public class TestSizeBoundedOptimize extends LuceneTestCase {
+
+ private void addDocs(IndexWriter writer, int numDocs) throws IOException {
+ for (int i = 0; i < numDocs; i++) {
+ Document doc = new Document();
+ writer.addDocument(doc);
+ }
+ writer.commit();
+ }
-
++
+ private static IndexWriterConfig newWriterConfig() throws IOException {
+ IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, null);
+ conf.setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
+ conf.setRAMBufferSizeMB(IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB);
+ // prevent any merges by default.
+ conf.setMergePolicy(NoMergePolicy.COMPOUND_FILES);
+ return conf;
+ }
-
++
+ public void testByteSizeLimit() throws Exception {
+ // tests that the max merge size constraint is applied during optimize.
+ Directory dir = new RAMDirectory();
+
+ // Prepare an index w/ several small segments and a large one.
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
+ final int numSegments = 15;
+ for (int i = 0; i < numSegments; i++) {
+ int numDocs = i == 7 ? 30 : 1;
+ addDocs(writer, numDocs);
+ }
+ writer.close();
+
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ double min = sis.info(0).sizeInBytes(true);
+
+ conf = newWriterConfig();
+ LogByteSizeMergePolicy lmp = new LogByteSizeMergePolicy();
+ lmp.setMaxMergeMB((min + 1) / (1 << 20));
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
+
+ // Should only be 3 segments in the index, because one of them exceeds the size limit
+ sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(3, sis.size());
+ }
+
+ public void testNumDocsLimit() throws Exception {
+ // tests that the max merge docs constraint is applied during optimize.
+ Directory dir = new RAMDirectory();
+
+ // Prepare an index w/ several small segments and a large one.
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
+
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 5);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
-
++
+ writer.close();
+
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(3);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
+
+ // Should only be 3 segments in the index, because one of them exceeds the size limit
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(3, sis.size());
+ }
+
+ public void testLastSegmentTooLarge() throws Exception {
+ Directory dir = new RAMDirectory();
+
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
+
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 5);
-
++
+ writer.close();
+
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(3);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
+
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(2, sis.size());
+ }
-
++
+ public void testFirstSegmentTooLarge() throws Exception {
+ Directory dir = new RAMDirectory();
-
++
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
-
++
+ addDocs(writer, 5);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
-
++
+ writer.close();
-
++
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(3);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
-
++
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(2, sis.size());
+ }
-
++
+ public void testAllSegmentsSmall() throws Exception {
+ Directory dir = new RAMDirectory();
-
++
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
-
++
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
-
++
+ writer.close();
-
++
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(3);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
-
++
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(1, sis.size());
+ }
-
++
+ public void testAllSegmentsLarge() throws Exception {
+ Directory dir = new RAMDirectory();
-
++
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
-
++
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
-
++
+ writer.close();
-
++
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(2);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
-
++
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(3, sis.size());
+ }
-
++
+ public void testOneLargeOneSmall() throws Exception {
+ Directory dir = new RAMDirectory();
-
++
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
-
++
+ addDocs(writer, 3);
+ addDocs(writer, 5);
+ addDocs(writer, 3);
+ addDocs(writer, 5);
-
++
+ writer.close();
-
++
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(3);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
-
++
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(4, sis.size());
+ }
-
++
+ public void testMergeFactor() throws Exception {
+ Directory dir = new RAMDirectory();
-
++
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
-
++
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
+ addDocs(writer, 5);
+ addDocs(writer, 3);
+ addDocs(writer, 3);
-
++
+ writer.close();
-
++
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(3);
+ lmp.setMergeFactor(2);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
-
++
+ // Should only be 4 segments in the index, because of the merge factor and
+ // max merge docs settings.
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(4, sis.size());
+ }
-
++
+ public void testSingleNonOptimizedSegment() throws Exception {
+ Directory dir = new RAMDirectory();
-
++
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
-
++
+ addDocs(writer, 3);
+ addDocs(writer, 5);
+ addDocs(writer, 3);
-
++
+ writer.close();
-
++
+ // delete the last document, so that the last segment is optimized.
+ IndexReader r = IndexReader.open(dir, false);
+ r.deleteDocument(r.numDocs() - 1);
+ r.close();
-
++
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(3);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
-
++
+ // Verify that the last segment does not have deletions.
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(3, sis.size());
+ assertFalse(sis.info(2).hasDeletions());
+ }
-
++
+ public void testSingleOptimizedSegment() throws Exception {
+ Directory dir = new RAMDirectory();
-
++
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
-
++
+ addDocs(writer, 3);
-
++
+ writer.close();
-
++
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(3);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
-
++
+ // Verify that the last segment does not have deletions.
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(1, sis.size());
+ }
+
+ public void testSingleNonOptimizedTooLargeSegment() throws Exception {
+ Directory dir = new RAMDirectory();
-
++
+ IndexWriterConfig conf = newWriterConfig();
+ IndexWriter writer = new IndexWriter(dir, conf);
-
++
+ addDocs(writer, 5);
-
++
+ writer.close();
-
++
+ // delete the last document
+ IndexReader r = IndexReader.open(dir, false);
+ r.deleteDocument(r.numDocs() - 1);
+ r.close();
-
++
+ conf = newWriterConfig();
+ LogMergePolicy lmp = new LogDocMergePolicy();
+ lmp.setMaxMergeDocs(2);
+ conf.setMergePolicy(lmp);
-
++
+ writer = new IndexWriter(dir, conf);
+ writer.optimize();
+ writer.close();
-
++
+ // Verify that the last segment does not have deletions.
+ SegmentInfos sis = new SegmentInfos();
+ sis.read(dir);
+ assertEquals(1, sis.size());
+ assertTrue(sis.info(0).hasDeletions());
+ }
+
+ }
diff --cc lucene/src/test/org/apache/lucene/index/TestStressIndexing2.java
index 96f1a9e1ea6,2076e741c11..66b4816f35b
--- a/lucene/src/test/org/apache/lucene/index/TestStressIndexing2.java
+++ b/lucene/src/test/org/apache/lucene/index/TestStressIndexing2.java
@@@ -193,10 -200,14 +200,14 @@@ public class TestStressIndexing2 extend
boolean doReaderPooling) throws IOException, InterruptedException {
Map<String,Document> docs = new HashMap<String,Document>();
for(int iter=0;iter<3;iter++) {
- IndexWriter w = new MockIndexWriter(dir, new IndexWriterConfig(
+ if (VERBOSE) {
+ System.out.println("TEST: iter=" + iter);
+ }
+ IndexWriter w = new MockIndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()).setOpenMode(OpenMode.CREATE)
- .setRAMBufferSizeMB(0.1).setMaxBufferedDocs(maxBufferedDocs).setMaxThreadStates(maxThreadStates)
+ .setRAMBufferSizeMB(0.1).setMaxBufferedDocs(maxBufferedDocs).setIndexerThreadPool(new ThreadAffinityDocumentsWriterThreadPool(maxThreadStates))
.setReaderPooling(doReaderPooling));
+ w.setInfoStream(VERBOSE ? System.out : null);
LogMergePolicy lmp = (LogMergePolicy) w.getConfig().getMergePolicy();
lmp.setUseCompoundFile(false);
lmp.setMergeFactor(mergeFactor);
diff --cc lucene/src/test/org/apache/lucene/index/TestTermVectorsReader.java
index 170f766fc82,c48e571c0c4..31630ed8470
--- a/lucene/src/test/org/apache/lucene/index/TestTermVectorsReader.java
+++ b/lucene/src/test/org/apache/lucene/index/TestTermVectorsReader.java
@@@ -119,20 -121,26 +121,26 @@@ public class TestTermVectorsReader exte
fieldInfos = new FieldInfos(dir, IndexFileNames.segmentFileName(seg, "", IndexFileNames.FIELD_INFOS_EXTENSION));
}
-
+
+ @Override
+ public void tearDown() throws Exception {
+ dir.close();
+ super.tearDown();
+ }
+
private class MyTokenStream extends TokenStream {
int tokenUpto;
--
++
CharTermAttribute termAtt;
PositionIncrementAttribute posIncrAtt;
OffsetAttribute offsetAtt;
--
++
public MyTokenStream() {
termAtt = addAttribute(CharTermAttribute.class);
posIncrAtt = addAttribute(PositionIncrementAttribute.class);
offsetAtt = addAttribute(OffsetAttribute.class);
}
--
++
@Override
public boolean incrementToken() {
if (tokenUpto >= tokens.length)
diff --cc lucene/src/test/org/apache/lucene/store/MockDirectoryWrapper.java
index 64bbc503604,13587132b9d..91657ec4ac8
--- a/lucene/src/test/org/apache/lucene/store/MockDirectoryWrapper.java
+++ b/lucene/src/test/org/apache/lucene/store/MockDirectoryWrapper.java
@@@ -17,21 -17,24 +17,22 @@@ package org.apache.lucene.store
* limitations under the License.
*/
+ import java.io.Closeable;
-import java.io.FileNotFoundException;
import java.io.IOException;
-import java.util.ArrayList;
+import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
+ import java.util.IdentityHashMap;
import java.util.Iterator;
-import java.util.Map;
import java.util.Random;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Set;
-
-import org.apache.lucene.util.LuceneTestCase;
+import java.util.ArrayList;
- import java.util.Arrays;
/**
- * This is a subclass of RAMDirectory that adds methods
+ * This is a Directory Wrapper that adds methods
* intended to be used only by unit tests.
*/
diff --cc lucene/src/test/org/apache/lucene/store/TestFileSwitchDirectory.java
index 979541b9ff8,e9cf2b6a879..61170ad8697
--- a/lucene/src/test/org/apache/lucene/store/TestFileSwitchDirectory.java
+++ b/lucene/src/test/org/apache/lucene/store/TestFileSwitchDirectory.java
@@@ -26,7 -26,7 +26,6 @@@ import org.apache.lucene.index.IndexFil
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
--import org.apache.lucene.index.LogMergePolicy;
import org.apache.lucene.index.TestIndexWriterReader;
import org.apache.lucene.util.LuceneTestCase;
@@@ -39,15 -39,18 +38,18 @@@ public class TestFileSwitchDirectory ex
Set<String> fileExtensions = new HashSet<String>();
fileExtensions.add(IndexFileNames.FIELDS_EXTENSION);
fileExtensions.add(IndexFileNames.FIELDS_INDEX_EXTENSION);
-
- Directory primaryDir = new MockRAMDirectory();
- RAMDirectory secondaryDir = new MockRAMDirectory();
--
++
+ Directory primaryDir = new MockDirectoryWrapper(random, new RAMDirectory());
+ Directory secondaryDir = new MockDirectoryWrapper(random, new RAMDirectory());
-
++
FileSwitchDirectory fsd = new FileSwitchDirectory(fileExtensions, primaryDir, secondaryDir, true);
- IndexWriter writer = new IndexWriter(fsd, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));
- ((LogMergePolicy) writer.getConfig().getMergePolicy()).setUseCompoundFile(false);
+ IndexWriter writer = new IndexWriter(
+ fsd,
+ new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setMergePolicy(newLogMergePolicy(false))
+ );
TestIndexWriterReader.createIndexNoClose(true, "ram", writer);
- IndexReader reader = writer.getReader();
+ IndexReader reader = IndexReader.open(writer);
assertEquals(100, reader.maxDoc());
writer.commit();
// we should see only fdx,fdt files here
diff --cc lucene/src/test/org/apache/lucene/util/LuceneTestCase.java
index 17eac777b23,6dca8e97f01..7bbd4a0f86c
--- a/lucene/src/test/org/apache/lucene/util/LuceneTestCase.java
+++ b/lucene/src/test/org/apache/lucene/util/LuceneTestCase.java
@@@ -18,35 -18,57 +18,84 @@@ package org.apache.lucene.util
*/
import java.io.File;
- import java.io.PrintStream;
import java.io.IOException;
+ import java.io.PrintStream;
+ import java.lang.annotation.Documented;
+ import java.lang.annotation.Inherited;
+ import java.lang.annotation.Retention;
+ import java.lang.annotation.RetentionPolicy;
+ import java.lang.reflect.Constructor;
+ import java.lang.reflect.Method;
+ import java.lang.reflect.Modifier;
-import java.util.*;
++import java.util.ArrayList;
+import java.util.Arrays;
++import java.util.Collections;
++import java.util.HashMap;
++import java.util.HashSet;
++import java.util.IdentityHashMap;
+import java.util.Iterator;
- import java.util.Random;
- import java.util.ArrayList;
+import java.util.List;
- import java.util.Collections;
-
- import junit.framework.TestCase;
++import java.util.Locale;
++import java.util.Map;
++import java.util.Random;
++import java.util.Set;
++import java.util.TimeZone;
+ import java.util.regex.Matcher;
+ import java.util.regex.Pattern;
import org.apache.lucene.analysis.Analyzer;
- import org.apache.lucene.index.ConcurrentMergeScheduler;
+ import org.apache.lucene.document.Field;
+ import org.apache.lucene.document.Field.Index;
+ import org.apache.lucene.document.Field.Store;
+ import org.apache.lucene.document.Field.TermVector;
-import org.apache.lucene.index.*;
++import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriterConfig;
++import org.apache.lucene.index.LogByteSizeMergePolicy;
++import org.apache.lucene.index.LogDocMergePolicy;
++import org.apache.lucene.index.LogMergePolicy;
++import org.apache.lucene.index.SegmentReader;
++import org.apache.lucene.index.SerialMergeScheduler;
++import org.apache.lucene.index.ThreadAffinityDocumentsWriterThreadPool;
+ import org.apache.lucene.index.codecs.Codec;
+ import org.apache.lucene.index.codecs.CodecProvider;
+ import org.apache.lucene.index.codecs.mockintblock.MockFixedIntBlockCodec;
+ import org.apache.lucene.index.codecs.mockintblock.MockVariableIntBlockCodec;
+ import org.apache.lucene.index.codecs.mocksep.MockSepCodec;
+ import org.apache.lucene.index.codecs.preflex.PreFlexCodec;
+ import org.apache.lucene.index.codecs.preflexrw.PreFlexRWCodec;
+ import org.apache.lucene.index.codecs.pulsing.PulsingCodec;
+ import org.apache.lucene.index.codecs.simpletext.SimpleTextCodec;
+ import org.apache.lucene.index.codecs.standard.StandardCodec;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.FieldCache.CacheEntry;
+ import org.apache.lucene.store.Directory;
+ import org.apache.lucene.store.FSDirectory;
+ import org.apache.lucene.store.LockFactory;
+ import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.util.FieldCacheSanityChecker.Insanity;
- import org.apache.lucene.index.codecs.CodecProvider;
- import org.apache.lucene.index.codecs.Codec;
-import org.junit.*;
++import org.junit.After;
++import org.junit.AfterClass;
++import org.junit.Assert;
++import org.junit.Assume;
++import org.junit.Before;
++import org.junit.BeforeClass;
++import org.junit.Ignore;
++import org.junit.Rule;
++import org.junit.Test;
+ import org.junit.rules.TestWatchman;
+ import org.junit.runner.Description;
+ import org.junit.runner.RunWith;
+ import org.junit.runner.manipulation.Filter;
+ import org.junit.runner.manipulation.NoTestsRemainException;
+ import org.junit.runner.notification.RunNotifier;
+ import org.junit.runners.BlockJUnit4ClassRunner;
+ import org.junit.runners.model.FrameworkMethod;
+ import org.junit.runners.model.InitializationError;
- /**
- * Base class for all Lucene unit tests.
+ /**
+ * Base class for all Lucene unit tests, Junit3 or Junit4 variant.
* <p>
- * Currently the
- * only added functionality over JUnit's TestCase is
- * asserting that no unhandled exceptions occurred in
- * threads launched by ConcurrentMergeScheduler and asserting sane
- * FieldCache usage athe moment of tearDown.
* </p>
* <p>
* If you
@@@ -64,31 -100,62 +127,62 @@@ public abstract class LuceneTestCase ex
* true iff tests are run in verbose mode. Note: if it is false, tests are not
* expected to print any messages.
*/
- public static final boolean VERBOSE = LuceneTestCaseJ4.VERBOSE;
+ public static final boolean VERBOSE = Boolean.getBoolean("tests.verbose");
+
+ /** Use this constant when creating Analyzers and any other version-dependent stuff.
+ * <p><b>NOTE:</b> Change this when development starts for new Lucene version:
+ */
+ public static final Version TEST_VERSION_CURRENT = Version.LUCENE_40;
- /** Use this constant when creating Analyzers and any other version-dependent stuff. */
- public static final Version TEST_VERSION_CURRENT = LuceneTestCaseJ4.TEST_VERSION_CURRENT;
+ /**
+ * If this is set, it is the only method that should run.
+ */
+ static final String TEST_METHOD;
-
+
/** Create indexes in this directory, optimally use a subdir, named after the test */
- public static final File TEMP_DIR = LuceneTestCaseJ4.TEMP_DIR;
+ public static final File TEMP_DIR;
+ static {
+ String method = System.getProperty("testmethod", "").trim();
+ TEST_METHOD = method.length() == 0 ? null : method;
+ String s = System.getProperty("tempDir", System.getProperty("java.io.tmpdir"));
+ if (s == null)
+ throw new RuntimeException("To run tests, you need to define system property 'tempDir' or 'java.io.tmpdir'.");
+ TEMP_DIR = new File(s);
+ TEMP_DIR.mkdirs();
+ }
+ // by default we randomly pick a different codec for
+ // each test case (non-J4 tests) and each test class (J4
+ // tests)
/** Gets the codec to run tests with. */
- public static final String TEST_CODEC = LuceneTestCaseJ4.TEST_CODEC;
+ public static final String TEST_CODEC = System.getProperty("tests.codec", "randomPerField");
+ /** Gets the locale to run tests with */
+ public static final String TEST_LOCALE = System.getProperty("tests.locale", "random");
+ /** Gets the timezone to run tests with */
+ public static final String TEST_TIMEZONE = System.getProperty("tests.timezone", "random");
+ /** Gets the directory to run tests with */
+ public static final String TEST_DIRECTORY = System.getProperty("tests.directory", "random");
+ /** Get the number of times to run tests */
+ public static final int TEST_ITER = Integer.parseInt(System.getProperty("tests.iter", "1"));
+ /** Get the random seed for tests */
+ public static final String TEST_SEED = System.getProperty("tests.seed", "random");
+ /** whether or not nightly tests should run */
+ public static final boolean TEST_NIGHTLY = Boolean.parseBoolean(System.getProperty("tests.nightly", "false"));
+ /** the line file used by LineFileDocs */
+ public static final String TEST_LINE_DOCS_FILE = System.getProperty("tests.linedocsfile", "europarl.lines.txt.gz");
+
+ private static final Pattern codecWithParam = Pattern.compile("(.*)\\(\\s*(\\d+)\\s*\\)");
/**
* A random multiplier which you should use when writing random tests:
* multiply it by the number of iterations
*/
- public static final int RANDOM_MULTIPLIER = LuceneTestCaseJ4.RANDOM_MULTIPLIER;
-
+ public static final int RANDOM_MULTIPLIER = Integer.parseInt(System.getProperty("tests.multiplier", "1"));
-
++
private int savedBoolMaxClauseCount;
-
+
private volatile Thread.UncaughtExceptionHandler savedUncaughtExceptionHandler = null;
--
- private String savedDefaultCodec;
- private String codec;
- private Codec preFlexSav;
+
/** Used to track if setUp and tearDown are called correctly from subclasses */
private boolean setup;
@@@ -95,25 -177,263 +204,263 @@@
private static class UncaughtExceptionEntry {
public final Thread thread;
public final Throwable exception;
--
++
public UncaughtExceptionEntry(Thread thread, Throwable exception) {
this.thread = thread;
this.exception = exception;
}
}
private List<UncaughtExceptionEntry> uncaughtExceptions = Collections.synchronizedList(new ArrayList<UncaughtExceptionEntry>());
-
+
- public LuceneTestCase() {
- super();
+ // saves default codec: we do this statically as many build indexes in @beforeClass
+ private static String savedDefaultCodec;
+ // default codec: not set when we use a per-field provider.
+ private static Codec codec;
+ // default codec provider
+ private static CodecProvider savedCodecProvider;
-
++
+ private static Locale locale;
+ private static Locale savedLocale;
+ private static TimeZone timeZone;
+ private static TimeZone savedTimeZone;
-
++
+ private static Map<MockDirectoryWrapper,StackTraceElement[]> stores;
-
++
+ private static final String[] TEST_CODECS = new String[] {"MockSep", "MockFixedIntBlock", "MockVariableIntBlock"};
+
+ private static void swapCodec(Codec c, CodecProvider cp) {
+ Codec prior = null;
+ try {
+ prior = cp.lookup(c.name);
+ } catch (IllegalArgumentException iae) {
+ }
+ if (prior != null) {
+ cp.unregister(prior);
+ }
+ cp.register(c);
+ }
+
+ // returns current default codec
+ static Codec installTestCodecs(String codec, CodecProvider cp) {
+ savedDefaultCodec = cp.getDefaultFieldCodec();
+
+ final boolean codecHasParam;
+ int codecParam = 0;
+ if (codec.equals("randomPerField")) {
+ // lie
+ codec = "Standard";
+ codecHasParam = false;
+ } else if (codec.equals("random")) {
+ codec = pickRandomCodec(random);
+ codecHasParam = false;
+ } else {
+ Matcher m = codecWithParam.matcher(codec);
+ if (m.matches()) {
+ // codec has a fixed param
+ codecHasParam = true;
+ codec = m.group(1);
+ codecParam = Integer.parseInt(m.group(2));
+ } else {
+ codecHasParam = false;
+ }
+ }
+
+ cp.setDefaultFieldCodec(codec);
+
+ if (codec.equals("PreFlex")) {
+ // If we're running w/ PreFlex codec we must swap in the
+ // test-only PreFlexRW codec (since core PreFlex can
+ // only read segments):
+ swapCodec(new PreFlexRWCodec(), cp);
+ }
+
+ swapCodec(new MockSepCodec(), cp);
+ swapCodec(new PulsingCodec(codecHasParam && "Pulsing".equals(codec) ? codecParam : _TestUtil.nextInt(random, 1, 20)), cp);
+ swapCodec(new MockFixedIntBlockCodec(codecHasParam && "MockFixedIntBlock".equals(codec) ? codecParam : _TestUtil.nextInt(random, 1, 2000)), cp);
+ // baseBlockSize cannot be over 127:
+ swapCodec(new MockVariableIntBlockCodec(codecHasParam && "MockVariableIntBlock".equals(codec) ? codecParam : _TestUtil.nextInt(random, 1, 127)), cp);
+
+ return cp.lookup(codec);
+ }
+
+ // returns current PreFlex codec
+ static void removeTestCodecs(Codec codec, CodecProvider cp) {
+ if (codec.name.equals("PreFlex")) {
+ final Codec preFlex = cp.lookup("PreFlex");
+ if (preFlex != null) {
+ cp.unregister(preFlex);
+ }
+ cp.register(new PreFlexCodec());
+ }
+ cp.unregister(cp.lookup("MockSep"));
+ cp.unregister(cp.lookup("MockFixedIntBlock"));
+ cp.unregister(cp.lookup("MockVariableIntBlock"));
+ swapCodec(new PulsingCodec(1), cp);
+ cp.setDefaultFieldCodec(savedDefaultCodec);
+
+ }
+
+ // randomly picks from core and test codecs
+ static String pickRandomCodec(Random rnd) {
- int idx = rnd.nextInt(CodecProvider.CORE_CODECS.length +
++ int idx = rnd.nextInt(CodecProvider.CORE_CODECS.length +
+ TEST_CODECS.length);
+ if (idx < CodecProvider.CORE_CODECS.length) {
+ return CodecProvider.CORE_CODECS[idx];
+ } else {
+ return TEST_CODECS[idx - CodecProvider.CORE_CODECS.length];
+ }
+ }
+
+ private static class TwoLongs {
+ public final long l1, l2;
+
+ public TwoLongs(long l1, long l2) {
+ this.l1 = l1;
+ this.l2 = l2;
+ }
+
+ @Override
+ public String toString() {
+ return l1 + ":" + l2;
+ }
+
+ public static TwoLongs fromString(String s) {
+ final int i = s.indexOf(':');
+ assert i != -1;
+ return new TwoLongs(Long.parseLong(s.substring(0, i)),
+ Long.parseLong(s.substring(1+i)));
+ }
+ }
+
+ /** @deprecated (4.0) until we fix no-fork problems in solr tests */
+ @Deprecated
+ private static List<String> testClassesRun = new ArrayList<String>();
-
++
+ @BeforeClass
+ public static void beforeClassLuceneTestCaseJ4() {
+ staticSeed = "random".equals(TEST_SEED) ? seedRand.nextLong() : TwoLongs.fromString(TEST_SEED).l1;
+ random.setSeed(staticSeed);
+ stores = Collections.synchronizedMap(new IdentityHashMap<MockDirectoryWrapper,StackTraceElement[]>());
+ savedCodecProvider = CodecProvider.getDefault();
+ if ("randomPerField".equals(TEST_CODEC)) {
+ if (random.nextInt(4) == 0) { // preflex-only setup
+ codec = installTestCodecs("PreFlex", CodecProvider.getDefault());
+ } else { // per-field setup
+ CodecProvider.setDefault(new RandomCodecProvider(random));
+ codec = installTestCodecs(TEST_CODEC, CodecProvider.getDefault());
+ }
+ } else { // ordinary setup
+ codec = installTestCodecs(TEST_CODEC, CodecProvider.getDefault());
+ }
+ savedLocale = Locale.getDefault();
+ locale = TEST_LOCALE.equals("random") ? randomLocale(random) : localeForName(TEST_LOCALE);
+ Locale.setDefault(locale);
+ savedTimeZone = TimeZone.getDefault();
+ timeZone = TEST_TIMEZONE.equals("random") ? randomTimeZone(random) : TimeZone.getTimeZone(TEST_TIMEZONE);
+ TimeZone.setDefault(timeZone);
+ testsFailed = false;
}
-
+
- public LuceneTestCase(String name) {
- super(name);
+ @AfterClass
+ public static void afterClassLuceneTestCaseJ4() {
+ int rogueThreads = threadCleanup("test class");
+ if (rogueThreads > 0) {
+ // TODO: fail here once the leaks are fixed.
+ System.err.println("RESOURCE LEAK: test class left " + rogueThreads + " thread(s) running");
+ }
+ String codecDescription;
+ CodecProvider cp = CodecProvider.getDefault();
+
+ if ("randomPerField".equals(TEST_CODEC)) {
+ if (cp instanceof RandomCodecProvider)
+ codecDescription = cp.toString();
- else
++ else
+ codecDescription = "PreFlex";
+ } else {
+ codecDescription = codec.toString();
+ }
-
++
+ if (CodecProvider.getDefault() == savedCodecProvider)
+ removeTestCodecs(codec, CodecProvider.getDefault());
+ CodecProvider.setDefault(savedCodecProvider);
+ Locale.setDefault(savedLocale);
+ TimeZone.setDefault(savedTimeZone);
+ System.clearProperty("solr.solr.home");
+ System.clearProperty("solr.data.dir");
+ // now look for unclosed resources
+ if (!testsFailed)
+ for (MockDirectoryWrapper d : stores.keySet()) {
+ if (d.isOpen()) {
+ StackTraceElement elements[] = stores.get(d);
+ // Look for the first class that is not LuceneTestCase that requested
+ // a Directory. The first two items are of Thread's, so skipping over
+ // them.
+ StackTraceElement element = null;
+ for (int i = 2; i < elements.length; i++) {
+ StackTraceElement ste = elements[i];
+ if (ste.getClassName().indexOf("LuceneTestCase") == -1) {
+ element = ste;
+ break;
+ }
+ }
+ fail("directory of test was not closed, opened from: " + element);
+ }
+ }
+ stores = null;
+ // if verbose or tests failed, report some information back
+ if (VERBOSE || testsFailed)
- System.err.println("NOTE: test params are: codec=" + codecDescription +
- ", locale=" + locale +
++ System.err.println("NOTE: test params are: codec=" + codecDescription +
++ ", locale=" + locale +
+ ", timezone=" + (timeZone == null ? "(null)" : timeZone.getID()));
+ if (testsFailed) {
+ System.err.println("NOTE: all tests run in this JVM:");
+ System.err.println(Arrays.toString(testClassesRun.toArray()));
+ }
}
- @Override
- protected void setUp() throws Exception {
- super.setUp();
+ private static boolean testsFailed; /* true if any tests failed */
-
++
+ // This is how we get control when errors occur.
+ // Think of this as start/end/success/failed
+ // events.
+ @Rule
+ public final TestWatchman intercept = new TestWatchman() {
+
+ @Override
+ public void failed(Throwable e, FrameworkMethod method) {
+ // org.junit.internal.AssumptionViolatedException in older releases
+ // org.junit.Assume.AssumptionViolatedException in recent ones
+ if (e.getClass().getName().endsWith("AssumptionViolatedException")) {
+ if (e.getCause() instanceof TestIgnoredException)
+ e = e.getCause();
+ System.err.print("NOTE: Assume failed in '" + method.getName() + "' (ignored):");
+ if (VERBOSE) {
+ System.err.println();
+ e.printStackTrace(System.err);
+ } else {
+ System.err.print(" ");
+ System.err.println(e.getMessage());
+ }
+ } else {
+ testsFailed = true;
+ reportAdditionalFailureInfo();
+ }
+ super.failed(e, method);
+ }
+
+ @Override
+ public void starting(FrameworkMethod method) {
+ // set current method name for logging
+ LuceneTestCase.this.name = method.getName();
+ super.starting(method);
+ }
-
++
+ };
+
+ @Before
+ public void setUp() throws Exception {
+ seed = "random".equals(TEST_SEED) ? seedRand.nextLong() : TwoLongs.fromString(TEST_SEED).l2;
+ random.setSeed(seed);
assertFalse("ensure your tearDown() calls super.tearDown()!!!", setup);
setup = true;
savedUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
@@@ -124,24 -445,11 +472,11 @@@
savedUncaughtExceptionHandler.uncaughtException(t, e);
}
});
--
- ConcurrentMergeScheduler.setTestMode();
- savedBoolMaxClauseCount = BooleanQuery.getMaxClauseCount();
- savedDefaultCodec = CodecProvider.getDefaultCodec();
+
- codec = TEST_CODEC;
- if (codec.equals("random"))
- codec = CodecProvider.CORE_CODECS[seedRnd.nextInt(CodecProvider.CORE_CODECS.length)];
-
- // If we're running w/ PreFlex codec we must swap in the
- // test-only PreFlexRW codec (since core PreFlex can
- // only read segments):
- if (codec.equals("PreFlex")) {
- preFlexSav = LuceneTestCaseJ4.installPreFlexRW();
- }
- CodecProvider.setDefaultCodec(codec);
+ savedBoolMaxClauseCount = BooleanQuery.getMaxClauseCount();
}
+
/**
* Forcible purges all cache entries from the FieldCache.
* <p>
@@@ -165,15 -474,23 +501,23 @@@
assertTrue("ensure your setUp() calls super.setUp()!!!", setup);
setup = false;
BooleanQuery.setMaxClauseCount(savedBoolMaxClauseCount);
- // Restore read-only PreFlex codec:
- if (codec.equals("PreFlex")) {
- LuceneTestCaseJ4.restorePreFlex(preFlexSav);
- }
- CodecProvider.setDefaultCodec(savedDefaultCodec);
-
+ if (!getClass().getName().startsWith("org.apache.solr")) {
+ int rogueThreads = threadCleanup("test method: '" + getName() + "'");
+ if (rogueThreads > 0) {
- System.err.println("RESOURCE LEAK: test method: '" + getName()
++ System.err.println("RESOURCE LEAK: test method: '" + getName()
+ + "' left " + rogueThreads + " thread(s) running");
+ // TODO: fail, but print seed for now.
+ if (!testsFailed && uncaughtExceptions.isEmpty()) {
+ reportAdditionalFailureInfo();
+ }
+ }
+ }
+ Thread.setDefaultUncaughtExceptionHandler(savedUncaughtExceptionHandler);
try {
- Thread.setDefaultUncaughtExceptionHandler(savedUncaughtExceptionHandler);
+
if (!uncaughtExceptions.isEmpty()) {
+ testsFailed = true;
+ reportAdditionalFailureInfo();
System.err.println("The following exceptions were thrown by threads:");
for (UncaughtExceptionEntry entry : uncaughtExceptions) {
System.err.println("*** Thread: " + entry.thread.getName() + " ***");
@@@ -182,30 -499,80 +526,82 @@@
fail("Some threads threw uncaught exceptions!");
}
- // this isn't as useful as calling directly from the scope where the
- // index readers are used, because they could be gc'ed just before
- // tearDown is called.
- // calling assertSaneFieldCaches here isn't as useful as having test
- // classes call it directly from the scope where the index readers
- // are used, because they could be gc'ed just before this tearDown
++ // calling assertSaneFieldCaches here isn't as useful as having test
++ // classes call it directly from the scope where the index readers
++ // are used, because they could be gc'ed just before this tearDown
+ // method is called.
+ //
// But it's better then nothing.
+ //
- // If you are testing functionality that you know for a fact
- // "violates" FieldCache sanity, then you should either explicitly
++ // If you are testing functionality that you know for a fact
++ // "violates" FieldCache sanity, then you should either explicitly
+ // call purgeFieldCache at the end of your test method, or refactor
- // your Test class so that the inconsistant FieldCache usages are
- // isolated in distinct test methods
++ // your Test class so that the inconsistant FieldCache usages are
++ // isolated in distinct test methods
assertSaneFieldCaches(getTestLabel());
-
- if (ConcurrentMergeScheduler.anyUnhandledExceptions()) {
- // Clear the failure so that we don't just keep
- // failing subsequent test cases
- ConcurrentMergeScheduler.clearUnhandledExceptions();
- fail("ConcurrentMergeScheduler hit unhandled exceptions");
- }
+
} finally {
purgeFieldCache(FieldCache.DEFAULT);
}
+
- super.tearDown();
++ Thread.setDefaultUncaughtExceptionHandler(savedUncaughtExceptionHandler);
+ }
+
+ private final static int THREAD_STOP_GRACE_MSEC = 1000;
+ // jvm-wide list of 'rogue threads' we found, so they only get reported once.
+ private final static IdentityHashMap<Thread,Boolean> rogueThreads = new IdentityHashMap<Thread,Boolean>();
-
++
+ /**
+ * Looks for leftover running threads, trying to kill them off,
+ * so they don't fail future tests.
+ * returns the number of rogue threads that it found.
+ */
+ private static int threadCleanup(String context) {
+ // educated guess
+ Thread[] stillRunning = new Thread[Thread.activeCount()+1];
+ int threadCount = 0;
+ int rogueCount = 0;
-
++
+ if ((threadCount = Thread.enumerate(stillRunning)) > 1) {
+ while (threadCount == stillRunning.length) {
+ // truncated response
+ stillRunning = new Thread[stillRunning.length*2];
+ threadCount = Thread.enumerate(stillRunning);
+ }
-
++
+ for (int i = 0; i < threadCount; i++) {
+ Thread t = stillRunning[i];
-
- if (t.isAlive() &&
- !rogueThreads.containsKey(t) &&
++
++ if (t.isAlive() &&
++ !rogueThreads.containsKey(t) &&
+ t != Thread.currentThread() &&
+ // TODO: TimeLimitingCollector starts a thread statically.... WTF?!
+ !t.getName().equals("TimeLimitedCollector timer thread")) {
+ System.err.println("WARNING: " + context + " left thread running: " + t);
+ rogueThreads.put(t, true);
+ rogueCount++;
+ // wait on the thread to die of natural causes
+ try {
+ t.join(THREAD_STOP_GRACE_MSEC);
+ } catch (InterruptedException e) { e.printStackTrace(); }
+ // try to stop the thread:
+ t.setUncaughtExceptionHandler(null);
+ Thread.setDefaultUncaughtExceptionHandler(null);
+ t.interrupt();
+ try {
+ t.join(THREAD_STOP_GRACE_MSEC);
+ } catch (InterruptedException e) { e.printStackTrace(); }
+ }
+ }
+ }
+ return rogueCount;
}
-
+
- /**
- * Asserts that FieldCacheSanityChecker does not detect any
+ /**
+ * Asserts that FieldCacheSanityChecker does not detect any
* problems with FieldCache.DEFAULT.
* <p>
- * If any problems are found, they are logged to System.err
+ * If any problems are found, they are logged to System.err
* (allong with the msg) when the Assertion is thrown.
* </p>
* <p>
@@@ -242,16 -610,85 +639,85 @@@
}
}
-
+
+ // @deprecated (4.0) These deprecated methods should be removed soon, when all tests using no Epsilon are fixed:
+ @Deprecated
+ static public void assertEquals(double expected, double actual) {
+ assertEquals(null, expected, actual);
+ }
-
++
+ @Deprecated
+ static public void assertEquals(String message, double expected, double actual) {
+ assertEquals(message, Double.valueOf(expected), Double.valueOf(actual));
+ }
+
+ @Deprecated
+ static public void assertEquals(float expected, float actual) {
+ assertEquals(null, expected, actual);
+ }
+
+ @Deprecated
+ static public void assertEquals(String message, float expected, float actual) {
+ assertEquals(message, Float.valueOf(expected), Float.valueOf(actual));
+ }
-
++
+ // Replacement for Assume jUnit class, so we can add a message with explanation:
-
++
+ private static final class TestIgnoredException extends RuntimeException {
+ TestIgnoredException(String msg) {
+ super(msg);
+ }
-
++
+ TestIgnoredException(String msg, Throwable t) {
+ super(msg, t);
+ }
-
++
+ @Override
+ public String getMessage() {
+ StringBuilder sb = new StringBuilder(super.getMessage());
+ if (getCause() != null)
+ sb.append(" - ").append(getCause());
+ return sb.toString();
+ }
-
++
+ // only this one is called by our code, exception is not used outside this class:
+ @Override
+ public void printStackTrace(PrintStream s) {
+ if (getCause() != null) {
+ s.println(super.toString() + " - Caused by:");
+ getCause().printStackTrace(s);
+ } else {
+ super.printStackTrace(s);
+ }
+ }
+ }
-
++
+ public static void assumeTrue(String msg, boolean b) {
+ Assume.assumeNoException(b ? null : new TestIgnoredException(msg));
+ }
-
++
+ public static void assumeFalse(String msg, boolean b) {
+ assumeTrue(msg, !b);
+ }
-
++
+ public static void assumeNoException(String msg, Exception e) {
+ Assume.assumeNoException(e == null ? null : new TestIgnoredException(msg, e));
+ }
-
++
+ public static <T> Set<T> asSet(T... args) {
+ return new HashSet<T>(Arrays.asList(args));
+ }
+
/**
* Convinience method for logging an iterator.
- * @param label String logged before/after the items in the iterator
- * @param iter Each next() is toString()ed and logged on it's own line. If iter is null this is logged differnetly then an empty iterator.
+ *
+ * @param label String logged before/after the items in the iterator
+ * @param iter Each next() is toString()ed and logged on it's own line. If iter is null this is logged differnetly then an empty iterator.
* @param stream Stream to log messages to.
*/
- public static <T> void dumpIterator(String label, Iterator<T> iter,
+ public static void dumpIterator(String label, Iterator<?> iter,
PrintStream stream) {
- stream.println("*** BEGIN "+label+" ***");
+ stream.println("*** BEGIN " + label + " ***");
if (null == iter) {
stream.println(" ... NULL ...");
} else {
@@@ -259,59 -696,304 +725,304 @@@
stream.println(iter.next().toString());
}
}
- stream.println("*** END "+label+" ***");
+ stream.println("*** END " + label + " ***");
}
- /**
+ /**
* Convinience method for logging an array. Wraps the array in an iterator and delegates
+ *
* @see #dumpIterator(String,Iterator,PrintStream)
*/
- public static void dumpArray(String label, Object[] objs,
+ public static void dumpArray(String label, Object[] objs,
PrintStream stream) {
- Iterator<Object> iter = (null == objs) ? null : Arrays.asList(objs).iterator();
+ Iterator<?> iter = (null == objs) ? null : Arrays.asList(objs).iterator();
dumpIterator(label, iter, stream);
}
-
- /**
- * Returns a {@link Random} instance for generating random numbers during the test.
- * The random seed is logged during test execution and printed to System.out on any failure
- * for reproducing the test using {@link #newRandom(long)} with the recorded seed
- *.
- */
- public Random newRandom() {
- if (seed != null) {
- throw new IllegalStateException("please call LuceneTestCase.newRandom only once per test");
+
+ /** create a new index writer config with random defaults */
+ public static IndexWriterConfig newIndexWriterConfig(Version v, Analyzer a) {
+ return newIndexWriterConfig(random, v, a);
+ }
-
++
+ public static IndexWriterConfig newIndexWriterConfig(Random r, Version v, Analyzer a) {
+ IndexWriterConfig c = new IndexWriterConfig(v, a);
+ if (r.nextBoolean()) {
+ c.setMergeScheduler(new SerialMergeScheduler());
+ }
+ if (r.nextBoolean()) {
+ if (r.nextInt(20) == 17) {
+ c.setMaxBufferedDocs(2);
+ } else {
+ c.setMaxBufferedDocs(_TestUtil.nextInt(r, 2, 1000));
+ }
+ }
+ if (r.nextBoolean()) {
+ c.setTermIndexInterval(_TestUtil.nextInt(r, 1, 1000));
+ }
+ if (r.nextBoolean()) {
- c.setMaxThreadStates(_TestUtil.nextInt(r, 1, 20));
++ c.setIndexerThreadPool(new ThreadAffinityDocumentsWriterThreadPool(_TestUtil.nextInt(r, 1, 20)));
}
- this.seed = Long.valueOf(seedRnd.nextLong());
- if (VERBOSE) {
- System.out.println("NOTE: random seed of testcase '" + getName() + "' is: " + this.seed);
+
+ c.setMergePolicy(newLogMergePolicy(r));
+
+ c.setReaderPooling(r.nextBoolean());
+ c.setReaderTermsIndexDivisor(_TestUtil.nextInt(r, 1, 4));
+ return c;
+ }
+
+ public static LogMergePolicy newLogMergePolicy() {
+ return newLogMergePolicy(random);
+ }
+
+ public static LogMergePolicy newLogMergePolicy(Random r) {
+ LogMergePolicy logmp = r.nextBoolean() ? new LogDocMergePolicy() : new LogByteSizeMergePolicy();
+ logmp.setUseCompoundFile(r.nextBoolean());
+ logmp.setCalibrateSizeByDeletes(r.nextBoolean());
+ if (r.nextInt(3) == 2) {
+ logmp.setMergeFactor(2);
+ } else {
+ logmp.setMergeFactor(_TestUtil.nextInt(r, 2, 20));
}
- return new Random(seed);
+ return logmp;
+ }
+
+ public static LogMergePolicy newLogMergePolicy(boolean useCFS) {
+ LogMergePolicy logmp = newLogMergePolicy();
+ logmp.setUseCompoundFile(useCFS);
+ return logmp;
+ }
+
+ public static LogMergePolicy newLogMergePolicy(boolean useCFS, int mergeFactor) {
+ LogMergePolicy logmp = newLogMergePolicy();
+ logmp.setUseCompoundFile(useCFS);
+ logmp.setMergeFactor(mergeFactor);
+ return logmp;
+ }
+
+ public static LogMergePolicy newLogMergePolicy(int mergeFactor) {
+ LogMergePolicy logmp = newLogMergePolicy();
+ logmp.setMergeFactor(mergeFactor);
+ return logmp;
+ }
+
+ /**
+ * Returns a new Directory instance. Use this when the test does not
+ * care about the specific Directory implementation (most tests).
+ * <p>
+ * The Directory is wrapped with {@link MockDirectoryWrapper}.
+ * By default this means it will be picky, such as ensuring that you
+ * properly close it and all open files in your test. It will emulate
+ * some features of Windows, such as not allowing open files to be
+ * overwritten.
+ */
+ public static MockDirectoryWrapper newDirectory() throws IOException {
+ return newDirectory(random);
+ }
-
++
+ public static MockDirectoryWrapper newDirectory(Random r) throws IOException {
+ Directory impl = newDirectoryImpl(r, TEST_DIRECTORY);
+ MockDirectoryWrapper dir = new MockDirectoryWrapper(r, impl);
+ stores.put(dir, Thread.currentThread().getStackTrace());
+ return dir;
}
--
++
/**
- * Returns a {@link Random} instance for generating random numbers during the test.
- * If an error occurs in the test that is not reproducible, you can use this method to
- * initialize the number generator with the seed that was printed out during the failing test.
+ * Returns a new Directory instance, with contents copied from the
+ * provided directory. See {@link #newDirectory()} for more
+ * information.
*/
- public Random newRandom(long seed) {
- if (this.seed != null) {
- throw new IllegalStateException("please call LuceneTestCase.newRandom only once per test");
+ public static MockDirectoryWrapper newDirectory(Directory d) throws IOException {
+ return newDirectory(random, d);
+ }
-
++
+ /** Returns a new FSDirectory instance over the given file, which must be a folder. */
+ public static MockDirectoryWrapper newFSDirectory(File f) throws IOException {
+ return newFSDirectory(f, null);
+ }
-
++
+ /** Returns a new FSDirectory instance over the given file, which must be a folder. */
+ public static MockDirectoryWrapper newFSDirectory(File f, LockFactory lf) throws IOException {
+ String fsdirClass = TEST_DIRECTORY;
+ if (fsdirClass.equals("random")) {
+ fsdirClass = FS_DIRECTORIES[random.nextInt(FS_DIRECTORIES.length)];
+ }
-
++
+ if (fsdirClass.indexOf(".") == -1) {// if not fully qualified, assume .store
+ fsdirClass = "org.apache.lucene.store." + fsdirClass;
+ }
-
++
+ Class<? extends FSDirectory> clazz;
+ try {
+ try {
+ clazz = Class.forName(fsdirClass).asSubclass(FSDirectory.class);
+ } catch (ClassCastException e) {
+ // TEST_DIRECTORY is not a sub-class of FSDirectory, so draw one at random
+ fsdirClass = FS_DIRECTORIES[random.nextInt(FS_DIRECTORIES.length)];
-
++
+ if (fsdirClass.indexOf(".") == -1) {// if not fully qualified, assume .store
+ fsdirClass = "org.apache.lucene.store." + fsdirClass;
+ }
-
++
+ clazz = Class.forName(fsdirClass).asSubclass(FSDirectory.class);
+ }
+ MockDirectoryWrapper dir = new MockDirectoryWrapper(random, newFSDirectoryImpl(clazz, f, lf));
+ stores.put(dir, Thread.currentThread().getStackTrace());
+ return dir;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
}
- System.out.println("WARNING: random seed of testcase '" + getName() + "' is fixed to: " + seed);
- this.seed = Long.valueOf(seed);
- return new Random(seed);
}
-
+
- /** create a new index writer config with random defaults */
- public static IndexWriterConfig newIndexWriterConfig(Random r, Version v, Analyzer a) {
- return LuceneTestCaseJ4.newIndexWriterConfig(r, v, a);
+ public static MockDirectoryWrapper newDirectory(Random r, Directory d) throws IOException {
+ Directory impl = newDirectoryImpl(r, TEST_DIRECTORY);
+ for (String file : d.listAll()) {
+ d.copy(impl, file, file);
+ }
+ MockDirectoryWrapper dir = new MockDirectoryWrapper(r, impl);
+ stores.put(dir, Thread.currentThread().getStackTrace());
+ return dir;
+ }
-
++
+ public static Field newField(String name, String value, Index index) {
+ return newField(random, name, value, index);
+ }
-
++
+ public static Field newField(String name, String value, Store store, Index index) {
+ return newField(random, name, value, store, index);
+ }
-
++
+ public static Field newField(String name, String value, Store store, Index index, TermVector tv) {
+ return newField(random, name, value, store, index, tv);
+ }
-
++
+ public static Field newField(Random random, String name, String value, Index index) {
+ return newField(random, name, value, Store.NO, index);
+ }
-
++
+ public static Field newField(Random random, String name, String value, Store store, Index index) {
+ return newField(random, name, value, store, index, TermVector.NO);
+ }
-
++
+ public static Field newField(Random random, String name, String value, Store store, Index index, TermVector tv) {
+ if (!index.isIndexed())
+ return new Field(name, value, store, index);
-
++
+ if (!store.isStored() && random.nextBoolean())
+ store = Store.YES; // randomly store it
-
++
+ tv = randomTVSetting(random, tv);
-
++
+ return new Field(name, value, store, index, tv);
+ }
-
- static final TermVector tvSettings[] = {
- TermVector.NO, TermVector.YES, TermVector.WITH_OFFSETS,
- TermVector.WITH_POSITIONS, TermVector.WITH_POSITIONS_OFFSETS
++
++ static final TermVector tvSettings[] = {
++ TermVector.NO, TermVector.YES, TermVector.WITH_OFFSETS,
++ TermVector.WITH_POSITIONS, TermVector.WITH_POSITIONS_OFFSETS
+ };
-
++
+ private static TermVector randomTVSetting(Random random, TermVector minimum) {
+ switch(minimum) {
+ case NO: return tvSettings[_TestUtil.nextInt(random, 0, tvSettings.length-1)];
+ case YES: return tvSettings[_TestUtil.nextInt(random, 1, tvSettings.length-1)];
- case WITH_OFFSETS: return random.nextBoolean() ? TermVector.WITH_OFFSETS
++ case WITH_OFFSETS: return random.nextBoolean() ? TermVector.WITH_OFFSETS
+ : TermVector.WITH_POSITIONS_OFFSETS;
- case WITH_POSITIONS: return random.nextBoolean() ? TermVector.WITH_POSITIONS
++ case WITH_POSITIONS: return random.nextBoolean() ? TermVector.WITH_POSITIONS
+ : TermVector.WITH_POSITIONS_OFFSETS;
+ default: return TermVector.WITH_POSITIONS_OFFSETS;
+ }
+ }
-
++
+ /** return a random Locale from the available locales on the system */
+ public static Locale randomLocale(Random random) {
+ Locale locales[] = Locale.getAvailableLocales();
+ return locales[random.nextInt(locales.length)];
+ }
-
++
+ /** return a random TimeZone from the available timezones on the system */
+ public static TimeZone randomTimeZone(Random random) {
+ String tzIds[] = TimeZone.getAvailableIDs();
+ return TimeZone.getTimeZone(tzIds[random.nextInt(tzIds.length)]);
+ }
-
++
+ /** return a Locale object equivalent to its programmatic name */
+ public static Locale localeForName(String localeName) {
+ String elements[] = localeName.split("\\_");
+ switch(elements.length) {
+ case 3: return new Locale(elements[0], elements[1], elements[2]);
+ case 2: return new Locale(elements[0], elements[1]);
+ case 1: return new Locale(elements[0]);
+ default: throw new IllegalArgumentException("Invalid Locale: " + localeName);
+ }
+ }
+
+ private static final String FS_DIRECTORIES[] = {
+ "SimpleFSDirectory",
+ "NIOFSDirectory",
+ "MMapDirectory"
+ };
+
+ private static final String CORE_DIRECTORIES[] = {
+ "RAMDirectory",
+ FS_DIRECTORIES[0], FS_DIRECTORIES[1], FS_DIRECTORIES[2]
+ };
-
++
+ public static String randomDirectory(Random random) {
+ if (random.nextInt(10) == 0) {
+ return CORE_DIRECTORIES[random.nextInt(CORE_DIRECTORIES.length)];
+ } else {
+ return "RAMDirectory";
+ }
+ }
+
+ private static Directory newFSDirectoryImpl(
+ Class<? extends FSDirectory> clazz, File file, LockFactory lockFactory)
+ throws IOException {
+ try {
+ // Assuming every FSDirectory has a ctor(File), but not all may take a
+ // LockFactory too, so setting it afterwards.
+ Constructor<? extends FSDirectory> ctor = clazz.getConstructor(File.class);
+ FSDirectory d = ctor.newInstance(file);
+ if (lockFactory != null) {
+ d.setLockFactory(lockFactory);
+ }
+ return d;
+ } catch (Exception e) {
+ return FSDirectory.open(file);
+ }
+ }
-
++
+ static Directory newDirectoryImpl(Random random, String clazzName) {
+ if (clazzName.equals("random"))
+ clazzName = randomDirectory(random);
+ if (clazzName.indexOf(".") == -1) // if not fully qualified, assume .store
+ clazzName = "org.apache.lucene.store." + clazzName;
+ try {
+ final Class<? extends Directory> clazz = Class.forName(clazzName).asSubclass(Directory.class);
+ // If it is a FSDirectory type, try its ctor(File)
+ if (FSDirectory.class.isAssignableFrom(clazz)) {
+ final File tmpFile = File.createTempFile("test", "tmp", TEMP_DIR);
+ tmpFile.delete();
+ tmpFile.mkdir();
+ return newFSDirectoryImpl(clazz.asSubclass(FSDirectory.class), tmpFile, null);
+ }
+
+ // try empty ctor
+ return clazz.newInstance();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
- }
++ }
+ }
-
++
+
+ public String getName() {
+ return this.name;
}
-
+
/** Gets a resource from the classpath as {@link File}. This method should only be used,
* if a real file is needed. To get a stream, code should prefer
* {@link Class#getResourceAsStream} using {@code this.getClass()}.
*/
-
++
protected File getDataFile(String name) throws IOException {
try {
return new File(this.getClass().getResource(name).toURI());
@@@ -319,29 -1001,173 +1030,173 @@@
throw new IOException("Cannot find resource: " + name);
}
}
-
- @Override
- public void runBare() throws Throwable {
- //long t0 = System.currentTimeMillis();
- try {
- seed = null;
- super.runBare();
- } catch (Throwable e) {
- if (TEST_CODEC.equals("random")) {
- System.out.println("NOTE: random codec of testcase '" + getName() + "' was: " + codec);
+
+ // We get here from InterceptTestCaseEvents on the 'failed' event....
+ public void reportAdditionalFailureInfo() {
- System.err.println("NOTE: reproduce with: ant test -Dtestcase=" + getClass().getSimpleName()
++ System.err.println("NOTE: reproduce with: ant test -Dtestcase=" + getClass().getSimpleName()
+ + " -Dtestmethod=" + getName() + " -Dtests.seed=" + new TwoLongs(staticSeed, seed)
+ + reproduceWithExtraParams());
+ }
-
++
+ // extra params that were overridden needed to reproduce the command
+ private String reproduceWithExtraParams() {
+ StringBuilder sb = new StringBuilder();
+ if (!TEST_CODEC.equals("randomPerField")) sb.append(" -Dtests.codec=").append(TEST_CODEC);
+ if (!TEST_LOCALE.equals("random")) sb.append(" -Dtests.locale=").append(TEST_LOCALE);
+ if (!TEST_TIMEZONE.equals("random")) sb.append(" -Dtests.timezone=").append(TEST_TIMEZONE);
+ if (!TEST_DIRECTORY.equals("random")) sb.append(" -Dtests.directory=").append(TEST_DIRECTORY);
+ if (RANDOM_MULTIPLIER > 1) sb.append(" -Dtests.multiplier=").append(RANDOM_MULTIPLIER);
+ return sb.toString();
+ }
+
+ // recorded seed: for beforeClass
+ private static long staticSeed;
+ // seed for individual test methods, changed in @before
+ private long seed;
-
++
+ private static final Random seedRand = new Random();
+ protected static final Random random = new Random(0);
+
+ private String name = "<unknown>";
-
++
+ /**
+ * Annotation for tests that should only be run during nightly builds.
+ */
+ @Documented
+ @Inherited
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface Nightly {}
-
++
+ /** optionally filters the tests to be run by TEST_METHOD */
+ public static class LuceneTestCaseRunner extends BlockJUnit4ClassRunner {
+ private List<FrameworkMethod> testMethods;
+
+ @Override
+ protected List<FrameworkMethod> computeTestMethods() {
+ if (testMethods != null)
+ return testMethods;
+ testClassesRun.add(getTestClass().getJavaClass().getSimpleName());
+ testMethods = new ArrayList<FrameworkMethod>();
+ for (Method m : getTestClass().getJavaClass().getMethods()) {
+ // check if the current test's class has methods annotated with @Ignore
+ final Ignore ignored = m.getAnnotation(Ignore.class);
+ if (ignored != null && !m.getName().equals("alwaysIgnoredTestMethod")) {
+ System.err.println("NOTE: Ignoring test method '" + m.getName() + "': " + ignored.value());
+ }
+ // add methods starting with "test"
+ final int mod = m.getModifiers();
+ if (m.getAnnotation(Test.class) != null ||
+ (m.getName().startsWith("test") &&
+ !Modifier.isAbstract(mod) &&
+ m.getParameterTypes().length == 0 &&
+ m.getReturnType() == Void.TYPE))
+ {
+ if (Modifier.isStatic(mod))
+ throw new RuntimeException("Test methods must not be static.");
+ testMethods.add(new FrameworkMethod(m));
+ }
+ }
-
++
+ if (testMethods.isEmpty()) {
+ throw new RuntimeException("No runnable methods!");
+ }
-
++
+ if (TEST_NIGHTLY == false) {
+ if (getTestClass().getJavaClass().isAnnotationPresent(Nightly.class)) {
+ /* the test class is annotated with nightly, remove all methods */
+ String className = getTestClass().getJavaClass().getSimpleName();
+ System.err.println("NOTE: Ignoring nightly-only test class '" + className + "'");
+ testMethods.clear();
+ } else {
+ /* remove all nightly-only methods */
+ for (int i = 0; i < testMethods.size(); i++) {
+ final FrameworkMethod m = testMethods.get(i);
+ if (m.getAnnotation(Nightly.class) != null) {
+ System.err.println("NOTE: Ignoring nightly-only test method '" + m.getName() + "'");
+ testMethods.remove(i--);
+ }
+ }
+ }
+ /* dodge a possible "no-runnable methods" exception by adding a fake ignored test */
+ if (testMethods.isEmpty()) {
+ try {
+ testMethods.add(new FrameworkMethod(LuceneTestCase.class.getMethod("alwaysIgnoredTestMethod")));
+ } catch (Exception e) { throw new RuntimeException(e); }
+ }
+ }
+ return testMethods;
+ }
+
+ @Override
+ protected void runChild(FrameworkMethod arg0, RunNotifier arg1) {
+ for (int i = 0; i < TEST_ITER; i++)
+ super.runChild(arg0, arg1);
+ }
+
+ public LuceneTestCaseRunner(Class<?> clazz) throws InitializationError {
+ super(clazz);
+ Filter f = new Filter() {
+
+ @Override
+ public String describe() { return "filters according to TEST_METHOD"; }
+
+ @Override
+ public boolean shouldRun(Description d) {
+ return TEST_METHOD == null || d.getMethodName().equals(TEST_METHOD);
- }
++ }
+ };
-
++
+ try {
+ f.apply(this);
+ } catch (NoTestsRemainException e) {
+ throw new RuntimeException(e);
}
- if (seed != null) {
- System.out.println("NOTE: random seed of testcase '" + getName() + "' was: " + seed);
+ }
+ }
-
++
+ private static class RandomCodecProvider extends CodecProvider {
+ private List<Codec> knownCodecs = new ArrayList<Codec>();
+ private Map<String,Codec> previousMappings = new HashMap<String,Codec>();
+ private final int perFieldSeed;
-
++
+ RandomCodecProvider(Random random) {
+ this.perFieldSeed = random.nextInt();
+ register(new StandardCodec());
+ register(new PreFlexCodec());
+ register(new PulsingCodec(1));
+ register(new SimpleTextCodec());
+ Collections.shuffle(knownCodecs, random);
+ }
+
+ @Override
+ public synchronized void register(Codec codec) {
+ if (!codec.name.equals("PreFlex"))
+ knownCodecs.add(codec);
+ super.register(codec);
+ }
+
+ @Override
+ public synchronized void unregister(Codec codec) {
+ knownCodecs.remove(codec);
+ super.unregister(codec);
+ }
+
+ @Override
+ public synchronized String getFieldCodec(String name) {
+ Codec codec = previousMappings.get(name);
+ if (codec == null) {
+ codec = knownCodecs.get(Math.abs(perFieldSeed ^ name.hashCode()) % knownCodecs.size());
+ previousMappings.put(name, codec);
}
- throw e;
+ return codec.name;
+ }
-
++
+ @Override
+ public String toString() {
+ return "RandomCodecProvider: " + previousMappings.toString();
}
- //long t = System.currentTimeMillis() - t0;
- //System.out.println(t + " msec for " + getName());
}
-
- // recorded seed
- protected Long seed = null;
--
- // static members
- private static final Random seedRnd = new Random();
++
+ @Ignore("just a hack")
+ public final void alwaysIgnoredTestMethod() {}
}