Lucene详解

一.lucene原理

    Lucene 是apache软件基金会一个开放源代码的全文检索引擎工具包,是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎。它不是一个完整的搜索应用程序,而是为你的应用程序提供索引和搜索功能。lucene 能够为文本类型的数据建立索引,所以你只要能把你要索引的数据格式转化的文本的,Lucene 就能对你的文档进行索引和搜索。比如你要对一些 HTML 文档,PDF 文档进行索引的话你就首先需要把 HTML 文档和 PDF 文档转化成文本格式的,然后将转化后的内容交给 Lucene 进行索引,然后把创建好的索引文件保存到磁盘或者内存中,最后根据用户输入的查询条件在索引文件上进行查询。

搜索应用程序和 Lucene 之间的关系,也反映了利用 Lucene 构建搜索应用程序的流程:


二. 索引和搜索

   索引是现代搜索引擎的核心,建立索引的过程就是把源数据处理成非常方便查询的索引文件的过程。为什么索引这么重要呢,试想你现在要在大量的文档中搜索含有某个关键词的文档,那么如果不建立索引的话你就需要把这些文档顺序的读入内存,然后检查这个文章中是不是含有要查找的关键词,这样的话就会耗费非常多的时间,想想搜索引擎可是在毫秒级的时间内查找出要搜索的结果的。这就是由于建立了索引的原因,你可以把索引想象成这样一种数据结构,他能够使你快速的随机访问存储在索引中的关键词,进而找到该关键词所关联的文档。Lucene 采用的是一种称为反向索引(inverted index)的机制。反向索引就是说我们维护了一个词 / 短语表,对于这个表中的每个词 / 短语,都有一个链表描述了有哪些文档包含了这个词 / 短语。这样在用户输入查询条件的时候,就能非常快的得到搜索结果。搜索引擎首先会对搜索的关键词进行解析,然后再在建立好的索引上面进行查找,最终返回和用户输入的关键词相关联的文档。对于中文用户来说,最关心的问题是其是否支持中文的全文检索。由于Lucene良好架构设计,对中文的支持只需对其语言词法分析接口进行扩展就能实现对中文检索的支持。

三. 索引步骤

  1. 获取内容: Lucene本身没有提供获取内容的工具或者组件,内容是要开发者自己提供相应的程序。这一步包括使用网络爬虫或蜘蛛程序来搜索和界定需要索引的内容。当然,数据来源可能包括数据库、分布式文件系统、本地xml等等。lucene作为一款核心搜索库,不提供任何功能来实现内容获取。目前有大量的开源爬虫软件可以实现这个功能,例如:Solr,lucene的子项;Nutch,apache项目,包含大规模的爬虫工具,抓取和分辨web站点数据;Grub,比较流行的开源web爬虫工具;Heritrix,一款开源的Internet文档搜索程序;Aperture,支持从web站点、文件系统和邮箱中抓取,并解析和索引其中的文本数据。
  2. 建立文档:获取原始内容后,需要对这些内容进行索引,必须将这些内容转换成部件(文档)。文档主要包括几个带值的域,比如标题,正文,摘要,作者和链接。如果文档和域比较重要的话,还可以添加权值。设计完方案后,需要将原始内容中的文本提取出来写入各个文档,这一步可以使用文档过滤器,开源项目如Tika,实现很好的文档过滤。如果要获取的原始内容存储于数据库中,有一些项目通过无缝链接内容获取步骤和文档建立步骤就能轻易地对数据库表进行航所以操作和搜索操作,例如DBSight,Hibernate Search,LuSQL,Compass和Oracle/Lucene集成项目。
  3. 文档分析: 搜索引擎不能直接对文本进行索引:必须将文本分割成一系列被称为语汇单元的独立的原子元素。每一个语汇单元能大致与语言中的“单词”对应起来,这个步骤决定文档中的文本域如何分割成语汇单元系列。lucene提供了大量内嵌的分析器可以轻松控制这步操作。
  4. 文档索引: 将文档加入到索引列表中。Lucene在这一步骤中提供了强档的API,只需简单调用提供的几个方法就可以实现出文档索引的建立。为了提供好的用户体验,索引是必须要处理好的一环:在设计和定制索引程序时必须围绕如何提高用户的搜索体验来进行。

