讲解之前,先来分享一些资料

  首先呢,学习任何一门新的亦或是旧的开源技术,百度其中一二是最简单的办法,先了解其中的大概,思想等等。这里就贡献一个讲解很到位的ppt。已经被我转成了PDF,便于搜藏。

  其次,关于第一次编程初探,建议还是查看官方资料。百度到的资料,目前Lucene已经更新到4.9版本,这个版本需要1.7以上的JDK,所以如果还用1.6甚至是1.5的小盆友,请参考低版本,由于我用的1.6,因此在使用Lucene4.0。

  这是Lucene4.0的官网文档:http://lucene.apache.org/core/4_0_0/core/overview-summary.html

  这里非常佩服Lucene的开元贡献者,可以阅读Lucene in Action,作者最初想要写软件赚钱,最后贡献给了Apache,跑题了。

  最后,提醒学习Lucene的小盆友们,这个开源软件的版本更新不慢,版本之间的编程风格亦是不同,所以如果百度到的帖子,可能这段代码,用了4.0或者3.6就会不好使。

  比如,以前版本的申请IndexWriter时,是这样的:

 IndexWriter indexWriter  =   new IndexWriter(indexDir,luceneAnalyzer, true ); 

  但是4.0,我们需要配置一个conf,把配置内容放到这个对象中:

    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);IndexWriter iwriter = new IndexWriter(directory, config);

  所以,请一定要参考官方文档的编程风格,进行代码的书写

  最后的最后,从官网上面下载下来的文件,已经上传至百度网盘,欢迎下载。

  

  这是其中最常用的五个文件:

  第一个,也是最重要的,Lucene-core-4.0.0.jar,其中包括了常用的文档,索引,搜索,存储等相关核心代码。

  第二个,Lucene-analyzers-common-4.0.0.jar,这里面包含了各种语言的词法分析器,用于对文件内容进行关键字切分,提取。

  第三个,Lucene-highlighter-4.0.0.jar,这个jar包主要用于搜索出的内容高亮显示。

  第四个和第五个,Lucene-queryparser-4.0.0.jar,提供了搜索相关的代码,用于各种搜索,比如模糊搜索,范围搜索,等等。

废话说到这里,下面我们简单的讲解一下什么是全文检索

  比如,我们一个文件夹中,或者一个磁盘中有很多的文件,记事本、world、Excel、pdf,我们想根据其中的关键词搜索包含的文件。例如,我们输入Lucene,所有内容含有Lucene的文件就会被检查出来。这就是所谓的全文检索。

  因此,很容易的我们想到,应该建立一个关键字与文件的相关映射,盗用ppt中的一张图,很明白的解释了这种映射如何实现。

  在Lucene中,就是使用这种“倒排索引”的技术,来实现相关映射。

有了这种映射关系,我们就来看看Lucene的架构设计

  下面是Lucene的资料必出现的一张图,但也是其精髓的概括。

  我们可以看到,Lucene的使用主要体现在两个步骤:

  1 创建索引,通过IndexWriter对不同的文件进行索引的创建,并将其保存在索引相关文件存储的位置中。

  2 通过索引查寻关键字相关文档。

  下面针对官网上面给出的一个例子,进行分析:

 1   Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
 2
 3     // Store the index in memory:
 4     Directory directory = new RAMDirectory();
 5     // To store an index on disk, use this instead:
 6     //Directory directory = FSDirectory.open("/tmp/testindex");
 7     IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
 8     IndexWriter iwriter = new IndexWriter(directory, config);
 9     Document doc = new Document();
