Skip to content

Apache Lucene open-source search software

catch up with trunk

Simon Willnauer452684f1f1a4
diff --git a/lucene/contrib/CHANGES.txt b/lucene/contrib/CHANGES.txt
index 2a3c9ee7161..494b0ef9162 100644
--- a/lucene/contrib/CHANGES.txt
+++ b/lucene/contrib/CHANGES.txt
@@ -32,6 +32,11 @@ New Features
* LUCENE-2507: Added DirectSpellChecker, which retrieves correction candidates directly
from the term dictionary using levenshtein automata. (Robert Muir)
+ * LUCENE-2791: Added WindowsDirectory, a Windows-specific Directory impl
+ that doesn't synchronize on the file handle. This can be useful to
+ avoid the performance problems of SimpleFSDirectory and NIOFSDirectory.
+ (Robert Muir, Simon Willnauer, Uwe Schindler, Michael McCandless)
+
API Changes
* LUCENE-2606: Changed RegexCapabilities interface to fix thread
@@ -166,6 +171,9 @@ API Changes
new SpanMultiTermQueryWrapper<RegexQuery>(new RegexQuery()) instead.
(Robert Muir, Uwe Schindler)
+ * LUCENE-2747: Deprecated ArabicLetterTokenizer. StandardTokenizer now tokenizes
+ most languages correctly including Arabic. (Steven Rowe, Robert Muir)
+
New features
* LUCENE-2306: Add NumericRangeFilter and NumericRangeQuery support to XMLQueryParser.
@@ -274,7 +282,7 @@ Build
dependency management between contribs by a new ANT macro.
(Uwe Schindler, Shai Erera)
- * LUCENE-2399, LUCENE-2683: Upgrade contrib/icu's ICU jar file to ICU 4.4.2
+ * LUCENE-2797: Upgrade contrib/icu's ICU jar file to ICU 4.6
(Robert Muir)
Optimizations
diff --git a/lucene/contrib/misc/src/java/org/apache/lucene/index/BalancedSegmentMergePolicy.java b/lucene/contrib/misc/src/java/org/apache/lucene/index/BalancedSegmentMergePolicy.java
index 484d3326fef..9d6186bf9fc 100644
--- a/lucene/contrib/misc/src/java/org/apache/lucene/index/BalancedSegmentMergePolicy.java
+++ b/lucene/contrib/misc/src/java/org/apache/lucene/index/BalancedSegmentMergePolicy.java
@@ -132,11 +132,10 @@ public class BalancedSegmentMergePolicy extends LogByteSizeMergePolicy {
// Since we must optimize down to 1 segment, the
// choice is simple:
- boolean useCompoundFile = getUseCompoundFile();
if (last > 1 || !isOptimized(infos.info(0))) {
spec = new MergeSpecification();
- spec.add(new OneMerge(infos.range(0, last), useCompoundFile));
+ spec.add(new OneMerge(infos.range(0, last)));
}
} else if (last > maxNumSegments) {
@@ -153,7 +152,6 @@ public class BalancedSegmentMergePolicy extends LogByteSizeMergePolicy {
if (infoLen <= maxNumSegments) return null;
MergeSpecification spec = new MergeSpecification();
- boolean useCompoundFile = getUseCompoundFile();
// use Viterbi algorithm to find the best segmentation.
// we will try to minimize the size variance of resulting segments.
@@ -194,7 +192,7 @@ public class BalancedSegmentMergePolicy extends LogByteSizeMergePolicy {
prev = backLink[i][prev];
int mergeStart = i + prev;
if((mergeEnd - mergeStart) > 1) {
- spec.add(new OneMerge(infos.range(mergeStart, mergeEnd), useCompoundFile));
+ spec.add(new OneMerge(infos.range(mergeStart, mergeEnd)));
} else {
if(partialExpunge) {
SegmentInfo info = infos.info(mergeStart);
@@ -210,7 +208,7 @@ public class BalancedSegmentMergePolicy extends LogByteSizeMergePolicy {
if(partialExpunge && maxDelCount > 0) {
// expunge deletes
- spec.add(new OneMerge(infos.range(expungeCandidate, expungeCandidate + 1), useCompoundFile));
+ spec.add(new OneMerge(infos.range(expungeCandidate, expungeCandidate + 1)));
}
return spec;
@@ -260,7 +258,7 @@ public class BalancedSegmentMergePolicy extends LogByteSizeMergePolicy {
for(int i = 0; i < numLargeSegs; i++) {
SegmentInfo info = infos.info(i);
if(info.hasDeletions()) {
- spec.add(new OneMerge(infos.range(i, i + 1), getUseCompoundFile()));
+ spec.add(new OneMerge(infos.range(i, i + 1)));
}
}
return spec;
@@ -298,7 +296,7 @@ public class BalancedSegmentMergePolicy extends LogByteSizeMergePolicy {
if(totalSmallSegSize < targetSegSize * 2) {
MergeSpecification spec = findBalancedMerges(infos, numLargeSegs, (numLargeSegs - 1), _partialExpunge);
if(spec == null) spec = new MergeSpecification(); // should not happen
- spec.add(new OneMerge(infos.range(numLargeSegs, numSegs), getUseCompoundFile()));
+ spec.add(new OneMerge(infos.range(numLargeSegs, numSegs)));
return spec;
} else {
return findBalancedMerges(infos, numSegs, numLargeSegs, _partialExpunge);
@@ -313,7 +311,7 @@ public class BalancedSegmentMergePolicy extends LogByteSizeMergePolicy {
if(size(info) < sizeThreshold) break;
startSeg++;
}
- spec.add(new OneMerge(infos.range(startSeg, numSegs), getUseCompoundFile()));
+ spec.add(new OneMerge(infos.range(startSeg, numSegs)));
return spec;
} else {
// apply the log merge policy to small segments.
@@ -344,7 +342,7 @@ public class BalancedSegmentMergePolicy extends LogByteSizeMergePolicy {
}
}
if (maxDelCount > 0) {
- return new OneMerge(infos.range(expungeCandidate, expungeCandidate + 1), getUseCompoundFile());
+ return new OneMerge(infos.range(expungeCandidate, expungeCandidate + 1));
}
return null;
}
diff --git a/lucene/contrib/misc/src/java/org/apache/lucene/store/NativePosixUtil.cpp b/lucene/contrib/misc/src/java/org/apache/lucene/store/NativePosixUtil.cpp
index ced785fff6d..7ccf7e7b445 100644
--- a/lucene/contrib/misc/src/java/org/apache/lucene/store/NativePosixUtil.cpp
+++ b/lucene/contrib/misc/src/java/org/apache/lucene/store/NativePosixUtil.cpp
@@ -97,9 +97,9 @@ JNIEXPORT jobject JNICALL Java_org_apache_lucene_store_NativePosixUtil_open_1dir
fname = (char *) env->GetStringUTFChars(filename, NULL);
if (readOnly) {
- fd = open(fname, O_RDONLY | O_DIRECT);
+ fd = open(fname, O_RDONLY | O_DIRECT | O_NOATIME);
} else {
- fd = open(fname, O_RDWR | O_CREAT | O_DIRECT, 0666);
+ fd = open(fname, O_RDWR | O_CREAT | O_DIRECT | O_NOATIME, 0666);
}
//printf("open %s -> %d; ro %d\n", fname, fd, readOnly); fflush(stdout);
diff --git a/lucene/contrib/misc/src/java/org/apache/lucene/store/WindowsDirectory.cpp b/lucene/contrib/misc/src/java/org/apache/lucene/store/WindowsDirectory.cpp
new file mode 100644
index 00000000000..e6063b936f8
--- /dev/null
+++ b/lucene/contrib/misc/src/java/org/apache/lucene/store/WindowsDirectory.cpp
@@ -0,0 +1,175 @@
+/**
+ * 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.
+ */
+
+#include <jni.h>
+#include "windows.h"
+
+/**
+ * Windows Native IO methods.
+ */
+extern "C" {
+
+/**
+ * Utility to format a Windows system error code into an exception.
+ */
+void throwIOException(JNIEnv *env, DWORD error)
+{
+ jclass ioex;
+ char *msg;
+
+ ioex = env->FindClass("java/io/IOException");
+
+ if (ioex != NULL) {
+ FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &msg, 0, NULL );
+ env->ThrowNew(ioex, msg);
+ LocalFree(msg);
+ }
+}
+
+/**
+ * Utility to throw Exceptions on bad input
+ */
+void throwException(JNIEnv *env, const char *clazz, const char *msg)
+{
+ jclass exc = env->FindClass(clazz);
+
+ if (exc != NULL) {
+ env->ThrowNew(exc, msg);
+ }
+}
+
+/**
+ * Opens a handle to a file.
+ *
+ * Class: org_apache_lucene_store_WindowsDirectory
+ * Method: open
+ * Signature: (Ljava/lang/String;)J
+ */
+JNIEXPORT jlong JNICALL Java_org_apache_lucene_store_WindowsDirectory_open
+ (JNIEnv *env, jclass ignored, jstring filename)
+{
+ char *fname;
+ HANDLE handle;
+
+ if (filename == NULL) {
+ throwException(env, "java/lang/NullPointerException", "filename cannot be null");
+ return -1;
+ }
+
+ fname = (char *) env->GetStringUTFChars(filename, NULL);
+
+ if (fname == NULL) {
+ throwException(env, "java/lang/IllegalArgumentException", "invalid filename");
+ return -1;
+ }
+
+ handle = CreateFile(fname, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
+ NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
+
+ env->ReleaseStringUTFChars(filename, fname);
+
+ if (handle == INVALID_HANDLE_VALUE) {
+ throwIOException(env, GetLastError());
+ return -1;
+ }
+
+ return (jlong) handle;
+}
+
+/**
+ * Reads data into the byte array, starting at offset, for length characters.
+ * The read is positioned at pos.
+ *
+ * Class: org_apache_lucene_store_WindowsDirectory
+ * Method: read
+ * Signature: (J[BIIJ)I
+ */
+JNIEXPORT jint JNICALL Java_org_apache_lucene_store_WindowsDirectory_read
+ (JNIEnv *env, jclass ignored, jlong fd, jbyteArray bytes, jint offset, jint length, jlong pos)
+{
+ OVERLAPPED io = { 0 };
+ DWORD numRead = -1;
+
+ io.Offset = (DWORD) (pos & 0xFFFFFFFF);
+ io.OffsetHigh = (DWORD) ((pos >> 0x20) & 0x7FFFFFFF);
+
+ if (bytes == NULL) {
+ throwException(env, "java/lang/NullPointerException", "bytes cannot be null");
+ return -1;
+ }
+
+ if (length <= 4096) { /* For small buffers, avoid GetByteArrayElements' copy */
+ char buffer[length];
+
+ if (ReadFile((HANDLE) fd, &buffer, length, &numRead, &io)) {
+ env->SetByteArrayRegion(bytes, offset, numRead, (const jbyte *) buffer);
+ } else {
+ throwIOException(env, GetLastError());
+ numRead = -1;
+ }
+
+ } else {
+ jbyte *buffer = env->GetByteArrayElements (bytes, NULL);
+
+ if (!ReadFile((HANDLE) fd, (void *)(buffer+offset), length, &numRead, &io)) {
+ throwIOException(env, GetLastError());
+ numRead = -1;
+ }
+
+ env->ReleaseByteArrayElements(bytes, buffer, numRead == 0 || numRead == -1 ? JNI_ABORT : 0);
+ }
+
+ return numRead;
+}
+
+/**
+ * Closes a handle to a file
+ *
+ * Class: org_apache_lucene_store_WindowsDirectory
+ * Method: close
+ * Signature: (J)V
+ */
+JNIEXPORT void JNICALL Java_org_apache_lucene_store_WindowsDirectory_close
+ (JNIEnv *env, jclass ignored, jlong fd)
+{
+ if (!CloseHandle((HANDLE) fd)) {
+ throwIOException(env, GetLastError());
+ }
+}
+
+/**
+ * Returns the length in bytes of a file.
+ *
+ * Class: org_apache_lucene_store_WindowsDirectory
+ * Method: length
+ * Signature: (J)J
+ */
+JNIEXPORT jlong JNICALL Java_org_apache_lucene_store_WindowsDirectory_length
+ (JNIEnv *env, jclass ignored, jlong fd)
+{
+ BY_HANDLE_FILE_INFORMATION info;
+
+ if (GetFileInformationByHandle((HANDLE) fd, (LPBY_HANDLE_FILE_INFORMATION) &info)) {
+ return (jlong) (((DWORDLONG) info.nFileSizeHigh << 0x20) + info.nFileSizeLow);
+ } else {
+ throwIOException(env, GetLastError());
+ return -1;
+ }
+}
+
+} /* extern "C" */
diff --git a/lucene/contrib/misc/src/java/org/apache/lucene/store/WindowsDirectory.java b/lucene/contrib/misc/src/java/org/apache/lucene/store/WindowsDirectory.java
new file mode 100644
index 00000000000..870ebfade1e
--- /dev/null
+++ b/lucene/contrib/misc/src/java/org/apache/lucene/store/WindowsDirectory.java
@@ -0,0 +1,124 @@
+package org.apache.lucene.store;
+
+/**
+ * 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;
+
+/**
+ * Native {@link Directory} implementation for Microsoft Windows.
+ * <p>
+ * Steps:
+ * <ol>
+ * <li>Compile the source code to create WindowsDirectory.dll:
+ * <blockquote>
+ * c:\mingw\bin\g++ -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at
+ * -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -static-libgcc
+ * -static-libstdc++ -shared WindowsDirectory.cpp -o WindowsDirectory.dll
+ * </blockquote>
+ * For 64-bit JREs, use mingw64, with the -m64 option.
+ * <li>Put WindowsDirectory.dll into some directory in your windows PATH
+ * <li>Open indexes with WindowsDirectory and use it.
+ * </p>
+ * @lucene.experimental
+ */
+public class WindowsDirectory extends FSDirectory {
+ private static final int DEFAULT_BUFFERSIZE = 4096; /* default pgsize on ia32/amd64 */
+
+ static {
+ System.loadLibrary("WindowsDirectory");
+ }
+
+ /** Create a new WindowsDirectory for the named location.
+ *
+ * @param path the path of the directory
+ * @param lockFactory the lock factory to use, or null for the default
+ * ({@link NativeFSLockFactory});
+ * @throws IOException
+ */
+ public WindowsDirectory(File path, LockFactory lockFactory) throws IOException {
+ super(path, lockFactory);
+ }
+
+ /** Create a new WindowsDirectory for the named location and {@link NativeFSLockFactory}.
+ *
+ * @param path the path of the directory
+ * @throws IOException
+ */
+ public WindowsDirectory(File path) throws IOException {
+ super(path, null);
+ }
+
+ public IndexInput openInput(String name, int bufferSize) throws IOException {
+ ensureOpen();
+ return new WindowsIndexInput(new File(getDirectory(), name), Math.max(bufferSize, DEFAULT_BUFFERSIZE));
+ }
+
+ protected static class WindowsIndexInput extends BufferedIndexInput {
+ private final long fd;
+ private final long length;
+ boolean isClone;
+ boolean isOpen;
+
+ public WindowsIndexInput(File file, int bufferSize) throws IOException {
+ super(bufferSize);
+ fd = WindowsDirectory.open(file.getPath());
+ length = WindowsDirectory.length(fd);
+ isOpen = true;
+ }
+
+ protected void readInternal(byte[] b, int offset, int length) throws IOException {
+ if (WindowsDirectory.read(fd, b, offset, length, getFilePointer()) != length)
+ throw new IOException("Read past EOF");
+ }
+
+ protected void seekInternal(long pos) throws IOException {
+ }
+
+ public synchronized void close() throws IOException {
+ // NOTE: we synchronize and track "isOpen" because Lucene sometimes closes IIs twice!
+ if (!isClone && isOpen) {
+ WindowsDirectory.close(fd);
+ isOpen = false;
+ }
+ }
+
+ public long length() {
+ return length;
+ }
+
+ @Override
+ public Object clone() {
+ WindowsIndexInput clone = (WindowsIndexInput)super.clone();
+ clone.isClone = true;
+ return clone;
+ }
+ }
+
+ /** Opens a handle to a file. */
+ private static native long open(String filename) throws IOException;
+
+ /** Reads data from a file at pos into bytes */
+ private static native int read(long fd, byte bytes[], int offset, int length, long pos) throws IOException;
+
+ /** Closes a handle to a file */
+ private static native void close(long fd) throws IOException;
+
+ /** Returns the length of a file */
+ private static native long length(long fd) throws IOException;
+}
diff --git a/lucene/contrib/misc/src/test/org/apache/lucene/index/TestIndexSplitter.java b/lucene/contrib/misc/src/test/org/apache/lucene/index/TestIndexSplitter.java
index 24efd037b3e..9e4d20fb916 100644
--- a/lucene/contrib/misc/src/test/org/apache/lucene/index/TestIndexSplitter.java
+++ b/lucene/contrib/misc/src/test/org/apache/lucene/index/TestIndexSplitter.java
@@ -34,7 +34,15 @@ public class TestIndexSplitter extends LuceneTestCase {
_TestUtil.rmDir(destDir);
destDir.mkdirs();
FSDirectory fsDir = FSDirectory.open(dir);
- IndexWriter iw = new IndexWriter(fsDir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).setOpenMode(OpenMode.CREATE));
+
+ LogMergePolicy mergePolicy = new LogByteSizeMergePolicy();
+ mergePolicy.setNoCFSRatio(1);
+ IndexWriter iw = new IndexWriter(
+ fsDir,
+ new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
+ setOpenMode(OpenMode.CREATE).
+ setMergePolicy(mergePolicy)
+ );
for (int x=0; x < 100; x++) {
Document doc = TestIndexWriterReader.createDocument(x, "index", 5);
iw.addDocument(doc);
diff --git a/lucene/src/java/org/apache/lucene/index/IndexWriter.java b/lucene/src/java/org/apache/lucene/index/IndexWriter.java
index 0f111be36dd..83de1c1a969 100644
--- a/lucene/src/java/org/apache/lucene/index/IndexWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/IndexWriter.java
@@ -50,13 +50,13 @@ import java.util.Date;
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
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,
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
open the existing index.</p>
@@ -72,11 +72,11 @@ import java.util.Date;
<p>These changes are buffered in memory and periodically
flushed to the {@link Directory} (during the above method
calls). A flush is triggered when there are enough
- buffered deletes (see {@link #setMaxBufferedDeleteTerms})
+ buffered deletes (see {@link IndexWriterConfig#setMaxBufferedDeleteTerms})
or enough added documents since the last flush, whichever
is sooner. For the added documents, flushing is triggered
either by RAM usage of the documents (see {@link
- #setRAMBufferSizeMB}) or the number of added documents.
+ IndexWriterConfig#setRAMBufferSizeMB}) or the number of added documents.
The default is to flush when RAM usage hits 16 MB. For
best indexing speed you should flush by RAM usage with a
large RAM buffer. Note that flushing just moves the
@@ -1252,8 +1252,8 @@ public class IndexWriter implements Closeable {
/**
* 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,
+ * 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
@@ -1301,7 +1301,7 @@ public class IndexWriter implements Closeable {
/**
* Adds a document to this index, using the provided analyzer instead of the
* value of {@link #getAnalyzer()}. If the document contains more than
- * {@link #setMaxFieldLength(int)} terms for a given field, the remainder are
+ * {@link IndexWriterConfig#setMaxFieldLength(int)} terms for a given field, the remainder are
* discarded.
*
* <p>See {@link #addDocument(Document)} for details on
@@ -1608,7 +1608,7 @@ public class IndexWriter implements Closeable {
*
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
- * @see LogMergePolicy#findMergesForOptimize
+ * @see MergePolicy#findMergesForOptimize
*/
public void optimize() throws CorruptIndexException, IOException {
optimize(true);
@@ -2289,8 +2289,7 @@ public class IndexWriter implements Closeable {
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
- public void addIndexes(IndexReader... readers)
- throws CorruptIndexException, IOException {
+ public void addIndexes(IndexReader... readers) throws CorruptIndexException, IOException {
ensureOpen();
try {
@@ -2303,47 +2302,33 @@ public class IndexWriter implements Closeable {
int docCount = merger.merge(); // merge 'em
- SegmentInfo info = null;
+ SegmentInfo info = new SegmentInfo(mergedName, docCount, directory,
+ false, -1, null, false, merger.hasProx(), merger.getSegmentCodecs());
+ setDiagnostics(info, "addIndexes(IndexReader...)");
+
+ boolean useCompoundFile;
+ synchronized(this) { // Guard segmentInfos
+ useCompoundFile = mergePolicy.useCompoundFile(segmentInfos, info);
+ }
+
+ // Now create the compound file if needed
+ if (useCompoundFile) {
+ merger.createCompoundFile(mergedName + ".cfs", info);
+ info.setUseCompoundFile(true);
+
+ // delete new non cfs files directly: they were never
+ // registered with IFD
+ deleter.deleteNewFiles(merger.getMergedFiles(info));
+ }
+
+ // Register the new segment
synchronized(this) {
- info = new SegmentInfo(mergedName, docCount, directory, false, -1,
- null, false, merger.hasProx(), merger.getSegmentCodecs());
- setDiagnostics(info, "addIndexes(IndexReader...)");
segmentInfos.add(info);
- checkpoint();
// Notify DocumentsWriter that the flushed count just increased
docWriter.updateFlushedDocCount(docCount);
- }
-
- // Now create the compound file if needed
- if (mergePolicy instanceof LogMergePolicy && ((LogMergePolicy) mergePolicy).getUseCompoundFile()) {
-
- List<String> files = null;
-
- 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);
- }
- }
-
- if (files != null) {
- try {
- merger.createCompoundFile(mergedName + ".cfs", info);
- synchronized(this) {
- info.setUseCompoundFile(true);
- checkpoint();
- }
- } finally {
- synchronized(this) {
- deleter.decRef(files);
- }
- }
- }
+
+ checkpoint();
}
} catch (OutOfMemoryError oom) {
handleOOM(oom, "addIndexes(IndexReader...)");
@@ -3447,8 +3432,12 @@ public class IndexWriter implements Closeable {
//System.out.println("merger set hasProx=" + merger.hasProx() + " seg=" + merge.info.name);
merge.info.setHasProx(merger.hasProx());
- if (merge.useCompoundFile) {
+ boolean useCompoundFile;
+ synchronized (this) { // Guard segmentInfos
+ useCompoundFile = mergePolicy.useCompoundFile(segmentInfos, merge.info);
+ }
+ if (useCompoundFile) {
success = false;
final String compoundFileName = IndexFileNames.segmentFileName(mergedName, "", IndexFileNames.COMPOUND_FILE_EXTENSION);
diff --git a/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java b/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java
index 876d5f9271d..17e42350901 100644
--- a/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java
+++ b/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java
@@ -127,8 +127,21 @@ public abstract class LogMergePolicy extends MergePolicy {
// Javadoc inherited
@Override
- public boolean useCompoundFile(SegmentInfos infos, SegmentInfo info) {
- return useCompoundFile;
+ public boolean useCompoundFile(SegmentInfos infos, SegmentInfo mergedInfo) throws IOException {
+ final boolean doCFS;
+
+ if (!useCompoundFile) {
+ doCFS = false;
+ } else if (noCFSRatio == 1.0) {
+ doCFS = true;
+ } else {
+ long totalSize = 0;
+ for (SegmentInfo info : infos)
+ totalSize += size(info);
+
+ doCFS = size(mergedInfo) <= noCFSRatio * totalSize;
+ }
+ return doCFS;
}
/** Sets whether compound file format should be used for
@@ -254,12 +267,12 @@ public abstract class LogMergePolicy extends MergePolicy {
// 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(makeOneMerge(infos, infos.range(start + 1, last)));
+ 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(makeOneMerge(infos, infos.range(start, last)));
+ spec.add(new OneMerge(infos.range(start, last)));
last = start;
}
--start;
@@ -267,7 +280,7 @@ public abstract class LogMergePolicy extends MergePolicy {
// Add any left-over segments, unless there is just 1 already optimized.
if (last > 0 && (++start + 1 < last || !isOptimized(infos.info(start)))) {
- spec.add(makeOneMerge(infos, infos.range(start, last)));
+ spec.add(new OneMerge(infos.range(start, last)));
}
return spec.merges.size() == 0 ? null : spec;
@@ -284,7 +297,7 @@ public abstract class LogMergePolicy extends MergePolicy {
// First, enroll all "full" merges (size
// mergeFactor) to potentially be run concurrently:
while (last - maxNumSegments + 1 >= mergeFactor) {
- spec.add(makeOneMerge(infos, infos.range(last-mergeFactor, last)));
+ spec.add(new OneMerge(infos.range(last - mergeFactor, last)));
last -= mergeFactor;
}
@@ -296,7 +309,7 @@ public abstract class LogMergePolicy extends MergePolicy {
// Since we must optimize down to 1 segment, the
// choice is simple:
if (last > 1 || !isOptimized(infos.info(0))) {
- spec.add(makeOneMerge(infos, infos.range(0, last)));
+ spec.add(new OneMerge(infos.range(0, last)));
}
} else if (last > maxNumSegments) {
@@ -325,7 +338,7 @@ public abstract class LogMergePolicy extends MergePolicy {
}
}
- spec.add(makeOneMerge(infos, infos.range(bestStart, bestStart+finalMergeSize)));
+ spec.add(new OneMerge(infos.range(bestStart, bestStart + finalMergeSize)));
}
}
return spec.merges.size() == 0 ? null : spec;
@@ -413,7 +426,7 @@ public abstract class LogMergePolicy extends MergePolicy {
// deletions, so force a merge now:
if (verbose())
message(" add merge " + firstSegmentWithDeletions + " to " + (i-1) + " inclusive");
- spec.add(makeOneMerge(segmentInfos, segmentInfos.range(firstSegmentWithDeletions, i)));
+ spec.add(new OneMerge(segmentInfos.range(firstSegmentWithDeletions, i)));
firstSegmentWithDeletions = i;
}
} else if (firstSegmentWithDeletions != -1) {
@@ -422,7 +435,7 @@ public abstract class LogMergePolicy extends MergePolicy {
// mergeFactor segments
if (verbose())
message(" add merge " + firstSegmentWithDeletions + " to " + (i-1) + " inclusive");
- spec.add(makeOneMerge(segmentInfos, segmentInfos.range(firstSegmentWithDeletions, i)));
+ spec.add(new OneMerge(segmentInfos.range(firstSegmentWithDeletions, i)));
firstSegmentWithDeletions = -1;
}
}
@@ -430,7 +443,7 @@ public abstract class LogMergePolicy extends MergePolicy {
if (firstSegmentWithDeletions != -1) {
if (verbose())
message(" add merge " + firstSegmentWithDeletions + " to " + (numSegments-1) + " inclusive");
- spec.add(makeOneMerge(segmentInfos, segmentInfos.range(firstSegmentWithDeletions, numSegments)));
+ spec.add(new OneMerge(segmentInfos.range(firstSegmentWithDeletions, numSegments)));
}
return spec;
@@ -530,7 +543,7 @@ public abstract class LogMergePolicy extends MergePolicy {
spec = new MergeSpecification();
if (verbose())
message(" " + start + " to " + end + ": add this merge");
- spec.add(makeOneMerge(infos, infos.range(start, end)));
+ spec.add(new OneMerge(infos.range(start, end)));
} else if (verbose())
message(" " + start + " to " + end + ": contains segment over maxMergeSize or maxMergeDocs; skipping");
@@ -544,29 +557,6 @@ public abstract class LogMergePolicy extends MergePolicy {
return spec;
}
- protected OneMerge makeOneMerge(SegmentInfos infos, SegmentInfos infosToMerge) throws IOException {
- final boolean doCFS;
- if (!useCompoundFile) {
- doCFS = false;
- } else if (noCFSRatio == 1.0) {
- doCFS = true;
- } else {
-
- long totSize = 0;
- for(SegmentInfo info : infos) {
- totSize += size(info);
- }
- long mergeSize = 0;
- for(SegmentInfo info : infosToMerge) {
- mergeSize += size(info);
- }
-
- doCFS = mergeSize <= noCFSRatio * totSize;
- }
-
- return new OneMerge(infosToMerge, doCFS);
- }
-
/** <p>Determines the largest segment (measured by
* document count) that may be merged with other segments.
* Small values (e.g., less than 10,000) are best for
diff --git a/lucene/src/java/org/apache/lucene/index/MergePolicy.java b/lucene/src/java/org/apache/lucene/index/MergePolicy.java
index 205a4060ba5..5be40254489 100644
--- a/lucene/src/java/org/apache/lucene/index/MergePolicy.java
+++ b/lucene/src/java/org/apache/lucene/index/MergePolicy.java
@@ -76,16 +76,14 @@ public abstract class MergePolicy implements java.io.Closeable {
SegmentReader[] readers; // used by IndexWriter
SegmentReader[] readersClone; // used by IndexWriter
public final SegmentInfos segments;
- public final boolean useCompoundFile;
boolean aborted;
Throwable error;
boolean paused;
- public OneMerge(SegmentInfos segments, boolean useCompoundFile) {
+ public OneMerge(SegmentInfos segments) {
if (0 == segments.size())
throw new RuntimeException("segments must include at least one segment");
this.segments = segments;
- this.useCompoundFile = useCompoundFile;
}
/** Record that an exception occurred while executing
@@ -314,10 +312,9 @@ public abstract class MergePolicy implements java.io.Closeable {
public abstract void close();
/**
- * Returns true if a newly flushed (not from merge)
- * segment should use the compound file format.
+ * Returns true if a new segment (regardless of its origin) should use the compound file format.
*/
- public abstract boolean useCompoundFile(SegmentInfos segments, SegmentInfo newSegment);
+ public abstract boolean useCompoundFile(SegmentInfos segments, SegmentInfo newSegment) throws IOException;
/**
* Returns true if the doc store files should use the
diff --git a/lucene/src/java/org/apache/lucene/search/cache/ByteValuesCreator.java b/lucene/src/java/org/apache/lucene/search/cache/ByteValuesCreator.java
index 04b092ab7a5..d28494b5db8 100644
--- a/lucene/src/java/org/apache/lucene/search/cache/ByteValuesCreator.java
+++ b/lucene/src/java/org/apache/lucene/search/cache/ByteValuesCreator.java
@@ -110,7 +110,6 @@ public class ByteValuesCreator extends CachedArrayCreator<ByteValues>
vals.values = new byte[maxDoc];
if (terms != null) {
final TermsEnum termsEnum = terms.iterator();
- final Bits delDocs = MultiFields.getDeletedDocs(reader);
OpenBitSet validBits = (hasOption(OPTION_CACHE_BITS)) ? new OpenBitSet( maxDoc ) : null;
DocsEnum docs = null;
try {
@@ -120,7 +119,7 @@ public class ByteValuesCreator extends CachedArrayCreator<ByteValues>
break;
}
final byte termval = parser.parseByte(term);
- docs = termsEnum.docs(delDocs, docs);
+ docs = termsEnum.docs(null, docs);
while (true) {
final int docID = docs.nextDoc();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
@@ -137,7 +136,7 @@ public class ByteValuesCreator extends CachedArrayCreator<ByteValues>
} catch (FieldCache.StopFillCacheException stop) {}
if( vals.valid == null ) {
- vals.valid = checkMatchAllBits( delDocs, validBits, vals.numDocs, maxDoc );
+ vals.valid = checkMatchAllBits( validBits, vals.numDocs, maxDoc );
}
}
if( vals.valid == null && vals.numDocs < 1 ) {
diff --git a/lucene/src/java/org/apache/lucene/search/cache/CachedArrayCreator.java b/lucene/src/java/org/apache/lucene/search/cache/CachedArrayCreator.java
index b65b61478ae..3129c755495 100644
--- a/lucene/src/java/org/apache/lucene/search/cache/CachedArrayCreator.java
+++ b/lucene/src/java/org/apache/lucene/search/cache/CachedArrayCreator.java
@@ -100,22 +100,13 @@ public abstract class CachedArrayCreator<T extends CachedArray> extends EntryCre
/**
* Utility function to help check what bits are valid
*/
- protected Bits checkMatchAllBits( Bits deleted, OpenBitSet valid, int numDocs, int maxDocs )
+ protected Bits checkMatchAllBits( OpenBitSet valid, int numDocs, int maxDocs )
{
if( numDocs != maxDocs ) {
if( hasOption( OPTION_CACHE_BITS ) ) {
- if( deleted == null ) {
- for( int i=0; i<maxDocs; i++ ) {
- if( !valid.get(i) ) {
- return valid;
- }
- }
- }
- else {
- for( int i=0; i<maxDocs; i++ ) {
- if( !deleted.get(i) && !valid.get(i) ) {
- return valid;
- }
+ for( int i=0; i<maxDocs; i++ ) {
+ if( !valid.get(i) ) {
+ return valid;
}
}
}
@@ -132,7 +123,6 @@ public abstract class CachedArrayCreator<T extends CachedArray> extends EntryCre
Terms terms = MultiFields.getTerms(reader, field);
if (terms != null) {
final TermsEnum termsEnum = terms.iterator();
- final Bits delDocs = MultiFields.getDeletedDocs(reader);
OpenBitSet validBits = new OpenBitSet( reader.maxDoc() );
DocsEnum docs = null;
while(true) {
@@ -140,7 +130,7 @@ public abstract class CachedArrayCreator<T extends CachedArray> extends EntryCre
if (term == null) {
break;
}
- docs = termsEnum.docs(delDocs, docs);
+ docs = termsEnum.docs(null, docs);
while (true) {
final int docID = docs.nextDoc();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
@@ -152,7 +142,7 @@ public abstract class CachedArrayCreator<T extends CachedArray> extends EntryCre
vals.numTerms++;
}
- vals.valid = checkMatchAllBits( delDocs, validBits, vals.numDocs, reader.maxDoc() );
+ vals.valid = checkMatchAllBits( validBits, vals.numDocs, reader.maxDoc() );
}
if( vals.numDocs < 1 ) {
vals.valid = new Bits.MatchNoBits( reader.maxDoc() );
diff --git a/lucene/src/java/org/apache/lucene/search/cache/DocTermsIndexCreator.java b/lucene/src/java/org/apache/lucene/search/cache/DocTermsIndexCreator.java
index b204111353e..2f0bb06e79d 100644
--- a/lucene/src/java/org/apache/lucene/search/cache/DocTermsIndexCreator.java
+++ b/lucene/src/java/org/apache/lucene/search/cache/DocTermsIndexCreator.java
@@ -130,7 +130,6 @@ public class DocTermsIndexCreator extends EntryCreatorWithOptions<DocTermsIndex>
if (terms != null) {
final TermsEnum termsEnum = terms.iterator();
- final Bits delDocs = MultiFields.getDeletedDocs(reader);
DocsEnum docs = null;
while(true) {
@@ -149,7 +148,7 @@ public class DocTermsIndexCreator extends EntryCreatorWithOptions<DocTermsIndex>
termOrdToBytesOffset = termOrdToBytesOffset.resize(ArrayUtil.oversize(1+termOrd, 1));
}
termOrdToBytesOffset.set(termOrd, bytes.copyUsingLengthPrefix(term));
- docs = termsEnum.docs(delDocs, docs);
+ docs = termsEnum.docs(null, docs);
while (true) {
final int docID = docs.nextDoc();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
diff --git a/lucene/src/java/org/apache/lucene/search/cache/DoubleValuesCreator.java b/lucene/src/java/org/apache/lucene/search/cache/DoubleValuesCreator.java
index de5171a00b4..a72a322e0dc 100644
--- a/lucene/src/java/org/apache/lucene/search/cache/DoubleValuesCreator.java
+++ b/lucene/src/java/org/apache/lucene/search/cache/DoubleValuesCreator.java
@@ -120,7 +120,6 @@ public class DoubleValuesCreator extends CachedArrayCreator<DoubleValues>
vals.values = null;
if (terms != null) {
final TermsEnum termsEnum = terms.iterator();
- final Bits delDocs = MultiFields.getDeletedDocs(reader);
OpenBitSet validBits = (hasOption(OPTION_CACHE_BITS)) ? new OpenBitSet( maxDoc ) : null;
DocsEnum docs = null;
try {
@@ -130,7 +129,7 @@ public class DoubleValuesCreator extends CachedArrayCreator<DoubleValues>
break;
}
final double termval = parser.parseDouble(term);
- docs = termsEnum.docs(delDocs, docs);
+ docs = termsEnum.docs(null, docs);
while (true) {
final int docID = docs.nextDoc();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
@@ -150,7 +149,7 @@ public class DoubleValuesCreator extends CachedArrayCreator<DoubleValues>
} catch (FieldCache.StopFillCacheException stop) {}
if( vals.valid == null ) {
- vals.valid = checkMatchAllBits( delDocs, validBits, vals.numDocs, maxDoc );
+ vals.valid = checkMatchAllBits( validBits, vals.numDocs, maxDoc );
}
}
diff --git a/lucene/src/java/org/apache/lucene/search/cache/FloatValuesCreator.java b/lucene/src/java/org/apache/lucene/search/cache/FloatValuesCreator.java
index b111dfa5492..42191168361 100644
--- a/lucene/src/java/org/apache/lucene/search/cache/FloatValuesCreator.java
+++ b/lucene/src/java/org/apache/lucene/search/cache/FloatValuesCreator.java
@@ -121,7 +121,6 @@ public class FloatValuesCreator extends CachedArrayCreator<FloatValues>
vals.values = null;
if (terms != null) {
final TermsEnum termsEnum = terms.iterator();
- final Bits delDocs = MultiFields.getDeletedDocs(reader);
OpenBitSet validBits = (hasOption(OPTION_CACHE_BITS)) ? new OpenBitSet( maxDoc ) : null;
DocsEnum docs = null;
try {
@@ -131,7 +130,7 @@ public class FloatValuesCreator extends CachedArrayCreator<FloatValues>
break;
}
final float termval = parser.parseFloat(term);
- docs = termsEnum.docs(delDocs, docs);
+ docs = termsEnum.docs(null, docs);
while (true) {
final int docID = docs.nextDoc();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
@@ -151,7 +150,7 @@ public class FloatValuesCreator extends CachedArrayCreator<FloatValues>
} catch (FieldCache.StopFillCacheException stop) {}
if( vals.valid == null ) {
- vals.valid = checkMatchAllBits( delDocs, validBits, vals.numDocs, maxDoc );
+ vals.valid = checkMatchAllBits( validBits, vals.numDocs, maxDoc );
}
}
diff --git a/lucene/src/java/org/apache/lucene/search/cache/IntValuesCreator.java b/lucene/src/java/org/apache/lucene/search/cache/IntValuesCreator.java
index a739dca4048..287fcb43113 100644
--- a/lucene/src/java/org/apache/lucene/search/cache/IntValuesCreator.java
+++ b/lucene/src/java/org/apache/lucene/search/cache/IntValuesCreator.java
@@ -121,7 +121,6 @@ public class IntValuesCreator extends CachedArrayCreator<IntValues>
vals.values = null;
if (terms != null) {
final TermsEnum termsEnum = terms.iterator();
- final Bits delDocs = MultiFields.getDeletedDocs(reader);
OpenBitSet validBits = (hasOption(OPTION_CACHE_BITS)) ? new OpenBitSet( maxDoc ) : null;
DocsEnum docs = null;
try {
@@ -131,7 +130,7 @@ public class IntValuesCreator extends CachedArrayCreator<IntValues>
break;
}
final int termval = parser.parseInt(term);
- docs = termsEnum.docs(delDocs, docs);
+ docs = termsEnum.docs(null, docs);
while (true) {
final int docID = docs.nextDoc();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
@@ -151,7 +150,7 @@ public class IntValuesCreator extends CachedArrayCreator<IntValues>
} catch (FieldCache.StopFillCacheException stop) {}
if( vals.valid == null ) {
- vals.valid = checkMatchAllBits( delDocs, validBits, vals.numDocs, maxDoc );
+ vals.valid = checkMatchAllBits( validBits, vals.numDocs, maxDoc );
}
}
diff --git a/lucene/src/java/org/apache/lucene/search/cache/LongValuesCreator.java b/lucene/src/java/org/apache/lucene/search/cache/LongValuesCreator.java
index 60174dab46c..f28eee7ce0d 100644
--- a/lucene/src/java/org/apache/lucene/search/cache/LongValuesCreator.java
+++ b/lucene/src/java/org/apache/lucene/search/cache/LongValuesCreator.java
@@ -121,7 +121,6 @@ public class LongValuesCreator extends CachedArrayCreator<LongValues>
vals.values = null;
if (terms != null) {
final TermsEnum termsEnum = terms.iterator();
- final Bits delDocs = MultiFields.getDeletedDocs(reader);
OpenBitSet validBits = (hasOption(OPTION_CACHE_BITS)) ? new OpenBitSet( maxDoc ) : null;
DocsEnum docs = null;
try {
@@ -131,7 +130,7 @@ public class LongValuesCreator extends CachedArrayCreator<LongValues>
break;
}
final long termval = parser.parseLong(term);
- docs = termsEnum.docs(delDocs, docs);
+ docs = termsEnum.docs(null, docs);
while (true) {
final int docID = docs.nextDoc();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
@@ -151,7 +150,7 @@ public class LongValuesCreator extends CachedArrayCreator<LongValues>
} catch (FieldCache.StopFillCacheException stop) {}
if( vals.valid == null ) {
- vals.valid = checkMatchAllBits( delDocs, validBits, vals.numDocs, maxDoc );
+ vals.valid = checkMatchAllBits( validBits, vals.numDocs, maxDoc );
}
}
diff --git a/lucene/src/java/org/apache/lucene/search/cache/ShortValuesCreator.java b/lucene/src/java/org/apache/lucene/search/cache/ShortValuesCreator.java
index af723846aae..603fcbbb1f8 100644
--- a/lucene/src/java/org/apache/lucene/search/cache/ShortValuesCreator.java
+++ b/lucene/src/java/org/apache/lucene/search/cache/ShortValuesCreator.java
@@ -111,7 +111,6 @@ public class ShortValuesCreator extends CachedArrayCreator<ShortValues>
vals.values = new short[maxDoc];
if (terms != null) {
final TermsEnum termsEnum = terms.iterator();
- final Bits delDocs = MultiFields.getDeletedDocs(reader);
OpenBitSet validBits = (hasOption(OPTION_CACHE_BITS)) ? new OpenBitSet( maxDoc ) : null;
DocsEnum docs = null;
try {
@@ -121,7 +120,7 @@ public class ShortValuesCreator extends CachedArrayCreator<ShortValues>
break;
}
final Short termval = parser.parseShort(term);
- docs = termsEnum.docs(delDocs, docs);
+ docs = termsEnum.docs(null, docs);
while (true) {
final int docID = docs.nextDoc();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
@@ -138,7 +137,7 @@ public class ShortValuesCreator extends CachedArrayCreator<ShortValues>
} catch (FieldCache.StopFillCacheException stop) {}
if( vals.valid == null ) {
- vals.valid = checkMatchAllBits( delDocs, validBits, vals.numDocs, maxDoc );
+ vals.valid = checkMatchAllBits( validBits, vals.numDocs, maxDoc );
}
}
if( vals.valid == null && vals.numDocs < 1 ) {
diff --git a/lucene/src/test/org/apache/lucene/index/TestAddIndexes.java b/lucene/src/test/org/apache/lucene/index/TestAddIndexes.java
index 6b2714dfff7..e7b3eed046c 100755
--- a/lucene/src/test/org/apache/lucene/index/TestAddIndexes.java
+++ b/lucene/src/test/org/apache/lucene/index/TestAddIndexes.java
@@ -24,6 +24,9 @@ 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;
@@ -36,6 +39,7 @@ import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.Version;
import org.apache.lucene.util._TestUtil;
public class TestAddIndexes extends LuceneTestCase {
@@ -1014,5 +1018,30 @@ public class TestAddIndexes extends LuceneTestCase {
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 --git a/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java b/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
index cef3c30d69f..f178f058e53 100644
--- a/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
+++ b/lucene/src/test/org/apache/lucene/index/TestBackwardsCompatibility.java
@@ -527,12 +527,15 @@ public class TestBackwardsCompatibility extends LuceneTestCase {
try {
Directory dir = FSDirectory.open(new File(fullDir(outputDir)));
+ LogMergePolicy mergePolicy = newLogMergePolicy(true, 10);
+ mergePolicy.setNoCFSRatio(1); // This test expects all of its segments to be in CFS
+
IndexWriter writer = new IndexWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
setMaxBufferedDocs(-1).
setRAMBufferSizeMB(16.0).
- setMergePolicy(newLogMergePolicy(true, 10))
+ setMergePolicy(mergePolicy)
);
for(int i=0;i<35;i++) {
addDoc(writer, i);
diff --git a/lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.java b/lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.java
index 0ff5d34d962..025f7c061de 100644
--- a/lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexFileDeleter.java
@@ -40,18 +40,23 @@ 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
+
IndexWriter writer = new IndexWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
setMaxBufferedDocs(10).
- setMergePolicy(newLogMergePolicy(true, 10))
+ setMergePolicy(mergePolicy)
);
+
int i;
for(i=0;i<35;i++) {
addDoc(writer, i);
}
- ((LogMergePolicy) writer.getConfig().getMergePolicy()).setUseCompoundFile(false);
- ((LogMergePolicy) writer.getConfig().getMergePolicy()).setUseCompoundDocStore(false);
+ mergePolicy.setUseCompoundFile(false);
+ mergePolicy.setUseCompoundDocStore(false);
for(;i<45;i++) {
addDoc(writer, i);
}
diff --git a/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java b/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java
index c41c765f6aa..ecbf3fa92fa 100644
--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java
@@ -2479,10 +2479,14 @@ public class TestIndexWriter extends LuceneTestCase {
public void testDeleteUnusedFiles() throws Exception {
for(int iter=0;iter<2;iter++) {
Directory dir = newDirectory();
+
+ LogMergePolicy mergePolicy = newLogMergePolicy(true);
+ mergePolicy.setNoCFSRatio(1); // This test expects all of its segments to be in CFS
+
IndexWriter w = new IndexWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()).
- setMergePolicy(newLogMergePolicy(true))
+ setMergePolicy(mergePolicy)
);
Document doc = new Document();
doc.add(newField("field", "go", Field.Store.NO, Field.Index.ANALYZED));
diff --git a/lucene/src/test/org/apache/lucene/search/TestSearchWithThreads.java b/lucene/src/test/org/apache/lucene/search/TestSearchWithThreads.java
new file mode 100644
index 00000000000..97d6e86aa56
--- /dev/null
+++ b/lucene/src/test/org/apache/lucene/search/TestSearchWithThreads.java
@@ -0,0 +1,109 @@
+package org.apache.lucene.search;
+
+/**
+ * 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.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.RandomIndexWriter;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.util.LuceneTestCase;
+
+public class TestSearchWithThreads extends LuceneTestCase {
+
+ final int NUM_DOCS = 10000;
+ final int NUM_SEARCH_THREADS = 5;
+ final int RUN_TIME_MSEC = 1000 * RANDOM_MULTIPLIER;
+
+ public void test() throws Exception {
+ final Directory dir = newDirectory();
+ final RandomIndexWriter w = new RandomIndexWriter(random, dir);
+
+ final long startTime = System.currentTimeMillis();
+
+ // TODO: replace w/ the @nightly test data; make this
+ // into an optional @nightly stress test
+ final Document doc = new Document();
+ final Field body = newField("body", "", Field.Index.ANALYZED);
+ doc.add(body);
+ final StringBuilder sb = new StringBuilder();
+ for(int docCount=0;docCount<NUM_DOCS*RANDOM_MULTIPLIER;docCount++) {
+ final int numTerms = random.nextInt(10);
+ for(int termCount=0;termCount<numTerms;termCount++) {
+ sb.append(random.nextBoolean() ? "aaa" : "bbb");
+ sb.append(' ');
+ }
+ body.setValue(sb.toString());
+ w.addDocument(doc);
+ sb.delete(0, sb.length());
+ }
+ final IndexReader r = w.getReader();
+ w.close();
+
+ final long endTime = System.currentTimeMillis();
+ if (VERBOSE) System.out.println("BUILD took " + (endTime-startTime));
+
+ final IndexSearcher s = new IndexSearcher(r);
+
+ final AtomicBoolean failed = new AtomicBoolean();
+ final long stopAt = System.currentTimeMillis() + RUN_TIME_MSEC;
+ final AtomicLong netSearch = new AtomicLong();
+
+ Thread[] threads = new Thread[NUM_SEARCH_THREADS];
+ for(int threadID=0;threadID<NUM_SEARCH_THREADS;threadID++) {
+ threads[threadID] = new Thread() {
+ TotalHitCountCollector col = new TotalHitCountCollector();
+ @Override
+ public void run() {
+ try {
+ long totHits = 0;
+ long totSearch = 0;
+ while(System.currentTimeMillis() < stopAt && !failed.get()) {
+ s.search(new TermQuery(new Term("body", "aaa")), col);
+ totHits += col.getTotalHits();
+ s.search(new TermQuery(new Term("body", "bbb")), col);
+ totHits += col.getTotalHits();
+ totSearch++;
+ }
+ assertTrue(totHits > 0);
+ netSearch.addAndGet(totSearch);
+ } catch (Exception exc) {
+ failed.set(true);
+ throw new RuntimeException(exc);
+ }
+ }
+ };
+ threads[threadID].setDaemon(true);
+ threads[threadID].start();
+ }
+
+ for(int threadID=0;threadID<NUM_SEARCH_THREADS;threadID++) {
+ threads[threadID].join();
+ }
+ if (VERBOSE) System.out.println(NUM_SEARCH_THREADS + " threads did " + netSearch.get() + " searches");
+
+ s.close();
+ r.close();
+ dir.close();
+ }
+}
diff --git a/lucene/src/test/org/apache/lucene/util/LuceneJUnitResultFormatter.java b/lucene/src/test/org/apache/lucene/util/LuceneJUnitResultFormatter.java
index c2895d8ec65..1f6c76d6401 100644
--- a/lucene/src/test/org/apache/lucene/util/LuceneJUnitResultFormatter.java
+++ b/lucene/src/test/org/apache/lucene/util/LuceneJUnitResultFormatter.java
@@ -18,6 +18,7 @@
package org.apache.lucene.util;
+import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
@@ -59,7 +60,7 @@ public class LuceneJUnitResultFormatter implements JUnitResultFormatter {
private String systemError = null;
/** Buffer output until the end of the test */
- private StringBuilder sb;
+ private ByteArrayOutputStream sb; // use a BOS for our mostly ascii-output
private static final org.apache.lucene.store.Lock lock;
@@ -80,7 +81,6 @@ public class LuceneJUnitResultFormatter implements JUnitResultFormatter {
/** Constructor for LuceneJUnitResultFormatter. */
public LuceneJUnitResultFormatter() {
- sb = new StringBuilder();
}
/**
@@ -116,13 +116,13 @@ public class LuceneJUnitResultFormatter implements JUnitResultFormatter {
if (out == null) {
return; // Quick return - no output do nothing.
}
+ sb = new ByteArrayOutputStream(); // don't reuse, so its gc'ed
try {
LogManager.getLogManager().readConfiguration();
} catch (Exception e) {}
- sb.setLength(0);
- sb.append("Testsuite: ");
- sb.append(suite.getName());
- sb.append(StringUtils.LINE_SEP);
+ append("Testsuite: ");
+ append(suite.getName());
+ append(StringUtils.LINE_SEP);
}
/**
@@ -130,21 +130,21 @@ public class LuceneJUnitResultFormatter implements JUnitResultFormatter {
* @param suite the test suite
*/
public synchronized void endTestSuite(JUnitTest suite) {
- sb.append("Tests run: ");
- sb.append(suite.runCount());
- sb.append(", Failures: ");
- sb.append(suite.failureCount());
- sb.append(", Errors: ");
- sb.append(suite.errorCount());
- sb.append(", Time elapsed: ");
- sb.append(numberFormat.format(suite.getRunTime() / ONE_SECOND));
- sb.append(" sec");
- sb.append(StringUtils.LINE_SEP);
- sb.append(StringUtils.LINE_SEP);
+ append("Tests run: ");
+ append(suite.runCount());
+ append(", Failures: ");
+ append(suite.failureCount());
+ append(", Errors: ");
+ append(suite.errorCount());
+ append(", Time elapsed: ");
+ append(numberFormat.format(suite.getRunTime() / ONE_SECOND));
+ append(" sec");
+ append(StringUtils.LINE_SEP);
+ append(StringUtils.LINE_SEP);
// append the err and output streams to the log
if (systemOutput != null && systemOutput.length() > 0) {
- sb.append("------------- Standard Output ---------------")
+ append("------------- Standard Output ---------------")
.append(StringUtils.LINE_SEP)
.append(systemOutput)
.append("------------- ---------------- ---------------")
@@ -152,7 +152,7 @@ public class LuceneJUnitResultFormatter implements JUnitResultFormatter {
}
if (systemError != null && systemError.length() > 0) {
- sb.append("------------- Standard Error -----------------")
+ append("------------- Standard Error -----------------")
.append(StringUtils.LINE_SEP)
.append(systemError)
.append("------------- ---------------- ---------------")
@@ -163,7 +163,7 @@ public class LuceneJUnitResultFormatter implements JUnitResultFormatter {
try {
lock.obtain(5000);
try {
- out.write(sb.toString().getBytes());
+ sb.writeTo(out);
out.flush();
} finally {
try {
@@ -252,14 +252,29 @@ public class LuceneJUnitResultFormatter implements JUnitResultFormatter {
endTest(test);
}
- sb.append(formatTest(test) + type);
- sb.append(StringUtils.LINE_SEP);
- sb.append(error.getMessage());
- sb.append(StringUtils.LINE_SEP);
+ append(formatTest(test) + type);
+ append(StringUtils.LINE_SEP);
+ append(error.getMessage());
+ append(StringUtils.LINE_SEP);
String strace = JUnitTestRunner.getFilteredTrace(error);
- sb.append(strace);
- sb.append(StringUtils.LINE_SEP);
- sb.append(StringUtils.LINE_SEP);
+ append(strace);
+ append(StringUtils.LINE_SEP);
+ append(StringUtils.LINE_SEP);
+ }
+
+ public LuceneJUnitResultFormatter append(String s) {
+ if (s == null)
+ s = "(null)";
+ try {
+ sb.write(s.getBytes()); // intentionally use default charset, its a console.
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return this;
+ }
+
+ public LuceneJUnitResultFormatter append(long l) {
+ return append(Long.toString(l));
}
}