四. 搜索组件

  搜索组件即为输入搜索短语,然后进行分词,然从索引中查找单词,从而找到包含该单词的文档。搜索质量由查准率和查全率来衡量。搜索组件主要包括以下内容:

  1. 用户搜索界面:主要是和用户进行交互的页面,也就是呈现在浏览器中能看到的东西,这里主要考虑的就是页面UI设计了。一个良好的UI设计是吸引用户的重要组成部分。
  2. 建立查询:建立查询主要是指用户输入所要查询的短语,以普通HTML表单或者ajax的方式提交到后台服务器端。然后把词语传递给后台搜索引擎。这就是一个简单建立查询的过程。
  3. 搜索查询:即为查询检索索引然后返回与查询词语匹配的文档。然后把返回来的结构按照查询请求来排序。搜索查询组件覆盖了搜索引擎中大部分的复杂内容。
  4. 展现结果:所谓展现结果,和第一个搜索界面类似。都是一个与用户交互的前端展示页面,作为一个搜索引擎,用户体验永远是第一位。其中前端展示在用户体现上占据了重要地位。

五. 官网实例解析

Lucene的使用主要体现在两个步骤:

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

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


 
 
  1. Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
  2. // Store the index in memory:
  3. Directory directory = new RAMDirectory();
  4. // To store an index on disk, use this instead:
  5. //Directory directory = FSDirectory.open("/tmp/testindex");
  6. IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
  7. IndexWriter iwriter = new IndexWriter(directory, config);
  8. Document doc = new Document();
  9. String text = "This is the text to be indexed.";
  10. doc.add( new Field( "fieldname", text, TextField.TYPE_STORED));
  11. iwriter.addDocument(doc);
  12. iwriter.close();
  13. // Now search the index:
  14. DirectoryReader ireader = DirectoryReader.open(directory);
  15. IndexSearcher isearcher = new IndexSearcher(ireader);
  16. // Parse a simple query that searches for "text":
  17. QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer);
  18. Query query = parser.parse( "text");
  19. ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
  20. assertEquals( 1, hits.length);
  21. // Iterate through the results:
  22. for ( int i = 0; i < hits.length; i++) {
  23. Document hitDoc = isearcher.doc(hits[i].doc);
  24. assertEquals( "This is the text to be indexed.", hitDoc.get( "fieldname"));
  25. }
  26. ireader.close();
  27. 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();
