Skip to content

Apache Lucene open-source search software

LUCENE-2812: fix IndexReader.indexExists to return false when segments_N file cannot be read

Michael McCandless625f60388dbf
diff --git a/lucene/src/java/org/apache/lucene/index/IndexReader.java b/lucene/src/java/org/apache/lucene/index/IndexReader.java
index 73266e8831d..560abe58e25 100644
--- a/lucene/src/java/org/apache/lucene/index/IndexReader.java
+++ b/lucene/src/java/org/apache/lucene/index/IndexReader.java
@@ -835,13 +835,17 @@ public abstract class IndexReader implements Cloneable,Closeable {
/**
* Returns <code>true</code> if an index exists at the specified directory.
- * If the directory does not exist or if there is no index in it.
* @param directory the directory to check for an index
* @return <code>true</code> if an index exists; <code>false</code> otherwise
* @throws IOException if there is a problem with accessing the index
*/
public static boolean indexExists(Directory directory) throws IOException {
- return SegmentInfos.getCurrentSegmentGeneration(directory) != -1;
+ try {
+ new SegmentInfos().read(directory);
+ return true;
+ } catch (IOException ioe) {
+ return false;
+ }
}
/** Returns the number of documents in this index. */
diff --git a/lucene/src/test/org/apache/lucene/index/TestIndexReader.java b/lucene/src/test/org/apache/lucene/index/TestIndexReader.java
index b086d589f13..39208d1561d 100644
--- a/lucene/src/test/org/apache/lucene/index/TestIndexReader.java
+++ b/lucene/src/test/org/apache/lucene/index/TestIndexReader.java
@@ -1850,5 +1850,16 @@ public class TestIndexReader extends LuceneTestCase
}
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();
+ }
}