Lucene4.3入门
辞职交接期间无聊看了一下搜索引擎,java社区比较火的当然是Lucene,想写一个简单的小例子,在网上找了些资料,不过都不是4.3的,自己看了一下。
下载地址:http://lucene.apache.org/core/
项目结构
constans.java 是常量类
LuceneIndex.java 建立索引类
LuceneSearch.java 搜索类
数据文件:
package com.xin;
public class Constants {
public final static String INDEX_FILE_PATH = "e:\\lucene\\test"; //索引的文件的存放路径
public final static String INDEX_STORE_PATH = "e:\\lucene\\index"; //索引的存放位置
}
package com.xin; import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Date; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
/**
* @author chongxin
* @since 2013/6/19
* @version Lucene 4.3.1
* */
public class LuceneIndex {
// 索引器
private IndexWriter writer = null;
public LuceneIndex() {
try {
//索引文件的保存位置
Directory dir = FSDirectory.open(new File(Constants.INDEX_STORE_PATH));
//分析器
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
//配置类
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40,analyzer);
iwc.setOpenMode(OpenMode.CREATE);//创建模式 OpenMode.CREATE_OR_APPEND 添加模式 writer = new IndexWriter(dir, iwc);
} catch (Exception e) {
e.printStackTrace();
}
} // 将要建立索引的文件构造成一个Document对象,并添加一个域"content"
private Document getDocument(File f) throws Exception {
Document doc = new Document(); FileInputStream is = new FileInputStream(f);
Reader reader = new BufferedReader(new InputStreamReader(is));
//字符串 StringField LongField TextField
Field pathField = new StringField("path", f.getAbsolutePath(),Field.Store.YES);
Field contenField = new TextField("contents", reader);
//添加字段
doc.add(contenField);
doc.add(pathField);
return doc;
} public void writeToIndex() throws Exception {
File folder = new File(Constants.INDEX_FILE_PATH); if (folder.isDirectory()) {
String[] files = folder.list();
for (int i = 0; i < files.length; i++) {
File file = new File(folder, files[i]);
Document doc = getDocument(file);
System.out.println("正在建立索引 : " + file + "");
writer.addDocument(doc);
}
}
} public void close() throws Exception {
writer.close();
} public static void main(String[] args) throws Exception {
// 声明一个对象
LuceneIndex indexer = new LuceneIndex();
// 建立索引
Date start = new Date();
indexer.writeToIndex();
Date end = new Date(); System.out.println("建立索引用时" + (end.getTime() - start.getTime()) + "毫秒"); indexer.close();
}
}
执行结果:
正在建立索引 : e:\lucene\test\a.txt
正在建立索引 : e:\lucene\test\b.txt
正在建立索引 : e:\lucene\test\c.txt
正在建立索引 : e:\lucene\test\d.txt
建立索引用时109毫秒
生成的索引文件:
查找:
package com.xin; import java.io.File;
import java.util.Date; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
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.util.Version; /**
* @author chongxin
* @since 2013/6/19
* @version Lucene 4.3.1
* */
public class LuceneSearch {
// 声明一个IndexSearcher对象
private IndexSearcher searcher = null;
// 声明一个Query对象
private Query query = null;
private String field = "contents"; public LuceneSearch() {
try {
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(Constants.INDEX_STORE_PATH)));
searcher = new IndexSearcher(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
//返回查询结果
public final TopDocs search(String keyword) {
System.out.println("正在检索关键字 : " + keyword);
try {
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
QueryParser parser = new QueryParser(Version.LUCENE_40, field,analyzer);
// 将关键字包装成Query对象
query = parser.parse(keyword);
Date start = new Date();
TopDocs results = searcher.search(query, 5 * 2);
Date end = new Date();
System.out.println("检索完成,用时" + (end.getTime() - start.getTime())
+ "毫秒");
return results;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//打印结果
public void printResult(TopDocs results) {
ScoreDoc[] h = results.scoreDocs;
if (h.length == 0) {
System.out.println("对不起,没有找到您要的结果。");
} else {
for (int i = 0; i < h.length; i++) {
try {
Document doc = searcher.doc(h[i].doc);
System.out.print("这是第" + i + "个检索到的结果,文件名为:");
System.out.println(doc.get("path"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println("--------------------------");
} public static void main(String[] args) throws Exception {
LuceneSearch test = new LuceneSearch();
TopDocs h = null;
h = test.search("中国");
test.printResult(h);
h = test.search("人民");
test.printResult(h);
h = test.search("共和国");
test.printResult(h);
} }
Lucene4.3入门的更多相关文章
- lucene4入门(3)琐记
欢迎转载http://www.cnblogs.com/shizhongtao/p/3440486.html <--这个是lucene4.6的api下载地址,格式是chm的.需要的人可以下载htt ...
- lucene4入门(1)
欢迎转载http://www.cnblogs.com/shizhongtao/p/3440325.html lucene你可以理解为一种数据库,他是全文搜索的一种引擎. 1.首先去官网download ...
- lucene4入门(2)搜索
欢迎转载http://www.cnblogs.com/shizhongtao/p/3440479.html 接着上一篇,这里继续搜索,对于搜索和创建一样,首先你要确定搜索位置,然后用规定的类来读取.还 ...
- [全文检索]Lucene基础入门.
本打算直接来学习Solr, 现在先把Lucene的只是捋一遍. 本文内容: 1. 搜索引擎的发展史 2. Lucene入门 3. Lucene的API详解 4. 索引调优 5. Lucene搜索结果排 ...
- Lucene基础(一)--入门
Lucene介绍 lucene的介绍,这里引用百度百科的介绍Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,即它不是一个完整的全文检索引 ...
- Lucene全文检索入门使用
一. 什么是全文检索 全文检索是计算机程序通过扫描文章中的每一个词,对每一个词建立一个索引,指明该词在文章中出现的次数和位置.当用户查询时根据建立的索引查找,类似于通过字典的检索字表查字的过程 全文检 ...
- ElasticSearch入门介绍之安装部署(二)
散仙,在上篇文章对ElasticSearch整体入门作了个介绍,那么本篇我们来看下,如何安装,部署es,以及如何安装es的几个比较常用的插件. es的安装和部署,是非常简单方便的,至少这一点散仙在es ...
- Angular2入门系列教程7-HTTP(一)-使用Angular2自带的http进行网络请求
上一篇:Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数 感觉这篇不是很好写,因为涉及到网络请求,如果采用真实的网络请求,这个例子大家拿到手估计还要自己写一个web ...
- ABP入门系列(1)——学习Abp框架之实操演练
作为.Net工地搬砖长工一名,一直致力于挖坑(Bug)填坑(Debug),但技术却不见长进.也曾热情于新技术的学习,憧憬过成为技术大拿.从前端到后端,从bootstrap到javascript,从py ...
随机推荐
- oracle 开发笔记“跨数据库查询复制”
1.方法一:创建DBL(data base link) CREATE PUBLIC DATABASE LINK 数据链名称 CONNECT TO 登陆用户名 IDENTIFIED BY 密码 USIN ...
- Python之路Day14
主要内容:jQuery进阶.CSS伪类和伪元素.jQuery插件 tab菜单样式 checkbox全选.反选 位置:scrollTop和offset 事件:两种绑定事件的方式和委托delegate a ...
- 最短路Dijkstra和Flyod
Problem Description 在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt.但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要 ...
- 周根项《一分钟速算》全集播放&下载地址
点击图片就可以观看 ↓↓↓↓↓↓↓↓ 第1章:指算法 周根项<一分钟速算>第1章:指算法 第一节 对手的认识 周根项<一分钟速算>第1章:指算法 第二节 个位数比十位数大1乘以 ...
- ASP.NET站点安全
<configuration> <appSettings/> <connectionStrings> <add name="MyBookShop&q ...
- Android 开发 AirPlay Server
安卓上开发 AirPlay Server 主要是参考了和修改了 DroidAirPlay项目 , 和Airplay 协议 1, 将DroidAirPlay 下载下来 2, Eclipse 新建一个 ...
- Codeforces 479D - Long Jumps
479D - Long Jumps, 480B - Long Jumps It , or . If we can already measure both x and y, output . Then ...
- ASP.NET Core (一):简介
下一篇:ASP.NET Core(二):入门 英文原版:Introduction to ASP.NET Core 关于ASP.NET Core ASP.NET Core 是一个全新的开源.跨平台框架, ...
- VC++共享数据段实现进程之间共享数据
当我写了一个程序,我希望当这个程序同时运行两遍的时候,两个进程之间能共享一些全局变量,怎么办呢?很简单,使用VC\VC++的共享数据段.; #pragma data_seg()//恢复到正常段继续编程 ...
- 用QFileSystemWatcher来监视文件和目录的改变(内部还是使用了timer)
Use Case: 两个程序共享同一个Configuration文件,当一个程序作出改变的时候,需要另外一个程序能够及时响应. 之前其实猜的八九不离十,估计是有一个Timer,然后定时查询Config ...