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. apache 修改最大连接数

    1.在哪里设置? 服务器的为FreeBSD 6.2 ,apache 2.24,使用默认配置(FreeBSD 默认不加载自定义MPM配置),默认最大连接数是250 在/usr/local/etc/apa ...

  2. spring mvc读取url变量

    @RequestMapping(value="/{id}/{name}", method=RequestMethod.GET) public ModelAndView getUrl ...

  3. 百度上传android包:应用名解析失败!

    manifest 里面<application增加android:label="@string/app_name"

  4. HDU 4893 Wow! Such Sequence!(2014 Multi-University Training Contest 3)

    题意: 有三种操作: 1 x y: 表示给x位置加上y 2 x y:查询[x,y]的区间和 3 x y:将 [x,y] 区间上的数变为最接近的 Fibonacci. 思路: 1 操作按正常单调更新,区 ...

  5. java.io中流的操作:字节流、字符流

    java.io中流的操作:字节流.字符流(1)使用File类打开一个文件(2)通过字节流或字符流的子类指定输出的位置(3)进行读/写操作(4)关闭输入/输出 1.字节流:主要是byte类型数据,以by ...

  6. EF Code-First数据迁移的尝试

    Code-First的方式虽然省去了大量的sql代码,但增加了迁移的操作.尝试如下: 1.首先要在“扩展管理器”里搜索并安装NuGet“库程序包管理器”,否则所有命令都不能识别,会报CommandNo ...

  7. 【C语言学习】-01 C基础

    本文目录: 0.进制转换 1.C数据类型 2.常量变量 3.运算符 4.表达式 5.格式化输入输出 回到顶部 0.进制转换 在计算机中存储的数据,主要是以二进制形式存在,而我们生活中主要使用的有十进制 ...

  8. fragment 添加menu

    http://bbs.51cto.com/thread-1091458-1-1.html 有详解 @Override public void onCreate(Bundle savedInstance ...

  9. 学习MVC的一些随笔简单记录

    1 视图本身没有它所要显示的数据,视图的数据源始终是控制器 3 游戏的进行是模型的一部分,不是控制器的一部分 4 模型关于游戏是什么,在模型中封装游戏进行的逻辑,模型对用户界面一无所知,里面没有任何同 ...

  10. 修改Azure Website 移动服务 默认时区

    Azure Website 默认时区为国际标准时间,对中国用户来说不太方便友好,如何设置成北京时间呢? 打开Azure Website的“配置”页,找到“应用设置”节点. 在应用设置中添加设置项,密钥 ...