一、索引优化技巧
1.索引的合并
lucene提供两种索引方式:RAMDirectory(内存)和
FSDirectory(硬盘)。对于频繁的文档的索引操作,统一优先写入内存,再一次性写入硬盘。
lucene提供索引合并的API:
writer.addindexes(new Directory()[]{});
具体步骤:
//使用RAMDirectory
RAMDirectory ramdir= new RAMDirectory();
IndexWriter ramWriter= new IndexWriter(ramdir,iwc);
Document doc=new Document();
doc.add(new StringField("title","lucene",Field.Store.Yes));
doc.add(new TextField("content","...",Field.Store.NO));
ramWriter.addDocument(doc);
ramWriter.close();
Directory dir=FSDirectory.open(new File("E:\\lucene_index"));
Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_42);
IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_42, analyzer);
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
iwc.setInfoStream(System.out);
IndexWriter writer=new IndexWriter(dir,iwc);
writer.addIndexes(new Directory()[]{ramdir});
2.内存消耗flush代替文档数量flush
indexWriter可以自动根据内存消耗调用flush()。可以使用
indexWriterConfig.setRAMBufferSizeMB(double)设置缓冲区大小。测试表明48MB为叫合适值。
3.重用Document和Field
创建Document单一实例,使用Field的setValue方法重用Field。
4.使用单一的IndexWriter实例
二、其他
IndexReader
maxDoc()返回下一个可用的内部Document号,即有效文档和删除文档的总数量
numDocs返回有效文档的数量