搭建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. 论文第4章:iOS绘图平台的实现

    面向移动设备的矢量绘图平台设计与实现 Design and Implementation of Mobile Device-oriented Vector Drawing Platform 引用本论文 ...

  2. Hadoop入门进阶课程11--Sqoop介绍、安装与操作

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,博主为石山园,博客地址为 http://www.cnblogs.com/shishanyuan  ...

  3. cmd 窗口配置mysql数据库

    1.运行-cmd 进入command 窗口 首先cd 到mysql目录下的bin的 路运行-cmd 进入command 窗口 首先cd 到mysql目录下的bin的路径.注意cd D盘时直接输入D:就 ...

  4. 将form表单元素转为实体对象 或集合 -ASP.NET C#

    简介: 做WEBFROM开发的同学都知道后台接收参数非常麻烦 虽然MVC中可以将表单直接转为集实,但不支持表单转为 LIST<T>这种集合 单个对象的用法: 表单: <input n ...

  5. SQL中对XML的处理

    DECLARE  @PreSOMasterXML XMLDECLARE   @SDA VARCHAR(100)SET @PreSOMasterXML=N'<ProcessTaskRequest& ...

  6. 自定义UICollectionViewController之后 如何设置UICollectionView的布局方式

    我们很多时候使用UICollectionView 可能都是直接创建 UICollectionView   通过初始化的时候  传入一个布局对象的方式来使用UICollectionView 比如我们之前 ...

  7. Mysql查找所有项目开始时间比之前项目结束时间小的项目ID

    这是之前遇到过的一道sql面试题,供参考学习: 查找所有项目开始时间比之前项目结束时间小的项目ID mysql> select * from t2; +----+---------------- ...

  8. 如何花样展示自己的摄影作品?CSS+JS+Html

    注意:Windows平台推荐使用Edge.Chrome.FireFox,部分浏览器打不开 P.S.慢慢用鼠标在图片上拖拽会感觉更神奇     // 0.5 ? 1 : -1; }, ease: fun ...

  9. C#设计模式——观察者模式(Observer Pattern)

    一.概述在软件设计工作中会存在对象之间的依赖关系,当某一对象发生变化时,所有依赖它的对象都需要得到通知.如果设计的不好,很容易造成对象之间的耦合度太高,难以应对变化.使用观察者模式可以降低对象之间的依 ...

  10. C#中的lock关键字有何作用

    作为C#的程序员来说,在遇到线程同步的需求时最常用的就是lock关键字.但如何正确并有效地使用lock,却是能否高效地达到同步要求的关键.正因为如此,程序员需要完全理解lock究竟为程序做了什么. 所 ...