辞职交接期间无聊看了一下搜索引擎,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入门的更多相关文章

  1. lucene4入门(3)琐记

    欢迎转载http://www.cnblogs.com/shizhongtao/p/3440486.html <--这个是lucene4.6的api下载地址,格式是chm的.需要的人可以下载htt ...

  2. lucene4入门(1)

    欢迎转载http://www.cnblogs.com/shizhongtao/p/3440325.html lucene你可以理解为一种数据库,他是全文搜索的一种引擎. 1.首先去官网download ...

  3. lucene4入门(2)搜索

    欢迎转载http://www.cnblogs.com/shizhongtao/p/3440479.html 接着上一篇,这里继续搜索,对于搜索和创建一样,首先你要确定搜索位置,然后用规定的类来读取.还 ...

  4. [全文检索]Lucene基础入门.

    本打算直接来学习Solr, 现在先把Lucene的只是捋一遍. 本文内容: 1. 搜索引擎的发展史 2. Lucene入门 3. Lucene的API详解 4. 索引调优 5. Lucene搜索结果排 ...

  5. Lucene基础(一)--入门

    Lucene介绍 lucene的介绍,这里引用百度百科的介绍Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,即它不是一个完整的全文检索引 ...

  6. Lucene全文检索入门使用

    一. 什么是全文检索 全文检索是计算机程序通过扫描文章中的每一个词,对每一个词建立一个索引,指明该词在文章中出现的次数和位置.当用户查询时根据建立的索引查找,类似于通过字典的检索字表查字的过程 全文检 ...

  7. ElasticSearch入门介绍之安装部署(二)

    散仙,在上篇文章对ElasticSearch整体入门作了个介绍,那么本篇我们来看下,如何安装,部署es,以及如何安装es的几个比较常用的插件. es的安装和部署,是非常简单方便的,至少这一点散仙在es ...

  8. Angular2入门系列教程7-HTTP(一)-使用Angular2自带的http进行网络请求

    上一篇:Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数 感觉这篇不是很好写,因为涉及到网络请求,如果采用真实的网络请求,这个例子大家拿到手估计还要自己写一个web ...

  9. ABP入门系列(1)——学习Abp框架之实操演练

    作为.Net工地搬砖长工一名,一直致力于挖坑(Bug)填坑(Debug),但技术却不见长进.也曾热情于新技术的学习,憧憬过成为技术大拿.从前端到后端,从bootstrap到javascript,从py ...

随机推荐

  1. C++中(int&)和(int)的区别

    在说这个问题之前,先说两个需要知道的背景知识: (1)语言的类型的强制转换不会修改原来的数据,会另外的开辟一个临时的或者程序中指定的空间来存储强制转换后的值. (2)C++引用的实现是在符号表中动了手 ...

  2. python--内建函数(1)

    Python中,按照对象是否可变,将类型分类为: 不可变类型:对象的内容不能够改变(not mutable),这些类型中主要有数值类型(整数,浮点数,复数),字符串类型,元组等 可变类型:对象的内容能 ...

  3. Controller.RedirectToAction 方法

    此成员被重载.有关此成员的完整信息,包括语法.用法和示例,请单击重载列表中的名称.

  4. Vijos P1067Warcraft III 守望者的烦恼

    题目 背景 守望者-warden,长期在暗夜精灵的的首都艾萨琳内担任视察监狱的任务,监狱是成长条行的,守望者warden拥有一个技能名叫“闪烁”,这个技能可以把她传送到后面的监狱内查看,她比较懒,一般 ...

  5. Java学习之二分查找算法

    好久没写算法了.只记得递归方法..结果测试下爆栈了. 思路就是取范围的中间点,判断是不是要找的值,是就输出,不是就与范围的两个临界值比较大小,不断更新临界值直到找到为止,给定的集合一定是有序的. 自己 ...

  6. uvalive 2322 Wooden Sticks(贪心)

    题目连接:2322 Wooden Sticks 题目大意:给出要求切的n个小木棍 , 每个小木棍有长度和重量,因为当要切的长度和重量分别大于前面一个的长度和重量的时候可以不用调整大木棍直接切割, 否则 ...

  7. POJ输出状态的逻辑。

    实測POJ应该是採取一个一个点測.哪个点fail了就输出哪个点的状态,但接下来的点貌似还是要測. 測试方法,1000先測出有6个測点1,2,3,4,6.15,然后交了下面代码. #include &l ...

  8. 设计模式(一)工厂模式Factory(创建型)

    设计模式一 工厂模式Factory 在面向对象编程中, 最通常的方法是一个new操作符产生一个对象实例,new操作符就是用来构造对象实例的.可是在一些情况下, new操作符直接生成对象会带来一些问题. ...

  9. Java怎样高速构造JSON字符串

    目标:依据key/value高速构造一个JSON字符串作为參数提交到web REST API服务上. 分别測试里阿里巴巴的FastJson和Google Gson,终于我採用了Google Gson来 ...

  10. z-index要同级比较,absolute包含块外有overflow-hidden

    z-index只能在position属性值为relative或absolute或fixed的元素上有效. z-index只决定同一父元素中的同级子元素的堆叠顺序. position:absolute ...