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

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

建立索引

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

package com.wuyudong.mylucene;

import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version; import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.FileReader; public class IndexerTest { public static void main(String[] args) throws Exception {
if (args.length != 2) {
throw new IllegalArgumentException("Usage: java " + IndexerTest.class.getName()
+ " <index dir> <data dir>");
}
String indexDir = args[0]; //1 指定目录创建索引
String dataDir = args[1]; //2 对指定目录中的*.txt文件进行索引 long start = System.currentTimeMillis();
IndexerTest indexer = new IndexerTest(indexDir);
int numIndexed;
try {
numIndexed = indexer.index(dataDir, new TextFilesFilter());
} finally {
indexer.close();
}
long end = System.currentTimeMillis(); System.out.println("Indexing " + numIndexed + " files took "
+ (end - start) + " milliseconds");
} private IndexWriter writer; public IndexerTest(String indexDir) throws IOException {
Directory dir = FSDirectory.open(new File(indexDir));
writer = new IndexWriter(dir, //3 创建IndexWriter
new StandardAnalyzer( //
Version.LUCENE_30),//
true, //
IndexWriter.MaxFieldLength.UNLIMITED); //
} public void close() throws IOException {
writer.close(); //4 关闭IndexWriter
} public int index(String dataDir, FileFilter filter)
throws Exception { File[] files = new File(dataDir).listFiles(); for (File f: files) {
if (!f.isDirectory() &&
!f.isHidden() &&
f.exists() &&
f.canRead() &&
(filter == null || filter.accept(f))) {
indexFile(f);
}
} return writer.numDocs(); //5 返回被索引的文档数
} private static class TextFilesFilter implements FileFilter {
public boolean accept(File path) {
return path.getName().toLowerCase() //6 只索引*.txt文件,采用FileFilter
.endsWith(".txt"); //
}
} protected Document getDocument(File f) throws Exception {
Document doc = new Document();
doc.add(new Field("contents", new FileReader(f))); //7 索引文件内容
doc.add(new Field("filename", f.getName(), //8 索引文件名
Field.Store.YES, Field.Index.NOT_ANALYZED));//
doc.add(new Field("fullpath", f.getCanonicalPath(), //9 索引文件完整路径
Field.Store.YES, Field.Index.NOT_ANALYZED));//
return doc;
} private void indexFile(File f) throws Exception {
System.out.println("Indexing " + f.getCanonicalPath());
Document doc = getDocument(f);
writer.addDocument(doc); //10 向Lucene索引中添加文档
}
}

在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,还是很让人不安

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

搜索索引

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

import org.apache.lucene.document.Document;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.util.Version; import java.io.File;
import java.io.IOException; public class SearcherTest { public static void main(String[] args) throws IllegalArgumentException,
IOException, ParseException {
if (args.length != 2) {
throw new IllegalArgumentException("Usage: java " + SearcherTest.class.getName()
+ " <index dir> <query>");
} String indexDir = args[0]; //1 解析输入的索引路径
String q = args[1]; //2 解析输入的查询字符串 search(indexDir, q);
} public static void search(String indexDir, String q)
throws IOException, ParseException { Directory dir = FSDirectory.open(new File(indexDir)); //3 打开索引文件
IndexSearcher is = new IndexSearcher(dir); //3 QueryParser parser = new QueryParser(Version.LUCENE_30, // 4 解析查询字符串
"contents", //
new StandardAnalyzer( //
Version.LUCENE_30)); //
Query query = parser.parse(q); //4
long start = System.currentTimeMillis();
TopDocs hits = is.search(query, 10); //5 搜索索引
long end = System.currentTimeMillis(); System.err.println("Found " + hits.totalHits + //6 记录索引状态
" document(s) (in " + (end - start) + //
" milliseconds) that matched query '" + //
q + "':"); // for(ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = is.doc(scoreDoc.doc); //7 返回匹配文本
System.out.println(doc.get("fullpath")); //8 显示匹配文件名
} is.close(); //9 关闭IndexSearcher
}
}

设置好参数: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. seajs中spm压缩工具使用

    seajs是个好东西,用起来很方便,但是她的压缩工具spm确不被网友看好,因为使用起来很麻烦,捯饬了一天多,终于勉强能压缩了,这里就简单记录一下. 按照地址:http://www.zhangxinxu ...

  2. Eclipse卸载插件

    Eclipse卸载插件 ### 本人Eclipse版本为:Eclipse Mars 1. 选择: Help -> Install New Software , 如下图:2. 点击 what is ...

  3. [Python] Basic operations in Pycharm

    From: http://learnpythonthehardway.org/book Comment with line comment: Ctrl + slash Run: Shift + F10 ...

  4. MySQL忘记root密码的找回方法

    (1)登录到数据库所在服务器,手工kill掉MySQL进程: kill ' cat /mysql-data-directory/hostname.pid'     其中,/mysql-data-dir ...

  5. JAVA jdbc(数据库连接池)学习笔记(一)

    学习内容: 1.JDBC的含义... JDBC想必学过JAVA的就不会陌生,JDBC到底是什么呢?其实就是由JAVA的一些类和接口构成的API,保存在java.sql和javax.sql..包中的一些 ...

  6. 轻松认识JVM运行时数据区域(使用思维导图)

    下面是个人阅读周志明编写的深入浅出Java虚拟机做成思维导图的笔记,线条.颜色和图片的视觉印象比起单纯文字笔记好得太多了,文字笔记的枯燥以及硬性记忆我就不再多说,特别对于JVM这块略微有点枯燥的知识, ...

  7. [Tool] Fiddle2基本使用

    Fiddler2已经成网页调试必备的工具. 简述下快捷命令: ?url =statu.=method @host bpafter url bpv method start stop 参考的文章: Fi ...

  8. wpf 下面用MVVC的RelayCommand命令引发的一个异常

    具体解决方法参见我的博问:https://q.cnblogs.com/list/myquestion

  9. 移动web开发总结

    让网页的宽度自适应屏幕<meta name="viewport" content="width=device-width"/>   1)html上加 ...

  10. linux下安装或升级GCC4.8,以支持C++11标准

    C++11标准在2011年8月份获得一致通过,这是自1998年后C++语言第一次大修订,对C++语言进行了改进和扩充.随后各编译器厂商都各自实现或部分实现了C++中的特性. 如需查看各编译器对C++1 ...