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建索引代码的更多相关文章

  1. lucene&solr学习——创建和查询索引(代码篇)

    1. Lucene的下载 Lucene是开发全文检索功能的工具包,从官网下载Lucene4.10.3并解压. 官网:http://lucene.apache.org/ 版本:lucene7.7.0 ( ...

  2. Lucene -- 实时索引

    lucene的实时搜索可以分成:实时和近实时的搜索. 实时只能依靠内存了. 近实时可以用lucene中提供org.apache.lucene.index.DirectoryReader.open(In ...

  3. 如何提高Lucene构建索引的速度

    如何提高Lucene构建索引的速度 hans(汉斯) 2013-01-27 10:12 对于Lucene>=2.3:IndexWriter可以自行根据内存使用来释放缓存.调用writer.set ...

  4. Lucene学习总结之三:Lucene的索引文件格式(1)

    Lucene的索引里面存了些什么,如何存放的,也即Lucene的索引文件格式,是读懂Lucene源代码的一把钥匙. 当我们真正进入到Lucene源代码之中的时候,我们会发现: Lucene的索引过程, ...

  5. Lucene.net(4.8.0) 学习问题记录六:Lucene 的索引系统和搜索过程分析

    前言:目前自己在做使用Lucene.net和PanGu分词实现全文检索的工作,不过自己是把别人做好的项目进行迁移.因为项目整体要迁移到ASP.NET Core 2.0版本,而Lucene使用的版本是3 ...

  6. [lucene系列笔记2]在eclipse里初步使用lucene的索引和查询功能

    首先,new一个java project,名字叫做LuceneTools. 然后,在project里new一个class,名字叫做IndexFiles.这个类用来给文件建索引(建好索引以后就可以高效检 ...

  7. Lucene学习总结之三:Lucene的索引文件格式(1) 2014-06-25 14:15 1124人阅读 评论(0) 收藏

    Lucene的索引里面存了些什么,如何存放的,也即Lucene的索引文件格式,是读懂Lucene源代码的一把钥匙. 当我们真正进入到Lucene源代码之中的时候,我们会发现: Lucene的索引过程, ...

  8. lucene写索引出现锁文件的原因之一

    lucene正常情况目录下的文件 有三个文件. segments.gen segments_a08, 还有一个类似 _uw.cfs名字的东西. 当然,不一定都一样, 但肯定是这三个. 如果出现了很多文 ...

  9. lucene学习笔记:三,Lucene的索引文件格式

    Lucene的索引里面存了些什么,如何存放的,也即Lucene的索引文件格式,是读懂Lucene源代码的一把钥匙. 当我们真正进入到Lucene源代码之中的时候,我们会发现: Lucene的索引过程, ...

随机推荐

  1. MySQL数据库百万级高并发网站实战

    在一开始接触PHP接触MYSQL的时候就听不少人说:“MySQL就跑跑一天几十万IP的小站还可以,要是几百万IP就不行了”,原话不记得了,大体 就是这个意思.一直也没有好的机会去验证这个说法,一是从没 ...

  2. 使用Zen coding高效编写html代码

    zen-Coding是一款快速编写HTML,CSS(或其他格式化语言)代码的编辑器插件,这个插件可以用缩写方式完成大量重复的编码工作,是web前端从业者的利器. zen-Coding插件支持多种编辑器 ...

  3. Error initializing endpoint java.lang.Exception: Socket bind failed: [730048] ?????????×???(Э?é/???????/???)????í??

    2010-5-18 22:00:38 org.apache.catalina.core.AprLifecycleListener lifecycleEvent 信息: The Apache Tomca ...

  4. Python Twisted介绍

    原文链接:http://www.aosabook.org/en/twisted.html 作者:Jessica McKellar Twisted是用Python实现的基于事件驱动的网络引擎框架.Twi ...

  5. hdu 4607 Park Visit

    http://acm.hdu.edu.cn/showproblem.php?pid=4607 先求树的直径 方法:两遍bfs ,任选一点 a  求到a点最远的一点b ,然后 求到b点最远点 c 这样 ...

  6. NOIP2005 等价表达式 解题报告

    明明进了中学之后,学到了代数表达式.有一天,他碰到一个很麻烦的选择题.这个题目的题干中首先给出了一个代数表达式,然后列出了若干选项,每个选项也是一个代数表达式,题目的要求是判断选项中哪些代数表达式是和 ...

  7. Achieving High Availability and Scalability - ARR and NLB

    Achieving High Availability and Scalability: Microsoft Application Request Routing (ARR) for IIS 7.0 ...

  8. 字符集与字符编码 (charset & encoding)

    乱码是个大坑,相信每个人都遇过,而且是个绕不过去的坑.我理解每个程序员都应该写一篇编码相关的博文,梳理自己对这一块的理解,下面是我反复理解多次之后的学习小结. 1.从记事本的不同编码说起: 打开记事本 ...

  9. python下的复杂网络编程包networkx的安装及使用

    由于py3.x与工具包的兼容问题,这里采用py2.7 1.python下的复杂网络编程包networkx的使用: http://blog.sina.com.cn/s/blog_720448d30101 ...

  10. Win7 Print Spooler服務自动关闭

    对于Win7系统而言,该问题通常是安装了错误的打印驱动引起的,Win7系统为了保护其它进程不受干扰,自动关闭了打印服务. 解决方法就是: a> 把不用的打印机删掉. b> 确保你安装了正确 ...