搭建lucene的步骤这里就不详细介绍了,无外乎就是下载相关jar包,在eclipse中新建java工程,引入相关的jar包即可

本文主要在没有剖析lucene的源码之前实战一下,通过实战来促进研究

建立索引

下面的程序展示了indexer的使用

  1. package com.wuyudong.mylucene;
  2.  
  3. import org.apache.lucene.index.IndexWriter;
  4. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  5. import org.apache.lucene.document.Document;
  6. import org.apache.lucene.document.Field;
  7. import org.apache.lucene.store.FSDirectory;
  8. import org.apache.lucene.store.Directory;
  9. import org.apache.lucene.util.Version;
  10.  
  11. import java.io.File;
  12. import java.io.FileFilter;
  13. import java.io.IOException;
  14. import java.io.FileReader;
  15.  
  16. public class IndexerTest {
  17.  
  18. public static void main(String[] args) throws Exception {
  19. if (args.length != 2) {
  20. throw new IllegalArgumentException("Usage: java " + IndexerTest.class.getName()
  21. + " <index dir> <data dir>");
  22. }
  23. String indexDir = args[0]; //1 指定目录创建索引
  24. String dataDir = args[1]; //2 对指定目录中的*.txt文件进行索引
  25.  
  26. long start = System.currentTimeMillis();
  27. IndexerTest indexer = new IndexerTest(indexDir);
  28. int numIndexed;
  29. try {
  30. numIndexed = indexer.index(dataDir, new TextFilesFilter());
  31. } finally {
  32. indexer.close();
  33. }
  34. long end = System.currentTimeMillis();
  35.  
  36. System.out.println("Indexing " + numIndexed + " files took "
  37. + (end - start) + " milliseconds");
  38. }
  39.  
  40. private IndexWriter writer;
  41.  
  42. public IndexerTest(String indexDir) throws IOException {
  43. Directory dir = FSDirectory.open(new File(indexDir));
  44. writer = new IndexWriter(dir, //3 创建IndexWriter
  45. new StandardAnalyzer( //
  46. Version.LUCENE_30),//
  47. true, //
  48. IndexWriter.MaxFieldLength.UNLIMITED); //
  49. }
  50.  
  51. public void close() throws IOException {
  52. writer.close(); //4 关闭IndexWriter
  53. }
  54.  
  55. public int index(String dataDir, FileFilter filter)
  56. throws Exception {
  57.  
  58. File[] files = new File(dataDir).listFiles();
  59.  
  60. for (File f: files) {
  61. if (!f.isDirectory() &&
  62. !f.isHidden() &&
  63. f.exists() &&
  64. f.canRead() &&
  65. (filter == null || filter.accept(f))) {
  66. indexFile(f);
  67. }
  68. }
  69.  
  70. return writer.numDocs(); //5 返回被索引的文档数
  71. }
  72.  
  73. private static class TextFilesFilter implements FileFilter {
  74. public boolean accept(File path) {
  75. return path.getName().toLowerCase() //6 只索引*.txt文件,采用FileFilter
  76. .endsWith(".txt"); //
  77. }
  78. }
  79.  
  80. protected Document getDocument(File f) throws Exception {
  81. Document doc = new Document();
  82. doc.add(new Field("contents", new FileReader(f))); //7 索引文件内容
  83. doc.add(new Field("filename", f.getName(), //8 索引文件名
  84. Field.Store.YES, Field.Index.NOT_ANALYZED));//
  85. doc.add(new Field("fullpath", f.getCanonicalPath(), //9 索引文件完整路径
  86. Field.Store.YES, Field.Index.NOT_ANALYZED));//
  87. return doc;
  88. }
  89.  
  90. private void indexFile(File f) throws Exception {
  91. System.out.println("Indexing " + f.getCanonicalPath());
  92. Document doc = getDocument(f);
  93. writer.addDocument(doc); //10 向Lucene索引中添加文档
  94. }
  95. }

在eclipse中配置好参数:

E:\luceneinaction\index E:\luceneinaction\lia2e\src\lia\meetlucene\data

运行结果如下:

Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\apache1.0.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\apache1.1.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\apache2.0.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\cpl1.0.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\epl1.0.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\freebsd.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\gpl1.0.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\gpl2.0.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\gpl3.0.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\lgpl2.1.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\lgpl3.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\lpgl2.0.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\mit.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\mozilla1.1.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\mozilla_eula_firefox3.txt
Indexing E:\luceneinaction\lia2e\src\lia\meetlucene\data\mozilla_eula_thunderbird2.txt
Indexing 16 files took 888 milliseconds

