other directory implementations
将某个directory装入到RAMDirectory中
Directory ramDir = new RAMDirectory(otherDir)
这个被用来加速搜索,将一个已经存在的在硬盘上的索引放入到ram中
我们也可以反过来:将RAMDirectory中的索引复制到另一个Directory中
Directory.copy(ramDir,otherDir)
该方法只是直接替换otherDir中的文件,需要保证没有indexwriter在ramDir中打开,因为该方法不会加锁
如果otherDir中存在一个index,当你需要将ramDir中documents加入到otherDir的index中,保留otherDir中原来的索引,需要使用下面的方法:IndexWriter.addIndexesNoOptimize
IndexWriter writer = new IndexWriter(otherDir,analyzer,InexWriter.MaxFieldLength.UNLIMITED);
writer.addIndexesNoOptimize(new Directory[]{ramDir});
在IndexWriter中还有其他的addIndexes方法,不过这些方法都有自己的优化措施
MMapDirectory 与FSDirectory一样,将文件存放在文件系统中,不同的地方是
它不是利用io来操作文件,而是利用内存映射
NIOFSDirectory 与FSDirectory一样,将文件存放在文件系统中,不同的地方是它利用的java.nio.*来读取文件,当多线程来读取同一文件时,不用像FSDirecotyr使用锁机制
Concurrency ,thread-safety,and locking issues
1.多个indexReader可以同时打开一个index
2.同一时刻只有一个writer打开一个index
3.indexReaders可以打开,即使有一个IndexWriter在操作index. indexReader看不到任何IndexWriter做的修改, 直到writer提交和reader 重新打开
4.多个线程可以分享同一个IndexReader或者IndexWirter实例
index locking
indexWriter或者indexReader执行删除或者修改norms,lucene会加锁
当企图在同一个index上建立另外一个writer会出现LockObtainFialedException
lucene允许改变锁机制,lockFactory的子类称为锁机制实现,然后调用Directory.setLockFactory,该方法需要在indexWriter打开之前执行
建立自己的锁机制时,lucene提供了一个工具来判断锁机制实现是否正确
LockStreassTest(org.apache.lucene.store)
package chapter02;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.Before;
import org.junit.Test;
public class LockTest {
private Directory dir;
@Before
public void setUp() throws IOException {
String indexDir = System.getProperty("java.io.tmpdir", "tmp") + System.getProperty("file.separetor") + "index";
dir = FSDirectory.getDirectory(indexDir);
}
@Test
public void testWriterLock() throws IOException {
IndexWriter writer1 = null;
IndexWriter writer2 = null;
try {
writer1 = new IndexWriter(dir, new SimpleAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED);
writer2 = new IndexWriter(dir, new SimpleAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED);
fail("we should never reach this point");
} catch (LockObtainFailedException e) {
e.printStackTrace();
} finally {
writer1.close();
assertNull(writer2);
}
}
}