Lucene建索引代码
Lucene 是apache软件基金会一个开放源代码的全文检索引擎工具包,是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎。 Lucene的目的是为软件开发人员提供一个简单易用的工具包,以方便的在目标系统中实现全文检索的功能,或者是以此为基础建立起完整的全文检索引擎。
下载地址:
http://www.apache.org/dyn/closer.cgi/lucene/java/4.10.1
1.建立lucene索引模块示例
package luceneL; import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; 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.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version; public class Index { public static void main(String[] args) throws Exception {
// String str1 = "e:/luc2";
String str2 = "e:/q";
// String str1 = args[0];
// String str2 = args[1];
Index in = new Index();
in.index(str1, str2);
}
public void index(String str1, String str2) throws Exception{
IndexWriter writer = null;
try {
// (1)创建Directory new RAMDirectory();建立在内存中
// Directory directory = new RAMDirectory();
Directory directory = FSDirectory.open(new File(str1));
// (2)创建IndexWriter,通过它来写索引
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_9, new StandardAnalyzer(Version.LUCENE_4_9)); iwc.setUseCompoundFile(false);
writer = new IndexWriter(directory, iwc);
// (3)创建Document对象,大小,路径、内容等信息作为Field存在在Document里面
Document document = null;
// (4)为Document文档添加Field
List<String> list = new ArrayList<String>();
File f = new File(str2);
long startTime=new Date().getTime(); for(File file : f.listFiles()){
System.out.println("开始建立索引,请稍等"); // 先存储路径、名字、内容
list=getContent(file);
System.out.println("文件有"+list.size()+"条数据");
for(int i=0;i<list.size();i++){ String[] con=list.get(i).split("\001");
document = new Document();
//System.out.println(co1.get(i)); for(int j=0;j<con.length;j++){
document.add(new TextField("c"+j, con[j],Field.Store.YES));
} // Field.Store.YES是否把这个文件的全名存储到硬盘中
// Field.Index.NOT_ANALYZED没有必要分词
document.add(new StringField("file_name", file.getName(), Field.Store.YES));
document.add(new StringField("path", file.getAbsolutePath(), Field.Store.YES));
// (5)通过IndexWriter添加文档到索引中
writer.addDocument(document); con =null; }
list.clear();
}
long endTime=new Date().getTime();
System.out.println("共花了"+(endTime-startTime)+"毫秒将文档增加到索引中"+str1); } catch (IOException e) {
e.printStackTrace();
}finally{
if(writer!=null){
try { writer.close();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} /**
* 获取文本内容
*/ public List<String> getContent(File file) throws Exception{ BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
//StringBuffer sb=new StringBuffer();
String line=br.readLine();
List<String> contents = new ArrayList<String>();
while(line!=null){
//sb.append(line);
contents.add(line);
//sb=null;
line=br.readLine();
}
br.close();
//return sb.toString();
return contents;
} }
2 检索模块示例
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List; //import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
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.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.lucene.queryparser.classic.QueryParser; public class Search { public static void main(String[] args) throws Exception { String str1 = "e:\\luc2";
String str2 = "mokdis旗舰店";
String str3 = "c2";
int in4 = 10;
// String str1 = args[0];
// String str2 = args[1];
// String str3 = args[2];
// int in4 = Integer.parseInt(args[3]);//检索出多少条数据
Search hl = new Search();
hl.search(str1, str2, str3, in4);
} @SuppressWarnings("deprecation")
public void search(String str1, String str2, String str3, int in4) { Directory directory = null;
IndexReader reader = null;
long startTime = new Date().getTime();
try { directory = FSDirectory.open(new File(str1));// (1)创建Directory,要去什么地方搜索
reader = IndexReader.open(directory); // (2)创建IndexReader,通过它来读取索引
IndexSearcher searcher = new IndexSearcher(reader);// (3)根据IndexReader来创建IndexSearcher
// (4)创建搜索的Query,创建parser来确定要搜索文件的内容,创建搜索的域,创建索引时设置的值
QueryParser parser = new QueryParser(Version.LUCENE_4_9, str3,
new StandardAnalyzer(Version.LUCENE_4_9)); // QueryParser parser = new QueryParser(Version.LUCENE_4_9, str3,
// new WhitespaceAnalyzer(Version.LUCENE_4_9)); Query query;
try {
query = parser.parse(str2);
TopDocs tds = searcher.search(query, in4); // (5)根据Searcher搜索并返回TopDocs
System.out.println("共为您查找到" + tds.totalHits + "条结果");
ScoreDoc[] sds = tds.scoreDocs; // (6)根据TopDocs获取ScoreDoc对象//这是获取一个属性
long midTime = new Date().getTime();
System.out.println("访问索引时间Tindex-1 = " + (midTime - startTime)
+ "毫秒");
int[] docCount = new int[in4];
int i = 0;
for (ScoreDoc sd : sds) {
docCount[i] = sd.doc;
i++;
System.out.println("sd.doc " + sd.doc);// (7)根据Searcher和ScoreDoc对象获取具体的Document对象
Document document = searcher.doc(sd.doc); // -Xmx
// (8)根据Document对象获取需要的值
// System.out.println(document.get("c0"));
System.out.println(document.get(str3));
// System.out.println(document.get("file_name") + "][ "
// + document.get("path"));
document = null;
} long endTime = new Date().getTime();
System.out.println("访问Lucene数据时间Tlocal = "
+ (endTime - midTime) + "毫秒");
System.out.println("总检索时间TLucene = " + (endTime - startTime)
+ "毫秒");
// DocId序列至少涵盖顺序、逆序、随机等情况
List<Integer> list = new ArrayList<Integer>(); for (int j = 0; j < docCount.length; j++) {
list.add(docCount[j]);
}
List<Integer> list1 = new ArrayList<Integer>();// 存原序列
List<Integer> list2 = new ArrayList<Integer>();// 存顺序排列
List<Integer> list3 = new ArrayList<Integer>();// 存倒序排列
list1 = list;// 原序列
System.out.println("原序列为:" + list1);
Collections.sort(list); // 顺序排列
list2 = list;// list2存顺序序列
System.out.println("顺序序列为:" + list2);
Collections.reverse(list); // 倒序排列
list3 = list;// list3存倒序排列
System.out.println("倒序序列为:" + list3);
Collections.shuffle(list); // 随机排列
System.out.println("随机序列为:" + list);// list存随机序列
} catch (ParseException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// (9)关闭Reader
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Lucene建索引代码的更多相关文章
- lucene&solr学习——创建和查询索引(代码篇)
1. Lucene的下载 Lucene是开发全文检索功能的工具包,从官网下载Lucene4.10.3并解压. 官网:http://lucene.apache.org/ 版本:lucene7.7.0 ( ...
- Lucene -- 实时索引
lucene的实时搜索可以分成:实时和近实时的搜索. 实时只能依靠内存了. 近实时可以用lucene中提供org.apache.lucene.index.DirectoryReader.open(In ...
- 如何提高Lucene构建索引的速度
如何提高Lucene构建索引的速度 hans(汉斯) 2013-01-27 10:12 对于Lucene>=2.3:IndexWriter可以自行根据内存使用来释放缓存.调用writer.set ...
- Lucene学习总结之三:Lucene的索引文件格式(1)
Lucene的索引里面存了些什么,如何存放的,也即Lucene的索引文件格式,是读懂Lucene源代码的一把钥匙. 当我们真正进入到Lucene源代码之中的时候,我们会发现: Lucene的索引过程, ...
- Lucene.net(4.8.0) 学习问题记录六:Lucene 的索引系统和搜索过程分析
前言:目前自己在做使用Lucene.net和PanGu分词实现全文检索的工作,不过自己是把别人做好的项目进行迁移.因为项目整体要迁移到ASP.NET Core 2.0版本,而Lucene使用的版本是3 ...
- [lucene系列笔记2]在eclipse里初步使用lucene的索引和查询功能
首先,new一个java project,名字叫做LuceneTools. 然后,在project里new一个class,名字叫做IndexFiles.这个类用来给文件建索引(建好索引以后就可以高效检 ...
- Lucene学习总结之三:Lucene的索引文件格式(1) 2014-06-25 14:15 1124人阅读 评论(0) 收藏
Lucene的索引里面存了些什么,如何存放的,也即Lucene的索引文件格式,是读懂Lucene源代码的一把钥匙. 当我们真正进入到Lucene源代码之中的时候,我们会发现: Lucene的索引过程, ...
- lucene写索引出现锁文件的原因之一
lucene正常情况目录下的文件 有三个文件. segments.gen segments_a08, 还有一个类似 _uw.cfs名字的东西. 当然,不一定都一样, 但肯定是这三个. 如果出现了很多文 ...
- lucene学习笔记:三,Lucene的索引文件格式
Lucene的索引里面存了些什么,如何存放的,也即Lucene的索引文件格式,是读懂Lucene源代码的一把钥匙. 当我们真正进入到Lucene源代码之中的时候,我们会发现: Lucene的索引过程, ...
随机推荐
- js私有共有成员
在小项目中对于JavaScript使用,只要写几个function就行了.但在大型项目中,尤其是在开发追求 良好的用户体验的网站中,如SNS,就会 用到大量的JavaScrpt,有时JavaScr ...
- 使用SoundPool播放音效
针对应用程序经常需要播放密集.短促的音效,因为MediaPlayer存在如下缺点: 1.资源占用量较高.延迟时间较长. 2.不支持多个音效同时播放. SoundPool使用音效池的概念来管理多个短促的 ...
- java之io之File类的list()方法过滤目录的使用
java的io的知识中,File类必须掌握.File类是对文件或者文件夹的封装.它本身并不能对所封装的文件进行读写,它封装的只是文件或文件夹的周边知识,比如 大小啦,创建日期啦,路径啦等等. 如果Fi ...
- bzoj 2143: 飞飞侠
#include<cstdio> #include<iostream> #include<queue> #define inf 1000000000 #define ...
- PowerMock 遇到的问题——2
如果我们要测试的类继承另一个类,而且在构造方法中有super():那么怎么Mock那个super语句呢? 在PowerMock中有一个suppressConstructor方法,具体写法如下: Pow ...
- 一模 (2) day2
第一题: 题目大意:给出n种物品和每种物品的件数,求拿k件的方案数.N<=30 解题过程: 1.一开始总想着是组合数学的模型,结果怎么都想不出来..然后写了个爆搜,数据很弱,只有1个点超时. 2 ...
- bitmap格式分析
位图(Bitmap)当然是最简单的,它Windows显示图片的基本格式,其文件扩展名为*.BMP.在Windows下,任何各式的图片文件(包括视频播放)都要转化为位图个时候才能显示出来,各种格式的图片 ...
- dedecms二级菜单实现
修改channelartlist.lib.php if($typeid==0 || $typeid=='top') { $tpsql = " reid=0 AND ispart<> ...
- 飞天诚信usb-key登录windows+远程桌面
最近在尝试用智能卡做身份验证,以飞天诚信的ePass3000为例. 1.网络环境搭建: 用3台虚机+1台实体机搭一个单独的测试网段:172.16.188.x,如下: 机器名 IP 操作系统 作用 do ...