在index文件内会产生索引文件:

由于被索引的文件都很小,数量也不大(如下图),但是会花费888ms,还是很让人不安

总体说来,搜索索引比建立索引重要,因为搜索很多次,而索引只是建立一次

搜索索引

接下来将创建一个程序 来对上面创建的索引进行搜索:

  1. import org.apache.lucene.document.Document;
  2. import org.apache.lucene.search.IndexSearcher;
  3. import org.apache.lucene.search.Query;
  4. import org.apache.lucene.search.ScoreDoc;
  5. import org.apache.lucene.search.TopDocs;
  6. import org.apache.lucene.store.FSDirectory;
  7. import org.apache.lucene.store.Directory;
  8. import org.apache.lucene.queryParser.QueryParser;
  9. import org.apache.lucene.queryParser.ParseException;
  10. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  11. import org.apache.lucene.util.Version;
  12.  
  13. import java.io.File;
  14. import java.io.IOException;
  15.  
  16. public class SearcherTest {
  17.  
  18. public static void main(String[] args) throws IllegalArgumentException,
  19. IOException, ParseException {
  20. if (args.length != 2) {
  21. throw new IllegalArgumentException("Usage: java " + SearcherTest.class.getName()
  22. + " <index dir> <query>");
  23. }
  24.  
  25. String indexDir = args[0]; //1 解析输入的索引路径
  26. String q = args[1]; //2 解析输入的查询字符串
  27.  
  28. search(indexDir, q);
  29. }
  30.  
  31. public static void search(String indexDir, String q)
  32. throws IOException, ParseException {
  33.  
  34. Directory dir = FSDirectory.open(new File(indexDir)); //3 打开索引文件
  35. IndexSearcher is = new IndexSearcher(dir); //3
  36.  
  37. QueryParser parser = new QueryParser(Version.LUCENE_30, // 4 解析查询字符串
  38. "contents", //
  39. new StandardAnalyzer( //
  40. Version.LUCENE_30)); //
  41. Query query = parser.parse(q); //4
  42. long start = System.currentTimeMillis();
  43. TopDocs hits = is.search(query, 10); //5 搜索索引
  44. long end = System.currentTimeMillis();
  45.  
  46. System.err.println("Found " + hits.totalHits + //6 记录索引状态
  47. " document(s) (in " + (end - start) + //
  48. " milliseconds) that matched query '" + //
  49. q + "':"); //
  50.  
  51. for(ScoreDoc scoreDoc : hits.scoreDocs) {
  52. Document doc = is.doc(scoreDoc.doc); //7 返回匹配文本
  53. System.out.println(doc.get("fullpath")); //8 显示匹配文件名
  54. }
  55.  
  56. is.close(); //9 关闭IndexSearcher
  57. }
  58. }

设置好参数:E:\luceneinaction\index patent

运行结果如下:

Found 8 document(s) (in 12 milliseconds) that matched query 'patent':
E:\luceneinaction\lia2e\src\lia\meetlucene\data\cpl1.0.txt
E:\luceneinaction\lia2e\src\lia\meetlucene\data\mozilla1.1.txt
E:\luceneinaction\lia2e\src\lia\meetlucene\data\epl1.0.txt
E:\luceneinaction\lia2e\src\lia\meetlucene\data\gpl3.0.txt
E:\luceneinaction\lia2e\src\lia\meetlucene\data\apache2.0.txt
E:\luceneinaction\lia2e\src\lia\meetlucene\data\gpl2.0.txt
E:\luceneinaction\lia2e\src\lia\meetlucene\data\lpgl2.0.txt
E:\luceneinaction\lia2e\src\lia\meetlucene\data\lgpl2.1.txt

可以看到速度很快(12ms),打印的是文件的绝对路径,这是因为indexer存储的是文件的绝对路径

