初次使用Lucene时候,当索引文件为空时,使用IndexReader读取索引时候会报以长no segments* file found ,就是说索引文件为空,因为还没有在该目录建立任何索引文件。
只需要将IndexWriter调用commit()方法即可
package lms.common.utils.lucene;
import java.io.File;
import java.io.IOException;
import net.paoding.analysis.analyzer.PaodingAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
/**
* 初始化Lucene索引基本配置
* @author root
*
*/
public class IndexConfig {
public static String indexDir = "/indexes"; //索引的保存目录
public static IndexReader reader;
public static IndexSearcher searcher;
public static PaodingAnalyzer analyzer = new PaodingAnalyzer();//使用PaodingAnalyzer
public static QueryParser parser;
public static File indexFile;
public static IndexWriterConfig iwc;//IndexWriter配置
public static IndexWriter writer;
public static Version VERSION = Version.LUCENE_36; //索引版本
static{
indexFile = new File(indexDir); //索引文件位置
}
/**
* 初始化写索引组件
*/
public static void writerInit(){
try {
iwc = new IndexWriterConfig(VERSION, analyzer);
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
writer = new IndexWriter(FSDirectory.open(indexFile), iwc);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 初始化读索引组建
*/
public static void readerInit(){
File[] fs = indexFile.listFiles();
if(fs.length == 0){ //如果 索引文件是空,初次使用增量索引时,添加索引文件
writerInit();
try {
writer.commit(); //只需要commit下就OK
} catch (IOException e) {
e.printStackTrace();
}
}
try {
reader = IndexReader.open(FSDirectory.open(indexFile));
searcher= new IndexSearcher(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
}