自己实现的一个小实例:对一个文件夹内的内容进行索引的创建,并根据关键字筛选文件,并读取其中的内容

 
 
  1. package cn.lnu.edu.yxk;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.IOException;
  8. import java.util.ArrayList;
  9. import java.util.Date;
  10. import java.util.List;
  11. import jxl.Cell;
  12. import jxl.Sheet;
  13. import jxl.Workbook;
  14. import jxl.read.biff.BiffException;
  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.Field;
  19. import org.apache.lucene.index.DirectoryReader;
  20. import org.apache.lucene.index.IndexWriter;
  21. import org.apache.lucene.index.IndexWriterConfig;
  22. import org.apache.lucene.queryparser.classic.ParseException;
  23. import org.apache.lucene.queryparser.classic.QueryParser;
  24. import org.apache.lucene.search.IndexSearcher;
  25. import org.apache.lucene.search.Query;
  26. import org.apache.lucene.search.ScoreDoc;
  27. import org.apache.lucene.store.Directory;
  28. import org.apache.lucene.store.FSDirectory;
  29. import org.apache.poi.hwpf.HWPFDocument;
  30. import org.apache.poi.hwpf.usermodel.Range;
  31. /**
  32. * 对一个文件夹内的内容进行索引的创建,并根据关键字筛选文件,读取其中的内容。
  33. * @author yxk
  34. *
  35. */
  36. public class IndexManager {
  37. private static String content = ""; //文件里面的内容
  38. private static String INDEX_DIR = "D:\\test\\luceneIndex"; //索引创建的存储目录
  39. private static String DATA_DIR = "D:\\test\\luceneData"; //文件夹的目录
  40. private static Analyzer analyzer = null; //词法分析器
  41. private static Directory directory = null; //索引文件存储的位置
  42. private static IndexWriter indexWriter = null; //创建索引器,索引文件的写入
  43. /**
  44. * 创建当前文件目录的索引
  45. * @param path当前目录的文件
  46. * @return 返回是否创建成功
  47. */
  48. public static Boolean createIndex(String path) {
  49. Date date1 = new Date(); //创建需要的时间
  50. List<File> files = listFile(path); // 获取指定目录下得所有符合条件的文件
  51. // 获取文件的内容
  52. for (File file : files) {
  53. content = "";
  54. //通过文件类型获取文件的内容
  55. String type = file.getName().substring(
  56. file.getName().lastIndexOf( ".") + 1);
  57. if ( "txt".equalsIgnoreCase(type)) {
  58. content += txt2String(file);
  59. } else if ( "doc".equalsIgnoreCase(type)) {
  60. content += doc2String(file);
  61. } else if ( "xls".equalsIgnoreCase(type)) {
  62. content += xls2String(file);
  63. }
  64. System.out.println( "name"+file.getName());
  65. System.out.println( "path"+file.getPath());
  66. //System.out.println(file.getName().getBytes().toString());
  67. System.out.println();
  68. try {
  69. analyzer = new StandardAnalyzer(); //词法分析器
  70. directory = FSDirectory.open( new File(INDEX_DIR).toPath()); //索引创建存储的位置
  71. // System.out.println("ssss"
  72. // + new File(INDEX_DIR).toPath().toString());
  73. //自动创建索引目录
  74. File indexFile = new File(INDEX_DIR);
  75. if (!indexFile.exists()) {
  76. indexFile.mkdirs();
  77. }
  78. //索引文件的写入
  79. IndexWriterConfig config = new IndexWriterConfig(analyzer);
  80. indexWriter = new IndexWriter(directory, config);
  81. /*
  82. * 内容提取,进行索引的存储
  83. */
  84. //申请了一个document对象,这个类似于数据库中的表中的一行。
  85. Document document = new Document();
  86. //把字符串存储起来(因为设置了TextField.TYPE_STORED,如果不想存储,可以使用其他参数,详情参考官方文档),并存储“表明”为"fieldname".
  87. document.add( new org.apache.lucene.document.TextField(
  88. "filename", file.getName(), Field.Store.YES)); //文件名索引创建
  89. document.add( new org.apache.lucene.document.TextField(
  90. "content", content, Field.Store.YES)); //文件内容索引创建
  91. document.add( new org.apache.lucene.document.TextField( "path",
  92. file.getPath(), Field.Store.YES)); //文件路径索引的创建
  93. //把document对象加入到索引创建中
  94. indexWriter.addDocument(document);
  95. //关闭IndexWriter,提交创建内容。
  96. indexWriter.commit();
  97. closeWriter();
  98. } catch (IOException e) {
  99. e.printStackTrace();
  100. }
  101. content = "";
  102. }
  103. Date date2 = new Date();
  104. System.out.println( "创建索引-----耗时:" + (date2.getTime() - date1.getTime())
  105. + "ms\n");
  106. return true;
  107. }
  108. /**
  109. * 查询索引,返回符合条件的文件
  110. *
  111. * @param 查询的字符串
  112. * @return 符合条件的结果
  113. * @throws IOException
  114. */
  115. public static void serarchIndex(String text) {
  116. Date date1 = new Date();
  117. try {
  118. //打开存储位置
  119. directory = FSDirectory.open( new File(INDEX_DIR).toPath());
  120. analyzer = new StandardAnalyzer();
  121. DirectoryReader ireader = DirectoryReader.open(directory);
  122. //创建搜索器
  123. IndexSearcher isearcher = new IndexSearcher(ireader);
  124. /*
  125. * 类似SQL,进行关键字查询
  126. */
  127. QueryParser parser = new QueryParser( "content", analyzer);
  128. Query query = parser.parse(text);
  129. //创建了一个查询器,并设置其词法分析器,以及查询的“表名“为”fieldname“。查询结果会返回一个集合,类似SQL的ResultSet,我们可以提取其中存储的内容。
  130. ScoreDoc[] hits = isearcher.search(query, 1000).scoreDocs;
  131. for ( int i = 0; i < hits.length; i++) {
  132. Document hitDoc = isearcher.doc(hits[i].doc);
  133. System.out.println( "-----------");
  134. System.out.println(hitDoc.get( "filename"));
  135. System.out.println(hitDoc.get( "content"));
  136. System.out.println(hitDoc.get( "path"));
  137. System.out.println( "------------");
  138. }
  139. //关闭查询器
  140. ireader.close();
  141. directory.close();
  142. } catch (IOException e) {
  143. e.printStackTrace();
  144. } catch (ParseException e) {
  145. e.printStackTrace();
  146. }
  147. Date date2 = new Date();
  148. System.out.println( "关键字查询-----耗时:" + (date2.getTime() - date1.getTime())
  149. + "ms\n");
  150. }
  151. /**
  152. *
  153. * @throws IOException
  154. */
  155. private static void closeWriter() throws IOException {
  156. if (indexWriter != null)
  157. indexWriter.close();
  158. }
  159. /**
  160. * 读取xls文件内容,引入jxl.jar类型的包
  161. * @param file
  162. * @return 返回内容
  163. */
  164. private 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; i < 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. }
  180. fis.close();
  181. result += sb.toString();
  182. } catch (FileNotFoundException e) {
  183. e.printStackTrace();
  184. } catch (BiffException e) {
  185. e.printStackTrace();
  186. } catch (IOException e) {
  187. e.printStackTrace();
  188. }
  189. return result;
  190. }
  191. /**
  192. * 读取doc类型文件的内容,通过poi.jar
  193. * @param file的类型
  194. * @return 返回文件的内容
  195. */
  196. private static String doc2String(File file) {
  197. String result = "";
  198. try {
  199. FileInputStream fis = new FileInputStream(file); //文件输入流
  200. HWPFDocument document = new HWPFDocument(fis);
  201. Range range = document.getRange();
  202. result += range.text();
  203. fis.close();
  204. } catch (FileNotFoundException e) {
  205. e.printStackTrace();
  206. } catch (IOException e) {
  207. e.printStackTrace();
  208. }
  209. return result;
  210. }
  211. /**
  212. * 读取txt文件的内容
  213. *
  214. * @param file想要读取的文件类型
  215. * @return 返回文件内容
  216. */
  217. private static String txt2String(File file) {
  218. String result = "";
  219. try {
  220. BufferedReader reader = new BufferedReader( new FileReader(file));
  221. String s = "";
  222. while ((s = reader.readLine()) != null) {
  223. result += result + "\n" + s;
  224. }
  225. reader.close();
  226. } catch (FileNotFoundException e) {
  227. e.printStackTrace();
  228. } catch (IOException e) {
  229. e.printStackTrace();
  230. }
  231. return result;
  232. }
  233. /**
  234. * 过滤当前目录下得文件
  235. * @param path 当前目录下得文件
  236. * @return 返回符合条件的文件
  237. */
  238. private static List<File> listFile(String path) {
  239. File[] files = new File(path).listFiles();
  240. List<File> fileList = new ArrayList<File>();
  241. for (File file : files) {
  242. if (isTxtFile(file.getName())) {
  243. fileList.add(file);
  244. }
  245. }
  246. return fileList;
  247. }
  248. /**
  249. * 判断是否为目标文件,支持的格式为.txt,.doc,.xls文件格式 如果是文件类型满足过滤条件,返回true;否则返回false
  250. * @param name 根据文件名的后缀
  251. * @return 是否符合格式规范
  252. */
  253. private static boolean isTxtFile(String name) {
  254. if (name.lastIndexOf( ".txt") > 0)
  255. return true;
  256. else if (name.lastIndexOf( ".doc") > 0)
  257. return true;
  258. else if (name.lastIndexOf( ".xls") > 0)
  259. return true;
  260. return false;
  261. }
  262. public static void main(String[] args) {
  263. //创建索引目录,运行一次,重新创建一次
  264. File fileIndex = new File(INDEX_DIR);
  265. if (deleteIndex(fileIndex)) {
  266. fileIndex.mkdir();
  267. } else {
  268. fileIndex.mkdir();
  269. }
  270. //创建索引文件
  271. createIndex(DATA_DIR);
  272. //通过关键字查询
  273. serarchIndex( "中华");
  274. }
  275. /**
  276. * 删除文件目录下得所有文件
  277. *
  278. * @param fileIndex 当前索引目录下得文件
  279. * @return 返回是否删除重新创建
  280. */
  281. private static boolean deleteIndex(File fileIndex) {
  282. if (fileIndex.isDirectory()) {
  283. File[] files = fileIndex.listFiles();
  284. for ( int i = 0; i < files.length; i++) {
  285. deleteIndex(files[i]);
  286. }
  287. }
  288. fileIndex.delete();
  289. return true;
  290. }
  291. }