10     String text = "This is the text to be indexed.";
11     doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
12     iwriter.addDocument(doc);
13     iwriter.close();
14
15     // Now search the index:
16     DirectoryReader ireader = DirectoryReader.open(directory);
17     IndexSearcher isearcher = new IndexSearcher(ireader);
18     // Parse a simple query that searches for "text":
19     QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer);
20     Query query = parser.parse("text");
21     ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
22     assertEquals(1, hits.length);
23     // Iterate through the results:
24     for (int i = 0; i < hits.length; i++) {
25       Document hitDoc = isearcher.doc(hits[i].doc);
26       assertEquals("This is the text to be indexed.", hitDoc.get("fieldname"));
27     }
28     ireader.close();
29     directory.close();

索引的创建

  首先,我们需要定义一个词法分析器。

  比如一句话,“我爱我们的中国!”,如何对他拆分,扣掉停顿词“的”,提取关键字“我”“我们”“中国”等等。这就要借助的词法分析器Analyzer来实现。这里面使用的是标准的词法分析器,如果专门针对汉语,还可以搭配paoding,进行使用。

1 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);

  参数中的Version.LUCENE_CURRENT,代表使用当前的Lucene版本,本文环境中也可以写成Version.LUCENE_40。

  第二步,确定索引文件存储的位置,Lucene提供给我们两种方式:

  1 本地文件存储

Directory directory = FSDirectory.open("/tmp/testindex");

  2 内存存储

Directory directory = new RAMDirectory();

  可以根据自己的需要进行设定。

  第三步,创建IndexWriter,进行索引文件的写入。

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
IndexWriter iwriter = new IndexWriter(directory, config);

  这里的IndexWriterConfig,据官方文档介绍,是对indexWriter的配置,其中包含了两个参数,第一个是目前的版本,第二个是词法分析器Analyzer。

  第四步,内容提取,进行索引的存储。

Document doc = new Document();
String text = "This is the text to be indexed.";
doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
iwriter.addDocument(doc);
iwriter.close();

  第一行,申请了一个document对象,这个类似于数据库中的表中的一行。

  第二行,是我们即将索引的字符串。

  第三行,把字符串存储起来(因为设置了TextField.TYPE_STORED,如果不想存储,可以使用其他参数,详情参考官方文档),并存储“表明”为"fieldname".

  第四行,把doc对象加入到索引创建中。

  第五行,关闭IndexWriter,提交创建内容。

  这就是索引创建的过程。

关键字查询:

  第一步,打开存储位置

DirectoryReader ireader = DirectoryReader.open(directory);

  第二步,创建搜索器

IndexSearcher isearcher = new IndexSearcher(ireader);

  第三步,类似SQL,进行关键字查询

QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer);
Query query = parser.parse("text");
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
assertEquals(1, hits.length);
for (int i = 0; i < hits.length; i++) {Document hitDoc = isearcher.doc(hits[i].doc);assertEquals("This is the text to be indexed.",hitDoc.get("fieldname"));
}

  这里,我们创建了一个查询器,并设置其词法分析器,以及查询的“表名“为”fieldname“。查询结果会返回一个集合,类似SQL的ResultSet,我们可以提取其中存储的内容。

  关于各种不同的查询方式,可以参考官方手册,或者推荐的PPT

  第四步,关闭查询器等。

ireader.close();
directory.close();

  最后,博猪自己写了个简单的例子,可以对一个文件夹内的内容进行索引的创建,并根据关键字筛选文件,并读取其中的内容

创建索引:

/*** 创建当前文件目录的索引* @param path 当前文件目录* @return 是否成功*/public static boolean createIndex(String path){Date date1 = new Date();List<File> fileList = getFileList(path);for (File file : fileList) {content = "";//获取文件后缀String type = file.getName().substring(file.getName().lastIndexOf(".")+1);if("txt".equalsIgnoreCase(type)){content += txt2String(file);}else if("doc".equalsIgnoreCase(type)){content += doc2String(file);}else if("xls".equalsIgnoreCase(type)){content += xls2String(file);}System.out.println("name :"+file.getName());System.out.println("path :"+file.getPath());
//            System.out.println("content :"+content);
            System.out.println();try{analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);directory = FSDirectory.open(new File(INDEX_DIR));File indexFile = new File(INDEX_DIR);if (!indexFile.exists()) {indexFile.mkdirs();}IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);indexWriter = new IndexWriter(directory, config);Document document = new Document();document.add(new TextField("filename", file.getName(), Store.YES));document.add(new TextField("content", content, Store.YES));document.add(new TextField("path", file.getPath(), Store.YES));indexWriter.addDocument(document);indexWriter.commit();closeWriter();}catch(Exception e){e.printStackTrace();}content = "";}Date date2 = new Date();System.out.println("创建索引-----耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");return true;}