Lucene实战构建索引的更多相关文章

  1. 【Lucene实验1】构建索引

    一.实验名称:构建索引 二.实验日期:2013/9/21 三.实验目的: 1)        能理解Lucene中的Document-Field结构的数据建模过程: 2)        能编针对特定数 ...

  2. 如何提高Lucene构建索引的速度

    如何提高Lucene构建索引的速度 hans(汉斯) 2013-01-27 10:12 对于Lucene>=2.3:IndexWriter可以自行根据内存使用来释放缓存.调用writer.set ...

  3. 【Lucene】Apache Lucene全文检索引擎架构之构建索引2

    上一篇博文中已经对全文检索有了一定的了解,这篇文章主要来总结一下全文检索的第一步:构建索引.其实上一篇博文中的示例程序已经对构建索引写了一段程序了,而且那个程序还是挺完善的.不过从知识点的完整性来考虑 ...

  4. Lucene实战(第2版)》

    <Lucene实战(第2版)>基于Apache的Lucene 3.0,从Lucene核心.Lucene应用.案例分析3个方面详细系统地介绍了Lucene,包括认识Lucene.建立索引.为 ...

  5. lucene实战(第二版)学习笔记

    初识Lucene 构建索引 为应用程序添加搜索功能 Lucene的分析过程

  6. Lucene核心--构建Lucene搜索(下篇,理论篇)

    2.1.6 截取索引(Indextruncate) 一些应用程序的所以文档的大小先前是不知道的.作为控制RAM和磁盘存储空间的使用数量的安全机制,你可能想要限制每个字段允许输入索引的输入数量.一个大的 ...

  7. Lucene核心--构建Lucene搜索(上篇,理论篇)

    2.1构建Lucene搜索 2.1.1 Lucene内容模型 一个文档(document)就是Lucene建立索引和搜索的原子单元,它由一个或者多个字段(field)组成,字段才是Lucene的真实内 ...

  8. Lucene底层原理和优化经验分享(1)-Lucene简介和索引原理

    Lucene底层原理和优化经验分享(1)-Lucene简介和索引原理 2017年01月04日 08:52:12 阅读数:18366 基于Lucene检索引擎我们开发了自己的全文检索系统,承担起后台PB ...

  9. 3.2 Lucene实战:一个简单的小程序

    在讲解Lucene索引和检索的原理之前,我们先来实战Lucene:一个简单的小程序! 一.索引小程序 首先,new一个java project,名字叫做LuceneIndex. 然后,在project ...

随机推荐

  1. zk框架window之间传值操作

    .zul中向Action传递参数: <listcell> <button label="修改" onClick="@command('edit',id= ...

  2. WCF安全1-开篇

    概述: WCF安全简介 1.在企业级应用中什么是“安全” 答: (1)应用能够识别用户的身份-认证Authentication (2)应用能够将用户的操作和可访问的资源限制在其允许的权限范围之内-授权 ...

  3. "浅谈Android"第二篇:活动(Activity)

        距离上一篇文章,过去有半个多月了,在此期间忙于工作,疏于整理和总结,特此写下这篇博文,来谈谈自己对Activity的理解.总所周知,Activity组件在Android中的重要性不言而喻,我们 ...

  4. Direct3D11学习:(九)绘制基本几何体

    转载请注明出处:http://www.cnblogs.com/Ray1024 一.概述 Direct3D中很多复杂的几何效果都是由基本的几何体组合而成的,这篇文章中,我们来学习集中常见的基本几何体的绘 ...

  5. Mysql学习笔记(十二)触发器

    学习内容: 1.触发器: 什么是触发器?我们什么时候能够使用触发器?   触发器就是用来监听某个表的变化,当这个表发生变化的时候来触发某种操作..比若说两个表是相互关联的,当我们在对其中一个表格进行操 ...

  6. SystemTap知识(一)

    SystemTap是一个系统的跟踪探测工具.它能让用户来跟踪和研究计算机系统在底层的实现. 安装SystemTap需要为你的系统内核安装-devel,-debuginfo,-debuginfo-com ...

  7. CentOS6.5菜鸟之旅:识别NTFS分区

    一.前言 CentOS默认时不能识别NTFS分区的,需要那么需要安装fuse-ntfs-3g来处理了. 二.安装fuse-ntfs-3g     yum install fuse-ntfs-3g

  8. sprint2 项目部署+展示

    项目展示网址: http://160q49b998.51mypc.cn/ (注:所有用户密码都为123456,校内断网时访问不了)

  9. Scrum 项目5.0--软件工程

    1.燃尽图: 2.每日立会更新任务板上任务完成情况.燃尽图的实际线,分析项目进度是否在正轨.    每天的例会结束后的都为任务板拍照并发布到博客上     团队贡献分: 蔡舜 : 21 卢晓洵 : 1 ...

  10. 面向对象的JavaScript(2):类

    在小项目中对于JavaScript使用,只要写几个function就行了.但在大型项目中,尤其是在开发追求良好的用户体验的网站中,如SNS,就会 用到大量的JavaScrpt,有时JavaScript ...