通过对几位博文的分析进行总结;

原文博客出自:http://blog.csdn.net/csh624366188/article/category/895342

https://www.cnblogs.com/xing901022/p/3933675.html



一.lucene原理

    Lucene 是apache软件基金会一个开放源代码的全文检索引擎工具包,是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎。它不是一个完整的搜索应用程序,而是为你的应用程序提供索引和搜索功能。lucene 能够为文本类型的数据建立索引,所以你只要能把你要索引的数据格式转化的文本的,Lucene 就能对你的文档进行索引和搜索。比如你要对一些 HTML 文档,PDF 文档进行索引的话你就首先需要把 HTML 文档和 PDF 文档转化成文本格式的,然后将转化后的内容交给 Lucene 进行索引,然后把创建好的索引文件保存到磁盘或者内存中,最后根据用户输入的查询条件在索引文件上进行查询。

搜索应用程序和 Lucene 之间的关系,也反映了利用 Lucene 构建搜索应用程序的流程:


二. 索引和搜索

   索引是现代搜索引擎的核心,建立索引的过程就是把源数据处理成非常方便查询的索引文件的过程。为什么索引这么重要呢,试想你现在要在大量的文档中搜索含有某个关键词的文档,那么如果不建立索引的话你就需要把这些文档顺序的读入内存,然后检查这个文章中是不是含有要查找的关键词,这样的话就会耗费非常多的时间,想想搜索引擎可是在毫秒级的时间内查找出要搜索的结果的。这就是由于建立了索引的原因,你可以把索引想象成这样一种数据结构,他能够使你快速的随机访问存储在索引中的关键词,进而找到该关键词所关联的文档。Lucene 采用的是一种称为反向索引(inverted index)的机制。反向索引就是说我们维护了一个词 / 短语表,对于这个表中的每个词 / 短语,都有一个链表描述了有哪些文档包含了这个词 / 短语。这样在用户输入查询条件的时候,就能非常快的得到搜索结果。搜索引擎首先会对搜索的关键词进行解析,然后再在建立好的索引上面进行查找,最终返回和用户输入的关键词相关联的文档。对于中文用户来说,最关心的问题是其是否支持中文的全文检索。由于Lucene良好架构设计,对中文的支持只需对其语言词法分析接口进行扩展就能实现对中文检索的支持。