进行查询:

/*** 查找索引,返回符合条件的文件* @param text 查找的字符串* @return 符合条件的文件List*/public static void searchIndex(String text){Date date1 = new Date();try{directory = FSDirectory.open(new File(INDEX_DIR));analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);DirectoryReader ireader = DirectoryReader.open(directory);IndexSearcher isearcher = new IndexSearcher(ireader);QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "content", analyzer);Query query = parser.parse(text);ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;for (int i = 0; i < hits.length; i++) {Document hitDoc = isearcher.doc(hits[i].doc);System.out.println("____________________________");System.out.println(hitDoc.get("filename"));System.out.println(hitDoc.get("content"));System.out.println(hitDoc.get("path"));System.out.println("____________________________");}ireader.close();directory.close();}catch(Exception e){e.printStackTrace();}Date date2 = new Date();System.out.println("查看索引-----耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");}

全部代码:

  1 package test;
  2
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileReader;
  7 import java.util.ArrayList;
  8 import java.util.Date;
  9 import java.util.List;
 10
 11 import jxl.Cell;
 12 import jxl.Sheet;
 13 import jxl.Workbook;
 14
 15 import org.apache.lucene.analysis.Analyzer;
 16 import org.apache.lucene.analysis.standard.StandardAnalyzer;
 17 import org.apache.lucene.document.Document;
 18 import org.apache.lucene.document.LongField;
 19 import org.apache.lucene.document.TextField;
 20 import org.apache.lucene.document.Field.Store;
 21 import org.apache.lucene.index.DirectoryReader;
 22 import org.apache.lucene.index.IndexWriter;
 23 import org.apache.lucene.index.IndexWriterConfig;
 24 import org.apache.lucene.queryparser.classic.QueryParser;
 25 import org.apache.lucene.search.IndexSearcher;
 26 import org.apache.lucene.search.Query;
 27 import org.apache.lucene.search.ScoreDoc;
 28 import org.apache.lucene.store.Directory;
 29 import org.apache.lucene.store.FSDirectory;
 30 import org.apache.lucene.util.Version;
 31 import org.apache.poi.hwpf.HWPFDocument;
 32 import org.apache.poi.hwpf.usermodel.Range;
 33
 34 /**
 35  * @author xinghl
 36  *
 37  */
 38 public class IndexManager{
 39     private static IndexManager indexManager;
 40     private static String content="";
 41
 42     private static String INDEX_DIR = "D:\\luceneIndex";
 43     private static String DATA_DIR = "D:\\luceneData";
 44     private static Analyzer analyzer = null;
 45     private static Directory directory = null;
 46     private static IndexWriter indexWriter = null;
 47
 48     /**
 49      * 创建索引管理器
 50      * @return 返回索引管理器对象
 51      */
 52     public IndexManager getManager(){
 53         if(indexManager == null){
 54             this.indexManager = new IndexManager();
 55         }
 56         return indexManager;
 57     }
 58     /**
 59      * 创建当前文件目录的索引
 60      * @param path 当前文件目录
 61      * @return 是否成功
 62      */
 63     public static boolean createIndex(String path){
 64         Date date1 = new Date();
 65         List<File> fileList = getFileList(path);
 66         for (File file : fileList) {
 67             content = "";
 68             //获取文件后缀
 69             String type = file.getName().substring(file.getName().lastIndexOf(".")+1);
 70             if("txt".equalsIgnoreCase(type)){
 71
 72                 content += txt2String(file);
 73
 74             }else if("doc".equalsIgnoreCase(type)){
 75
 76                 content += doc2String(file);
 77
 78             }else if("xls".equalsIgnoreCase(type)){
 79
 80                 content += xls2String(file);
 81
 82             }
 83
 84             System.out.println("name :"+file.getName());
 85             System.out.println("path :"+file.getPath());
 86 //            System.out.println("content :"+content);
 87             System.out.println();
 88
 89
 90             try{
 91                 analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
 92                 directory = FSDirectory.open(new File(INDEX_DIR));
 93
 94                 File indexFile = new File(INDEX_DIR);
 95                 if (!indexFile.exists()) {
 96                     indexFile.mkdirs();
 97                 }
 98                 IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
 99                 indexWriter = new IndexWriter(directory, config);
100
101                 Document document = new Document();
102                 document.add(new TextField("filename", file.getName(), Store.YES));
103                 document.add(new TextField("content", content, Store.YES));
104                 document.add(new TextField("path", file.getPath(), Store.YES));
105                 indexWriter.addDocument(document);
106                 indexWriter.commit();
107                 closeWriter();
108
109
110             }catch(Exception e){
111                 e.printStackTrace();
112             }
113             content = "";
114         }
115         Date date2 = new Date();
116         System.out.println("创建索引-----耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
117         return true;
118     }
119
120     /**
121      * 读取txt文件的内容
122      * @param file 想要读取的文件对象
123      * @return 返回文件内容
124      */
125     public static String txt2String(File file){
126         String result = "";
127         try{
128             BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
129             String s = null;
130             while((s = br.readLine())!=null){//使用readLine方法,一次读一行
131                 result = result + "\n" +s;
132             }
133             br.close();
134         }catch(Exception e){
135             e.printStackTrace();
136         }
137         return result;
138     }
139
140     /**
141      * 读取doc文件内容
142      * @param file 想要读取的文件对象
143      * @return 返回文件内容
144      */
145     public static String doc2String(File file){
146         String result = "";
147         try{
148             FileInputStream fis = new FileInputStream(file);
149             HWPFDocument doc = new HWPFDocument(fis);
150             Range rang = doc.getRange();
151             result += rang.text();
152             fis.close();
153         }catch(Exception e){
154             e.printStackTrace();
155         }
156         return result;
157     }
158
159     /**
160      * 读取xls文件内容
161      * @param file 想要读取的文件对象
162      * @return 返回文件内容
163      */
164     public static String xls2String(File file){
165         String result = "";
166         try{
167             FileInputStream fis = new FileInputStream(file);
168             StringBuilder sb = new StringBuilder();
169             jxl.Workbook rwb = Workbook.getWorkbook(fis);
170             Sheet[] sheet = rwb.getSheets();
171             for (int i = 0; i < sheet.length; i++) {
172                 Sheet rs = rwb.getSheet(i);
173                 for (int j = 0; j < rs.getRows(); j++) {
174                    Cell[] cells = rs.getRow(j);
175                    for(int k=0;k<cells.length;k++)
176                    sb.append(cells[k].getContents());
177                 }
178             }
179             fis.close();
180             result += sb.toString();
181         }catch(Exception e){
182             e.printStackTrace();
183         }
184         return result;
185     }
186     /**
187      * 查找索引,返回符合条件的文件
188      * @param text 查找的字符串
189      * @return 符合条件的文件List
190      */
191     public static void searchIndex(String text){
192         Date date1 = new Date();
193         try{
194             directory = FSDirectory.open(new File(INDEX_DIR));
195             analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
196             DirectoryReader ireader = DirectoryReader.open(directory);
197             IndexSearcher isearcher = new IndexSearcher(ireader);
198
199             QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "content", analyzer);
200             Query query = parser.parse(text);
201
202             ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
203
204             for (int i = 0; i < hits.length; i++) {
205                 Document hitDoc = isearcher.doc(hits[i].doc);
206                 System.out.println("____________________________");
207                 System.out.println(hitDoc.get("filename"));
208                 System.out.println(hitDoc.get("content"));
209                 System.out.println(hitDoc.get("path"));
210                 System.out.println("____________________________");
211             }
212             ireader.close();
213             directory.close();
214         }catch(Exception e){
215             e.printStackTrace();
216         }
217         Date date2 = new Date();
218         System.out.println("查看索引-----耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
219     }
220     /**
221      * 过滤目录下的文件
222      * @param dirPath 想要获取文件的目录
223      * @return 返回文件list
224      */
225     public static List<File> getFileList(String dirPath) {
226         File[] files = new File(dirPath).listFiles();
227         List<File> fileList = new ArrayList<File>();
228         for (File file : files) {
229             if (isTxtFile(file.getName())) {
230                 fileList.add(file);
231             }
232         }
233         return fileList;
234     }
235     /**
236      * 判断是否为目标文件,目前支持txt xls doc格式
237      * @param fileName 文件名称
238      * @return 如果是文件类型满足过滤条件,返回true;否则返回false
239      */
240     public static boolean isTxtFile(String fileName) {
241         if (fileName.lastIndexOf(".txt") > 0) {
242             return true;
243         }else if (fileName.lastIndexOf(".xls") > 0) {
244             return true;
245         }else if (fileName.lastIndexOf(".doc") > 0) {
246             return true;
247         }
248         return false;
249     }
250
251     public static void closeWriter() throws Exception {
252         if (indexWriter != null) {
253             indexWriter.close();
254         }
255     }
256     /**
257      * 删除文件目录下的所有文件
258      * @param file 要删除的文件目录
259      * @return 如果成功,返回true.
260      */
261     public static boolean deleteDir(File file){
262         if(file.isDirectory()){
263             File[] files = file.listFiles();
264             for(int i=0; i<files.length; i++){
265                 deleteDir(files[i]);
266             }
267         }
268         file.delete();
269         return true;
270     }
271     public static void main(String[] args){
272         File fileIndex = new File(INDEX_DIR);
273         if(deleteDir(fileIndex)){
274             fileIndex.mkdir();
275         }else{
276             fileIndex.mkdir();
277         }
278
279         createIndex(DATA_DIR);
280         searchIndex("man");
281     }
282 }

运行结果:

  所有包含man关键字的文件,都被筛选出来了。

  

本文转自博客园xingoo的博客,原文链接:【手把手教你全文检索】Apache Lucene初探,如需转载请自行联系原博主。

【手把手教你全文检索】Apache Lucene初探相关推荐

  1. 【手把手教你全文检索】Lucene索引的【增、删、改、查】

    2019独角兽企业重金招聘Python工程师标准>>> 前言 搞检索的,应该多少都会了解Lucene一些,它开源而且简单上手,官方API足够编写些小DEMO.并且根据倒排索引,实现快 ...

  2. 手把手教你实战apache调优之apache模式介绍

    apache运行模式-prefork-worker运行模式介绍 1. apache不同运行模式调优 Web服务器Apache目前一共有三种稳定的MPM(Multi-Processing Module, ...

  3. Apache Lucene与Lucene.Net——全文检索服务器

    lucene学习教程 1.1 什么是lucene Lucene是一个全文搜索框架,而不是应用产品.因此它并不像www.baidu.com 或者google Desktop那么拿来就能用,它只是提供了一 ...

  4. 服务器系统2022安装wsl2,手把手教你踩坑:老白的Docker for Windows安装初探WSL 2 backend...

    手把手教你踩坑:老白的Docker for Windows安装初探WSL 2 backend 2020-06-16 13:29:47 15点赞 63收藏 4评论 创作立场声明:老白的踩坑记录 嗨,大家 ...

  5. Apache Lucene Java 全文检索引擎架构

    Apache Lucene Java 全文检索引擎架构 Apache Lucene 8.9.0 已发布,Lucene 是完全用 Java 编写的高性能.功能齐全的全文检索引擎架构,提供了完整的查询引擎 ...

  6. 【Lucene】Apache Lucene全文检索引擎架构之中文分词和高亮显示4

    前面总结的都是使用Lucene的标准分词器,这是针对英文的,但是中文的话就不顶用了,因为中文的语汇与英文是不同的,所以一般我们开发的时候,有中文的话肯定要使用中文分词了,这一篇博文主要介绍一下如何使用 ...

  7. 【Lucene】Apache Lucene全文检索引擎架构之中文分词和高亮显示

    欢迎关注我新搭建的博客:http://www.itcodai.com/ 前面总结的都是使用Lucene的标准分词器,这是针对英文的,但是中文的话就不顶用了,因为中文的语汇与英文是不同的,所以一般我们开 ...

  8. skywalking原理_Skywalking系列博客6手把手教你编写 Skywalking 插件

    点击上方 IT牧场 ,选择 置顶或者星标技术干货每日送达! 前置知识 在正式进入编写环节之前,建议先花一点时间了解下javaagent(这是JDK 5引入的一个玩意儿,最好了解下其工作原理):另外,S ...

  9. centos7 nginx安装_手把手教你PHP(一) Centos7上的LEMP配置

    相信有些刚刚接触web开发的小伙伴对于服务器上搭建web环境还不太了解,今天手把手教大家搭建lemp的线上环境,您需要做如下一些准备: 阿里云或者其他服务商的云主机一台 云主机已安装Centos 7 ...

最新文章

  1. 小白学数据分析-----Excel制作INFOGRAPHIC
  2. 【每周CV论文】初学深度学习图像风格化要读的文章
  3. mysql 视图 字符集_MySQL创建子视图并查看的时候,字符集报错问题
  4. linux下find命令之-exec ll -sh {} \;
  5. 你不知道的JavaScript(二)
  6. Python reduce / map / filter 函数区别 - Python零基础入门教程
  7. python公众号文章爬虫_微信公众号文章爬虫
  8. 如何写一篇文献计量分析论文---citespace+vosviewer+文献计量在线分析平台
  9. usb抓包工具 安卓_USB抓包工具(Bus Hound)下载 v6.0.1 官方版
  10. 媒体实测英特尔® 傲腾™ 持久内存数据曝光,DRAM 和 SSD 都沉默了
  11. 关于数组中的大括号{}和数组的遍历
  12. Fail: Failover,Failfast,Failback,Failsafe
  13. 高三数学微课堂【教学视频】
  14. Word打印目录或另存为PDF时出现“错误!未定义书签!”的解决办法
  15. canvas画出闪瞎眼的简单图形
  16. linux屏幕触碰事件,触摸屏中鼠标事件的捕获和传递及触摸屏的移植
  17. windows7系统损坏修复_为什么有的win7开机没有修复计算机的选项?分享解决方法!...
  18. 30分钟java桌球小游戏_30分钟完成桌球小游戏项目
  19. ChatGPT有效提问技巧
  20. 扒开ARM中断控制器的底裤来看看!

热门文章

  1. 低代码缺少的五大组件
  2. ​Google 鼓励的 13 条代码审查标准,建议收藏!
  3. 如何避免操作系统中多线程资源竞争的互斥与同步?
  4. oracle删除临时表空间一直处于等待状态
  5. 随笔 | 抢红包不是一件小事
  6. [UWP]在应用开发中安全使用文件资源
  7. vim编辑器操作命令大全-绝对全
  8. 学习决心书-linux oldboy
  9. [LeetCode]: 242: Valid Anagram
  10. 【ML】【GM】【转】图模型(graphical model, GM)的表示