2lucene如何创建一个索引

本文提供了一个使用Lucene 3.1.0创建文本索引的具体示例,包括设置文档路径、索引存储路径及采用StandardAnalyzer进行分析的过程。

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

根据前面的那个例子,写出如下创建索引的例子,搞了老半天能,
3.0的和3.1.0的居然也那么的不一样。。。
先放着,以后备用


import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class LuceneTest {

String docsPath = null; //文件位置
String indexPath =null; //索引位置
public static void main(String[] args) {
LuceneTest test = new LuceneTest();

try {
test.index();
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LockObtainFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
/**
* 先创立索引
* @throws IOException
* @throws LockObtainFailedException
* @throws CorruptIndexException
*/
public void index() throws CorruptIndexException, LockObtainFailedException, IOException
{

docsPath="F:\\Search engine\\搜索引擎\\lucene-3.1.0-src\\lucene-3.1.0\\contrib\\analyzers\\common\\readm.txt";
indexPath="D:\\mywork\\LuceneTest\\lucenedic";

if(docsPath==null)
{
System.err.println("docsPath为空");
System.exit(1);
}
File docDir = new File(docsPath);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
Directory dir = FSDirectory.open(new File(indexPath));

IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_31, analyzer);
/*IndexWriter indexWriter1 = new IndexWriter(dir,new IndexWriterConfig(Version.LUCENE_31,
new WhitespaceAnalyzer(Version.LUCENE_31)));*/

iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
IndexWriter indexWriter = new IndexWriter(dir,iwc);
Document doc = new Document();

Field pathField = new Field("path",docDir.getPath(),Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS);
pathField.setOmitTermFreqAndPositions(true);
doc.add(pathField);
indexWriter.addDocument(doc);
indexWriter.close();

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值