三. 索引步骤

  1. 获取内容: Lucene本身没有提供获取内容的工具或者组件,内容是要开发者自己提供相应的程序。这一步包括使用网络爬虫或蜘蛛程序来搜索和界定需要索引的内容。当然,数据来源可能包括数据库、分布式文件系统、本地xml等等。lucene作为一款核心搜索库,不提供任何功能来实现内容获取。目前有大量的开源爬虫软件可以实现这个功能,例如:Solr,lucene的子项;Nutch,apache项目,包含大规模的爬虫工具,抓取和分辨web站点数据;Grub,比较流行的开源web爬虫工具;Heritrix,一款开源的Internet文档搜索程序;Aperture,支持从web站点、文件系统和邮箱中抓取,并解析和索引其中的文本数据。
  2. 建立文档:获取原始内容后,需要对这些内容进行索引,必须将这些内容转换成部件(文档)。文档主要包括几个带值的域,比如标题,正文,摘要,作者和链接。如果文档和域比较重要的话,还可以添加权值。设计完方案后,需要将原始内容中的文本提取出来写入各个文档,这一步可以使用文档过滤器,开源项目如Tika,实现很好的文档过滤。如果要获取的原始内容存储于数据库中,有一些项目通过无缝链接内容获取步骤和文档建立步骤就能轻易地对数据库表进行航所以操作和搜索操作,例如DBSight,Hibernate Search,LuSQL,Compass和Oracle/Lucene集成项目。
  3. 文档分析: 搜索引擎不能直接对文本进行索引:必须将文本分割成一系列被称为语汇单元的独立的原子元素。每一个语汇单元能大致与语言中的“单词”对应起来,这个步骤决定文档中的文本域如何分割成语汇单元系列。lucene提供了大量内嵌的分析器可以轻松控制这步操作。
  4. 文档索引: 将文档加入到索引列表中。Lucene在这一步骤中提供了强档的API,只需简单调用提供的几个方法就可以实现出文档索引的建立。为了提供好的用户体验,索引是必须要处理好的一环:在设计和定制索引程序时必须围绕如何提高用户的搜索体验来进行。

