搜索引擎学习(二)Lucene创建索引

时间:2023-03-10 01:36:55
搜索引擎学习(二)Lucene创建索引

PS:需要用到的jar包:

搜索引擎学习(二)Lucene创建索引

代码实现

1、工程结构

搜索引擎学习(二)Lucene创建索引

2、设置工程依赖的jar包

搜索引擎学习(二)Lucene创建索引

3、代码实现

/**
* Lucene入门
* 创建索引
*/
public class CreateIndex { /**
* 创建索引
* 第一步:创建java工程,导入相关的jar包
* 第二步:创建一个indexWriter(索引写入)对象
* (1)指定索引库的存放位置Directory
* (2)指定一个分析器,对文档内容进行分析
* 第三步:创建document(文档)对象
* 第四步:创建field(域)对象,将field添加到document对象中
* 第五步:使用indexWriter对象将document对象写入索引库,此过程进行索引创建,并将索引和document对象写入索引库
* 第六步:关闭indexWriter对象(关流)
*/
@Test
public void createIndex() throws Exception { /*第二步:创建一个indexWriter(索引写入)对象*/
//设置索引库的位置(PS:若使用RAMDiretory则是使用内存当做索引库,但是一关机就凉凉...)
Directory directory = FSDirectory.open(new File("E:\\zhanghaoBF\\luceneSolr\\indexLibrary").toPath());
//创建分词器对象(官方推荐标准分词器)
Analyzer analyzer = new StandardAnalyzer();
//设置使用的分词器
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
//创建索引对象
IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig); File f = new File("E:\\zhanghaoBF\\luceneSolr\\indexField");
File[] listFiles = f.listFiles();
for (File file : listFiles) {
/*第三步:创建document(文档)对象*/
Document document = new Document(); /*第四步:创建field(域)对象,将field添加到document对象中*/
//文件名称
String file_name = file.getName();
Field fileNameField = new TextField("fileName", file_name, Field.Store.YES);
//文件大小
long file_size = FileUtils.sizeOf(file);
Field fileSizeField = new StoredField("fileSize", file_size + "");
//文件路径
String file_path = file.getPath();
Field filePathField = new StoredField("filePath", file_path + "");
//文件内容
String file_content = FileUtils.readFileToString(file);
Field fileContentField = new TextField("fileContent", file_content, Field.Store.NO);//第三个参数是设置存不存在索引库里 document.add(fileNameField);//文件名称
document.add(fileSizeField);//文件大小
document.add(filePathField);//文件路径
document.add(fileContentField);//文件内容 /*第五步:使用indexWriter对象将document对象写入索引库,此过程进行索引创建,并将索引和document对象写入索引库*/
indexWriter.addDocument(document);
} /*第六步:关闭indexWriter对象(关流)*/
indexWriter.close();
}
}

4、右键运行后,查看生成的索引文件

搜索引擎学习(二)Lucene创建索引

5、使用luke查看索引

搜索引擎学习(二)Lucene创建索引

搜索引擎学习(二)Lucene创建索引

搜索引擎学习(二)Lucene创建索引

完事  lucene代码创建索引就算成功了~