一.lucene的组成部分【主要的三部分】
1. 索引部分
2. 分词部分
3. 搜索部分
1. 索引部分
1.1 准备相应的 jar 包
这里我采用的是springboot 整合Lucene,在 pom.xml文件中添加相应的依赖
<!--lucene-core --> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-core</artifactId> <version>3.5.0</version> </dependency> <!--commons-io依赖: 方便我们直接解析文件--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
1.2 开始编写代码【创建索引】
public class LuceneIndex
/** * 创建索引 */ public void index() {
IndexWriter indexWriter =null; try { //1. 创建 Directory 【内存】 // Directory directory = new RAMDirectory(); // 创建在内存 Directory directory = FSDirectory.open(new File("E:/lucene/index01")); // 创建在硬盘中 // 2. 创建 IndexWriter Analyzer analyzer =new StandardAnalyzer(Version.LUCENE_35); // 分词器 IndexWriterConfig indexWriterConfig =new IndexWriterConfig(Version.LUCENE_35,analyzer); indexWriter=new IndexWriter(directory,indexWriterConfig); // 3. 创建 document Document document =null; // 4. 为 document 添加 Filed File files =new File("E:/lucene/lucene"); // 获取要索引的文件 //遍历文件 for (File file: files.listFiles()){ document=new Document(); // 此处是将文件装换成字符串 【】
String content= FileUtils.readFileToString(file,"utf-8"); log.info("--------文件的内容--------------->"); log.info(content); log.info("<-------文件的内容----------------");
// 将文档也存储起来 【一般情况下 不建议------》消耗内存】 // document.add(new Field("content",content,Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));document.add( new Field( "content" , new FileReader(file))); // 添加内容 /** * Field.Store.YES 是否将文件存储 YES: * Field.Index.NOT_ANALYZED 是否要进行分词 NOT_ANALYZED :不需要 */ document.add( new Field( "filename" ,file.getName(),Field.Store. YES ,Field.Index. NOT_ANALYZED )); // 文件名 document.add( new Field( "path" ,file.getAbsolutePath(), Field.Store. YES ,Field.Index. NOT_ANALYZED )); // 文件地址 //5. 通过 indexWriter添加文档到索引 indexWriter.addDocument(document); log .info( "--------- 创建索引完毕 ---------->" ); } } catch (Exception e){ e.printStackTrace(); } finally { try { // 关闭流 【记得一定要关闭流】 if (indexWriter!= null ){ indexWriter.close(); } } catch (Exception e){ e.printStackTrace(); } } }}
1.3 创建测试类
@RunWith(SpringRunner.class) @SpringBootTest public class IndexUtilTests { /** * 测试索引 * @throws Exception */ @Test public void TestIndexUtil() throws Exception{ IndexUtil indexUtil =new IndexUtil(); indexUtil.index(); }}运行 TestIndexUtil() 方法后可以看到 在我的 E盘中生成了如下的目录【此时我们的索引就创建完成了】