四. 搜索组件

  搜索组件即为输入搜索短语,然后进行分词,然从索引中查找单词,从而找到包含该单词的文档。搜索质量由查准率和查全率来衡量。搜索组件主要包括以下内容:

  1. 用户搜索界面:主要是和用户进行交互的页面,也就是呈现在浏览器中能看到的东西,这里主要考虑的就是页面UI设计了。一个良好的UI设计是吸引用户的重要组成部分。
  2. 建立查询:建立查询主要是指用户输入所要查询的短语,以普通HTML表单或者ajax的方式提交到后台服务器端。然后把词语传递给后台搜索引擎。这就是一个简单建立查询的过程。
  3. 搜索查询:即为查询检索索引然后返回与查询词语匹配的文档。然后把返回来的结构按照查询请求来排序。搜索查询组件覆盖了搜索引擎中大部分的复杂内容。
  4. 展现结果:所谓展现结果,和第一个搜索界面类似。都是一个与用户交互的前端展示页面,作为一个搜索引擎,用户体验永远是第一位。其中前端展示在用户体现上占据了重要地位。

五. 官网实例解析

Lucene的使用主要体现在两个步骤:

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

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


 
 
  1. Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
  2. // Store the index in memory:
  3. Directory directory = new RAMDirectory();
  4. // To store an index on disk, use this instead:
  5. //Directory directory = FSDirectory.open("/tmp/testindex");
  6. IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
  7. IndexWriter iwriter = new IndexWriter(directory, config);
  8. Document doc = new Document();
  9. String text = "This is the text to be indexed.";
  10. doc.add( new Field( "fieldname", text, TextField.TYPE_STORED));
  11. iwriter.addDocument(doc);
  12. iwriter.close();
  13. // Now search the index:
  14. DirectoryReader ireader = DirectoryReader.open(directory);
  15. IndexSearcher isearcher = new IndexSearcher(ireader);
  16. // Parse a simple query that searches for "text":
  17. QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "fieldname", analyzer);
  18. Query query = parser.parse( "text");
  19. ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
  20. assertEquals( 1, hits.length);
  21. // Iterate through the results:
  22. for ( int i = 0; i < hits.length; i++) {
  23. Document hitDoc = isearcher.doc(hits[i].doc);
  24. assertEquals( "This is the text to be indexed.", hitDoc.get( "fieldname"));
  25. }
  26. ireader.close();
  27. 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();
