Lucene5学习之创建索引入门示例

简介:

    Lucene更新实在太快了,只好紧跟脚步开始学习Lucene5,花了点时间写了一个demo,就是程序根据用户提供的一个文件夹,读取该文件夹下的所有文件,然后读取文件里的内容写入索引。读取文件部分采用的是最新的NIO2.0API,因此,JDK必须使用1.7及以上版本。Lucene5开发压缩包请在Lucene官网下载。不多说了,对于码农来说,最直接的就是上代码。

Java代码   收藏代码
  1. package com.yida.framework.lucene5.core;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.nio.charset.StandardCharsets;  
  8. import java.nio.file.FileVisitResult;  
  9. import java.nio.file.Files;  
  10. import java.nio.file.LinkOption;  
  11. import java.nio.file.OpenOption;  
  12. import java.nio.file.Path;  
  13. import java.nio.file.Paths;  
  14. import java.nio.file.SimpleFileVisitor;  
  15. import java.nio.file.attribute.BasicFileAttributes;  
  16.   
  17. import org.apache.lucene.analysis.Analyzer;  
  18. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  19. import org.apache.lucene.document.Document;  
  20. import org.apache.lucene.document.Field;  
  21. import org.apache.lucene.document.LongField;  
  22. import org.apache.lucene.document.StringField;  
  23. import org.apache.lucene.document.TextField;  
  24. import org.apache.lucene.index.IndexWriter;  
  25. import org.apache.lucene.index.IndexWriterConfig;  
  26. import org.apache.lucene.index.Term;  
  27. import org.apache.lucene.store.Directory;  
  28. import org.apache.lucene.store.FSDirectory;  
  29.   
  30. /** 
  31.  * 读取硬盘文件,创建索引 
  32.  *  
  33.  * @author Lanxiaowei 
  34.  *  
  35.  */  
  36. @SuppressWarnings({ "unchecked""unused""rawtypes" })  
  37. public class IndexFile {  
  38.     public static void main(String[] args) throws IOException {  
  39.         String dirPath = "D:/docPath";  
  40.         String indexPath = "D:/lucenedir";  
  41.         createIndex(dirPath, indexPath);  
  42.     }  
  43.       
  44.     /** 
  45.      * 创建索引 
  46.      * @param dirPath       需要读取的文件所在文件目录 
  47.      * @param indexPath     索引存放目录 
  48.      * @throws IOException 
  49.      */  
  50.     public static void createIndex(String dirPath, String indexPath) throws IOException {  
  51.         createIndex(dirPath, indexPath, false);  
  52.     }  
  53.       
  54.     /** 
  55.      * 创建索引 
  56.      * @param dirPath         需要读取的文件所在文件目录 
  57.      * @param indexPath       索引存放目录 
  58.      * @param createOrAppend  始终重建索引/不存在则追加索引 
  59.      * @throws IOException 
  60.      */  
  61.     public static void createIndex(String dirPath, String indexPath,  
  62.             boolean createOrAppend) throws IOException {  
  63.         long start = System.currentTimeMillis();  
  64.         Directory dir = FSDirectory.open(Paths.get(indexPath, new String[0]));  
  65.         Path docDirPath = Paths.get(dirPath, new String[0]);  
  66.         Analyzer analyzer = new StandardAnalyzer();  
  67.         IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);  
  68.   
  69.         if (createOrAppend) {  
  70.             indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);  
  71.         } else {  
  72.             indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);  
  73.         }  
  74.         IndexWriter writer = new IndexWriter(dir, indexWriterConfig);  
  75.         indexDocs(writer, docDirPath);  
  76.         writer.close();  
  77.         long end = System.currentTimeMillis();  
  78.         System.out.println("Time consumed:" + (end - start) + " ms");  
  79.     }  
  80.   
  81.     /** 
  82.      *  
  83.      * @param writer 
  84.      *            索引写入器 
  85.      * @param path 
  86.      *            文件路径 
  87.      * @throws IOException 
  88.      */  
  89.     public static void indexDocs(final IndexWriter writer, Path path)  
  90.             throws IOException {  
  91.         // 如果是目录,查找目录下的文件  
  92.         if (Files.isDirectory(path, new LinkOption[0])) {  
  93.             System.out.println("directory");  
  94.             Files.walkFileTree(path, new SimpleFileVisitor() {  
  95.                 @Override  
  96.                 public FileVisitResult visitFile(Object file,  
  97.                         BasicFileAttributes attrs) throws IOException {  
  98.                     Path path = (Path)file;  
  99.                     System.out.println(path.getFileName());  
  100.                     indexDoc(writer, path, attrs.lastModifiedTime().toMillis());  
  101.                     return FileVisitResult.CONTINUE;  
  102.                 }  
  103.             });  
  104.         } else {  
  105.             indexDoc(writer, path,  
  106.                     Files.getLastModifiedTime(path, new LinkOption[0])  
  107.                             .toMillis());  
  108.         }  
  109.     }  
  110.   
  111.     /** 
  112.      * 读取文件创建索引 
  113.      *  
  114.      * @param writer 
  115.      *            索引写入器 
  116.      * @param file 
  117.      *            文件路径 
  118.      * @param lastModified 
  119.      *            文件最后一次修改时间 
  120.      * @throws IOException 
  121.      */  
  122.     public static void indexDoc(IndexWriter writer, Path file, long lastModified)  
  123.             throws IOException {  
  124.         InputStream stream = Files.newInputStream(file, new OpenOption[0]);  
  125.         Document doc = new Document();  
  126.   
  127.         Field pathField = new StringField("path", file.toString(),  
  128.                 Field.Store.YES);  
  129.         doc.add(pathField);  
  130.   
  131.         doc.add(new LongField("modified", lastModified, Field.Store.NO));  
  132.         doc.add(new TextField("contents"new BufferedReader(  
  133.                 new InputStreamReader(stream, StandardCharsets.UTF_8))));  
  134.   
  135.         if (writer.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE) {  
  136.             System.out.println("adding " + file);  
  137.             writer.addDocument(doc);  
  138.         } else {  
  139.             System.out.println("updating " + file);  
  140.             writer.updateDocument(new Term("path", file.toString()), doc);  
  141.         }  
  142.         writer.commit();  
  143.     }  
  144. }  

 项目采用的是Maven构建,怎么创建Maven Project就不用介绍了吧,我就贴下pom配置吧。

