luence基础学习——no segments* file found in org.apache.lu异常处理

本文介绍如何使用Lucene创建和读取索引,包括Directory、Analyzer、IndexWriter等核心组件的使用方法,并通过示例代码展示了索引创建过程中常见的错误及解决办法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

建立索引:
public void testCreateIndex() throws Exception{
		Directory directory=FSDirectory.open(new File("D:/index"));
		//lucene当前使用的版本
		Version version=Version.LUCENE_44;
		//抽象类。。。分词器,,,,对一段文本进行分词
		Analyzer analyzer=new StandardAnalyzer(version);
		
		IndexWriterConfig writerConfig=new IndexWriterConfig(version, analyzer);
		IndexWriter indexWriter=new IndexWriter(directory, writerConfig);
		
		Document doc=new Document();
		//构造索引document对应的字段,inxdexableFild是一个接口,
		IndexableField field=new IntField("id", 1, Store.YES);
		
		IndexableField stringField=new StringField("title", "小苹果成功逆袭", Store.YES);
		
		IndexableField testField=new TextField("content", "你是我的小呀小苹果", Store.YES);
		
		doc.add(field);
		doc.add(testField);
		doc.add(stringField);
		
		
		indexWriter.addDocument(doc);
		//indexWriter.close();
	}
读取索引:
<pre name="code" class="java">@Test
	public void SearchTest() throws Exception{
		Directory directory=FSDirectory.open(new File("D:/index"));
		IndexReader r=DirectoryReader.open(directory);
		//索引读取器
		IndexSearcher indexSearcher=new IndexSearcher(r);
		//query是一个查询对象,具体的查询规则
		
		Query query=new TermQuery(new Term("content","苹"));
		//检索符合条件的前面n条记录
		TopDocs topDocs = indexSearcher.search(query, 100);
		//返回命中文档的id
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			int doce = scoreDoc.doc;
			Document document = indexSearcher.doc(doce);
			System.out.println("id=="+document.get("id"));
			System.out.println("title=="+document.get("title"));
			System.out.println("content=="+document.get("content"));
		}
	}

建立索引时没有出错,但是读取索引时出现如上错误,查看索引的目录,显示索引目录都为0kb,导致此问题的原因是因为没有关流的原因,也就是
indexWriter.close();导致没有写入到索引中去,所以出现此异常


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值