自己实现的一个小实例:对一个文件夹内的内容进行索引的创建,并根据关键字筛选文件,并读取其中的内容

 
 
  1. package cn.lnu.edu.yxk;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.IOException;
  8. import java.util.ArrayList;
  9. import java.util.Date;
  10. import java.util.List;
  11. import jxl.Cell;
  12. import jxl.Sheet;
  13. import jxl.Workbook;
  14. import jxl.read.biff.BiffException;
  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.Field;
  19. import org.apache.lucene.index.DirectoryReader;
  20. import org.apache.lucene.index.IndexWriter;
  21. import org.apache.lucene.index.IndexWriterConfig;
  22. import org.apache.lucene.queryparser.classic.ParseException;
  23. import org.apache.lucene.queryparser.classic.QueryParser;
  24. import org.apache.lucene.search.IndexSearcher;
  25. import org.apache.lucene.search.Query;
  26. import org.apache.lucene.search.ScoreDoc;
  27. import org.apache.lucene.store.Directory;
  28. import org.apache.lucene.store.FSDirectory;
  29. import org.apache.poi.hwpf.HWPFDocument;
  30. import org.apache.poi.hwpf.usermodel.Range;
  31. /**
  32. * 对一个文件夹内的内容进行索引的创建,并根据关键字筛选文件,读取其中的内容。
  33. * @author yxk
  34. *
  35. */
  36. public class IndexManager {
  37. private static String content = ""; //文件里面的内容
  38. private static String INDEX_DIR = "D:\\test\\luceneIndex"; //索引创建的存储目录
  39. private static String DATA_DIR = "D:\\test\\luceneData"; //文件夹的目录
  40. private static Analyzer analyzer = null; //词法分析器
  41. private static Directory directory = null; //索引文件存储的位置
  42. private static IndexWriter indexWriter = null; //创建索引器,索引文件的写入
  43. /**
  44. * 创建当前文件目录的索引
  45. * @param path当前目录的文件
  46. * @return 返回是否创建成功
  47. */
  48. public static Boolean createIndex(String path) {
  49. Date date1 = new Date(); //创建需要的时间
  50. List<File> files = listFile(path); // 获取指定目录下得所有符合条件的文件
  51. // 获取文件的内容
  52. for (File file : files) {
  53. content = "";
  54. //通过文件类型获取文件的内容
  55. String type = file.getName().substring(
  56. file.getName().lastIndexOf( ".") + 1);
  57. if ( "txt".equalsIgnoreCase(type)) {
  58. content += txt2String(file);
  59. } else if ( "doc".equalsIgnoreCase(type)) {
  60. content += doc2String(file);
  61. } else if ( "xls".equalsIgnoreCase(type)) {
  62. content += xls2String(file);
  63. }
  64. System.out.println( "name"+file.getName());
  65. System.out.println( "path"+file.getPath());
  66. //System.out.println(file.getName().getBytes().toString());
  67. System.out.println();
  68. try {
  69. analyzer = new StandardAnalyzer(); //词法分析器
  70. directory = FSDirectory.open( new File(INDEX_DIR).toPath()); //索引创建存储的位置
  71. // System.out.println("ssss"
  72. // + new File(INDEX_DIR).toPath().toString());
  73. //自动创建索引目录
  74. File indexFile = new File(INDEX_DIR);
  75. if (!indexFile.exists()) {
  76. indexFile.mkdirs();
  77. }
  78. //索引文件的写入
  79. IndexWriterConfig config = new IndexWriterConfig(analyzer);
  80. indexWriter = new IndexWriter(directory, config);
  81. /*
  82. * 内容提取,进行索引的存储
  83. */
  84. //申请了一个document对象,这个类似于数据库中的表中的一行。
  85. Document document = new Document();
  86. //把字符串存储起来(因为设置了TextField.TYPE_STORED,如果不想存储,可以使用其他参数,详情参考官方文档),并存储“表明”为"fieldname".
  87. document.add( new org.apache.lucene.document.TextField(
  88. "filename", file.getName(), Field.Store.YES)); //文件名索引创建
  89. document.add( new org.apache.lucene.document.TextField(
  90. "content", content, Field.Store.YES)); //文件内容索引创建
  91. document.add( new org.apache.lucene.document.TextField( "path",
  92. file.getPath(), Field.Store.YES)); //文件路径索引的创建
  93. //把document对象加入到索引创建中
  94. indexWriter.addDocument(document);
  95. //关闭IndexWriter,提交创建内容。
  96. indexWriter.commit();
  97. closeWriter();
  98. } catch (IOException e) {
  99. e.printStackTrace();
  100. }
  101. content = "";
  102. }
  103. Date date2 = new Date();
  104. System.out.println( "创建索引-----耗时:" + (date2.getTime() - date1.getTime())
  105. + "ms\n");
  106. return true;
  107. }
  108. /**
  109. * 查询索引,返回符合条件的文件
  110. *
  111. * @param 查询的字符串
  112. * @return 符合条件的结果
  113. * @throws IOException
  114. */
  115. public static void serarchIndex(String text) {
  116. Date date1 = new Date();
  117. try {
  118. //打开存储位置
  119. directory = FSDirectory.open( new File(INDEX_DIR).toPath());
  120. analyzer = new StandardAnalyzer();
  121. DirectoryReader ireader = DirectoryReader.open(directory);
  122. //创建搜索器
  123. IndexSearcher isearcher = new IndexSearcher(ireader);
  124. /*
  125. * 类似SQL,进行关键字查询
  126. */
  127. QueryParser parser = new QueryParser( "content", analyzer);
  128. Query query = parser.parse(text);
  129. //创建了一个查询器,并设置其词法分析器,以及查询的“表名“为”fieldname“。查询结果会返回一个集合,类似SQL的ResultSet,我们可以提取其中存储的内容。
  130. ScoreDoc[] hits = isearcher.search(query, 1000).scoreDocs;
  131. for ( int i = 0; i < hits.length; i++) {
  132. Document hitDoc = isearcher.doc(hits[i].doc);
  133. System.out.println( "-----------");
  134. System.out.println(hitDoc.get( "filename"));
  135. System.out.println(hitDoc.get( "content"));
  136. System.out.println(hitDoc.get( "path"));
  137. System.out.println( "------------");
  138. }
  139. //关闭查询器
  140. ireader.close();
  141. directory.close();
  142. } catch (IOException e) {
  143. e.printStackTrace();
  144. } catch (ParseException e) {
  145. e.printStackTrace();
  146. }
  147. Date date2 = new Date();
  148. System.out.println( "关键字查询-----耗时:" + (date2.getTime() - date1.getTime())
  149. + "ms\n");
  150. }
  151. /**
  152. *
  153. * @throws IOException
  154. */
  155. private static void closeWriter() throws IOException {
  156. if (indexWriter != null)
  157. indexWriter.close();
  158. }
  159. /**
  160. * 读取xls文件内容,引入jxl.jar类型的包
  161. * @param file
  162. * @return 返回内容
  163. */
  164. private 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; i < 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. }
  180. fis.close();
  181. result += sb.toString();
  182. } catch (FileNotFoundException e) {
  183. e.printStackTrace();
  184. } catch (BiffException e) {
  185. e.printStackTrace();
  186. } catch (IOException e) {
  187. e.printStackTrace();
  188. }
  189. return result;
  190. }
  191. /**
  192. * 读取doc类型文件的内容,通过poi.jar
  193. * @param file的类型
  194. * @return 返回文件的内容
  195. */
  196. private static String doc2String(File file) {
  197. String result = "";
  198. try {
  199. FileInputStream fis = new FileInputStream(file); //文件输入流
  200. HWPFDocument document = new HWPFDocument(fis);
  201. Range range = document.getRange();
  202. result += range.text();
  203. fis.close();
  204. } catch (FileNotFoundException e) {
  205. e.printStackTrace();
  206. } catch (IOException e) {
  207. e.printStackTrace();
  208. }
  209. return result;
  210. }
  211. /**
  212. * 读取txt文件的内容
  213. *
  214. * @param file想要读取的文件类型
  215. * @return 返回文件内容
  216. */
  217. private static String txt2String(File file) {
  218. String result = "";
  219. try {
  220. BufferedReader reader = new BufferedReader( new FileReader(file));
  221. String s = "";
  222. while ((s = reader.readLine()) != null) {
  223. result += result + "\n" + s;
  224. }
  225. reader.close();
  226. } catch (FileNotFoundException e) {
  227. e.printStackTrace();
  228. } catch (IOException e) {
  229. e.printStackTrace();
  230. }
  231. return result;
  232. }
  233. /**
  234. * 过滤当前目录下得文件
  235. * @param path 当前目录下得文件
  236. * @return 返回符合条件的文件
  237. */
  238. private static List<File> listFile(String path) {
  239. File[] files = new File(path).listFiles();
  240. List<File> fileList = new ArrayList<File>();
  241. for (File file : files) {
  242. if (isTxtFile(file.getName())) {
  243. fileList.add(file);
  244. }
  245. }
  246. return fileList;
  247. }
  248. /**
  249. * 判断是否为目标文件,支持的格式为.txt,.doc,.xls文件格式 如果是文件类型满足过滤条件,返回true;否则返回false
  250. * @param name 根据文件名的后缀
  251. * @return 是否符合格式规范
  252. */
  253. private static boolean isTxtFile(String name) {
  254. if (name.lastIndexOf( ".txt") > 0)
  255. return true;
  256. else if (name.lastIndexOf( ".doc") > 0)
  257. return true;
  258. else if (name.lastIndexOf( ".xls") > 0)
  259. return true;
  260. return false;
  261. }
  262. public static void main(String[] args) {
  263. //创建索引目录,运行一次,重新创建一次
  264. File fileIndex = new File(INDEX_DIR);
  265. if (deleteIndex(fileIndex)) {
  266. fileIndex.mkdir();
  267. } else {
  268. fileIndex.mkdir();
  269. }
  270. //创建索引文件
  271. createIndex(DATA_DIR);
  272. //通过关键字查询
  273. serarchIndex( "中华");
  274. }
  275. /**
  276. * 删除文件目录下得所有文件
  277. *
  278. * @param fileIndex 当前索引目录下得文件
  279. * @return 返回是否删除重新创建
  280. */
  281. private static boolean deleteIndex(File fileIndex) {
  282. if (fileIndex.isDirectory()) {
  283. File[] files = fileIndex.listFiles();
  284. for ( int i = 0; i < files.length; i++) {
  285. deleteIndex(files[i]);
  286. }
  287. }
  288. fileIndex.delete();
  289. return true;
  290. }
  291. }
通过对几位博文的分析进行总结;

原文博客出自:http://blog.csdn.net/csh624366188/article/category/895342

https://www.cnblogs.com/xing901022/p/3933675.html



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值