Xml代码   收藏代码
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>com.yida.framework</groupId>  
  5.     <artifactId>lucene5</artifactId>  
  6.     <packaging>war</packaging>  
  7.     <version>1.0</version>  
  8.     <name>lucene5 Maven Webapp</name>  
  9.     <url>http://maven.apache.org</url>  
  10.       
  11.     <properties>  
  12.         <lucene.version>5.0.0</lucene.version>  
  13.     </properties>  
  14.       
  15.     <dependencies>  
  16.         <dependency>  
  17.             <groupId>junit</groupId>  
  18.             <artifactId>junit</artifactId>  
  19.             <version>3.8.1</version>  
  20.             <scope>test</scope>  
  21.         </dependency>  
  22.         <dependency>  
  23.             <groupId>org.apache.lucene</groupId>  
  24.             <artifactId>lucene-core</artifactId>  
  25.             <version>${lucene.version}</version>  
  26.         </dependency>  
  27.         <dependency>  
  28.             <groupId>org.apache.lucene</groupId>  
  29.             <artifactId>lucene-analyzers-common</artifactId>  
  30.             <version>${lucene.version}</version>  
  31.         </dependency>  
  32.         <dependency>  
  33.             <groupId>org.apache.lucene</groupId>  
  34.             <artifactId>lucene-queryparser</artifactId>  
  35.             <version>${lucene.version}</version>  
  36.         </dependency>  
  37.         <dependency>  
  38.             <groupId>org.apache.lucene</groupId>  
  39.             <artifactId>lucene-highlighter</artifactId>  
  40.             <version>${lucene.version}</version>  
  41.         </dependency>  
  42.     </dependencies>  
  43.     <build>  
  44.         <finalName>lucene5</finalName>  
  45.     </build>  
  46. </project>  

 项目结构图如图:



 运行之前,先在D盘新建两个文件夹,如图:



 然后在docPath文件夹里随便放几个文本文件,如图:



 然后运行测试类,就会在lucenedir文件夹下创建索引。

代码很简单,没什么需要过多解释的,demo源码请在附件里下载。

希望能对大家学习Lucene有所帮助,其次也算是对自己学习轨迹的一个记录,写博客这个习惯

我会努力保持下去。

若你还有什么疑问,请加我Q-Q:7-3-6-0-3-1-3-0-5,或者加裙:


,欢迎你加入一起交流学习。

转载:http://iamyida.iteye.com/blog/2192938

目录
相关文章
|
6月前
|
索引
07Lucene索引库的修改
07Lucene索引库的修改
15 0
|
8月前
|
存储 JSON 自然语言处理
|
9月前
|
存储 JSON 自然语言处理
三.全文检索ElasticSearch经典入门-索引CRUD&分词器&文档映射&文档CRUD
三.全文检索ElasticSearch经典入门-索引CRUD&分词器&文档映射&文档CRUD
|
10月前
|
存储 前端开发 Java
ElasticSearch快速入门之创建索引库、创建映射、创建文档、搜索文档
ElasticSearch快速入门之创建索引库、创建映射、创建文档、搜索文档
306 0
|
索引
ElasticSearch学习(二)——索引、文档简单操作 下
ElasticSearch学习(二)——索引、文档简单操作 下
87 0
ElasticSearch学习(二)——索引、文档简单操作 下
|
JSON 自然语言处理 关系型数据库
ElasticSearch学习(二)——索引、文档简单操作 上
ElasticSearch学习(二)——索引、文档简单操作 上
119 0
ElasticSearch学习(二)——索引、文档简单操作    上
|
存储 自然语言处理 算法
【MySQL从入门到精通】【高级篇】(十九)索引的分类&创建索引的三种方式&删除索引的两种方式
MySQL中的索引包括普通索引、全文索引、单列索引、多列索引和空间索引等。
200 0
【MySQL从入门到精通】【高级篇】(十九)索引的分类&创建索引的三种方式&删除索引的两种方式
|
存储 自然语言处理 搜索推荐
Elasticsearch 学习笔记(一)-----Lucene的简介以及索引原理
今天,正式开始学习Elasticsearch,因为Elasticsearch是用Lucene来实现索引的查询功能的,所以,理解Lucene的原理显的尤为重要。
346 0
Elasticsearch 学习笔记(一)-----Lucene的简介以及索引原理
|
JSON 分布式计算 Hadoop
创建索引库和索引_演示|学习笔记
快速学习创建索引库和索引_演示。
61 0
|
JSON 分布式计算 Hadoop
创建索引库和索引演示 | 学习笔记
快速学习创建索引库和索引演示
77 0
创建索引库和索引演示 | 学习笔记