Lucene 使用no segments* file 异常原因

初次使用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();
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值