Lucene6.0学习笔记——建立索引

本文介绍使用Lucene创建中文文档索引的过程。包括定义关键变量、建立索引及将文件转换为Document对象的方法。涉及路径配置、索引管理及中文分词。

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

1.定义相关变量

private final static String filePath="E:\\workspace\\luceneDemo\\files";
private final static Path indexPath=Paths.get("E:\\workspace\\luceneDemo\\indexStore");
public static Analyzer analyzer = new SmartChineseAnalyzer();

filePath:需要创建索引的源文件地址

indexPath:索引保存地址

analyzer:定义分词器,这里采用lucene自带的中文分词器

2.建立索引

public static void createIndex(){
	List<Document> doc = File2DocumentUtil.files2Document(filePath);
	try {
		/*索引文件采用物理存储*/
		FSDirectory directory = FSDirectory.open(indexPath);
		/*索引文件内存存储*/
		//RAMDirectory directory1 = new RAMDirectory();
		//配置indexWriter,写入索引
		IndexWriterConfig config = new IndexWriterConfig(analyzer);
		IndexWriter indexWriter=new IndexWriter(directory, config);
		//创建之前删除所有索引
		indexWriter.deleteAll();
		//添加需要建立索引的Document
		indexWriter.addDocuments(doc);
		//提交写入
		indexWriter.commit();
		//关闭indexWriter
		indexWriter.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

3.文件转Document方法

public static List<Document> files2Document(String filePath) {
	File dir=new File(filePath);
	List<Document> list=new ArrayList<>();
	for(File file:dir.listFiles()){
		Document doc=new Document();
		doc.add(new TextField("name", file.getName(), Store.YES));
		doc.add(new StringField("path", file.getPath(), Store.YES));
		/*设置排序字段*/
		doc.add(new NumericDocValuesField("size",file.length()));  
		doc.add(new StringField("size", String.valueOf(file.length()), Store.YES));
		doc.add(new TextField("content", getFileContent(file), Store.YES));
		list.add(doc);
	}
	return list;
}

StringField:不会进行分词操作;

TextField:会进行分词操作。

转载于:https://my.oschina.net/visionit/blog/712647

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值