本文转自:http://blog.csdn.net/jyf211314/article/details/17503997           点击打开链接

lucene4.6小例子,Lucene全文检索步骤大体上有两方面:索引过程和搜索过程,具体如下:

1.索引过程

<1>创建IndexWriter
,它的作用是用来写索引文件,

可以将IndexWriter看做是一个特定类型的数据库,用来存放各种表,可以将Document看做是一张张的表。

IndexWriter iw=new IndexWriter(Directory dire, IndexWriterConfig iwc);

可见,该方法有两个参数,第一个参数为索引存放位置,参数类型为Directory,第二个参数为 IndexWriter的配置类,

@1.Directory dire=FSDirectory.open(new File(D:\\lucenefiles));

通过Directory的创建指定索引存放位置(D:\lucenefiles文件夹)

@2.Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_46);

通过Analyzer 的创建指定索引语言词汇的分析器。当前版本Lucene-core-4.6.0

@3.IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_46, analyzer);

iwc.setOpenMode(OpenMode.CREATE); //CREATE:清空重建(推荐);

IndexWriter indexWriter=new IndexWriter(dire, iwc);

通过IndexWriterConfig的创建指定索引版本和语言词汇分析器

<2>创建Document,代表要索引的文档

可以将Document看做是数据库中的一张张的表,而每个field都是表中的一个colum用来存放各种类型的信息,如标题、作者、时间等等

@1.File fileDir= new File("D:\\lucenefiles");
File[] files = fileDir.listFiles();

读取文件

@2.Document doc=new Document();

通过创建Document指定要索引的文档

@3.doc.add(new TextField("name", String name=files[i].getName(), Store.YES));

doc.add(new TextField("content", getFileContent(files[i]), Store.YES));

向Document文档中添加Field信息,不同类型的信息用不同类型的Field来表示;

getFileContent(File file)用于读取文件内容。

<3>将Document添加到IndexWriter中并且提交

表(Document)创建好之后,当然要添加到数据库(IndexWriter)中,同时commit

@1.indexWriter.addDocument(doc); 通过该方法添加

indexWriter.commit();

2.搜索过程

<!>首先指定搜索目录

Directory dire=FSDirectory.open(new File("D:\\luceneindex"));

<2>创建语言词汇解析器,前后版本要一致

Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_46);

<3>创建IndexReader将搜索目录读取到内存,

IndexReader ireader=DirectoryReader.open(dire);

<4>创建IndexSearcher准备搜索

IndexSearcher isearcher=new IndexSearcher(ireader);

<5>创建QueryParser对查询语句进行语法分析,确定搜索的内容

QueryParser parser = new QueryParser(Version.LUCENE_46, "path", analyzer);

<6>创建Query生成查询语法树,

QueryParser parser = new QueryParser(Version.LUCENE_46, "content", analyzer);

通过调用QueryParser 的parse("");方法来生成Query以及查询语法树

Query query = parser.parse("程序员");

<7>获取搜索结果

TopDocs td=is.search(query, 1000);ScoreDoc[] sds =td.scoreDocs;

<8>对搜索结果遍历操作

3.以下是个人测试例子

public class Constants {
public final static String INDEX_FILE_PATH = "F:\\lucene\\test";
//索引的文件的存放路径 测试时可以在本目录下自行建一些文档,内容自行编辑即可
public final static String INDEX_STORE_PATH = "F:\\lucene\\index";
//索引的存放位置
}
package com.lucene.jl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader; 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.Store;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
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.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version; public class LuceneIndex { /**
* 创建索引
* @param analyzer
* @throws Exception
*/
public static void createIndex(Analyzer analyzer) throws Exception{
Directory dire=FSDirectory.open(new File(Constants.INDEX_STORE_PATH));
IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_46, analyzer);
IndexWriter iw=new IndexWriter(dire, iwc);
LuceneIndex.addDoc(iw);
iw.close();
} /**
* 动态添加Document
* @param iw
* @throws Exception
*/
public static void addDoc(IndexWriter iw) throws Exception{
File[] files=new File(Constants.INDEX_FILE_PATH).listFiles();
for (File file : files) {
Document doc=new Document();
String content=LuceneIndex.getContent(file);
String name=file.getName();
String path=file.getAbsolutePath();
doc.add(new TextField("content", content, Store.YES));
doc.add(new TextField("name", name, Store.YES));
doc.add(new TextField("path", path,Store.YES));
System.out.println(name+"==="+content+"==="+path);
iw.addDocument(doc);
iw.commit();
}
} /**
* 获取文本内容
* @param file
* @return
* @throws Exception
*/
@SuppressWarnings("resource")
public static String getContent(File file) throws Exception{
FileInputStream fis=new FileInputStream(file);
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader br=new BufferedReader(isr);
StringBuffer sb=new StringBuffer();
String line=br.readLine();
while(line!=null){
sb.append(line+"\n");
line=null;
}
return sb.toString();
} /**
* 搜索
* @param query
* @throws Exception
*/
private static void search(Query query) throws Exception {
Directory dire=FSDirectory.open(new File(Constants.INDEX_STORE_PATH));
IndexReader ir=DirectoryReader.open(dire);
IndexSearcher is=new IndexSearcher(ir);
TopDocs td=is.search(query, 1000);
System.out.println("共为您查找到"+td.totalHits+"条结果");
ScoreDoc[] sds =td.scoreDocs;
for (ScoreDoc sd : sds) {
Document d = is.doc(sd.doc);
System.out.println(d.get("path") + ":["+d.get("path")+"]");
}
} public static void main(String[] args) throws Exception, Exception {
Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_46);
LuceneIndex.createIndex(analyzer);
QueryParser parser = new QueryParser(Version.LUCENE_46, "content", analyzer);
Query query = parser.parse("人");
LuceneIndex.search(query);
}
}

4.磁盘文件检索如上述,对于数据库的检索页应该是差不多,应该也是先从数据库查出数据,然后对查出的数据做索引然后搜索,大致一样吧

lucene4.6 索引创建和搜索例子的更多相关文章

  1. Lucene7.1.0版本的索引创建与查询以及维护,包括新版本的一些新特性探索!

    一 吐槽 lucene版本更新实在太快了,往往旧版本都还没学会,新的就出来,而且每个版本改动都特别大,尤其是4.7,6,6,7.1.......ε=(´ο`*)))唉,但不可否认,新版本确实要比旧版本 ...

  2. lucene4入门(2)搜索

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

  3. 关于lucene的IndexSearcher单实例,对于索引的实时搜索

    Lucene版本:3.0 一般情况下,lucene的IndexSearcher都要写成单实例,因为每次创建IndexSearcher对象的时候,它都需要把索引文件加载进来,如果访问量比较大,而索引也比 ...

  4. mysql 优化实例之索引创建

    mysql 优化实例之索引创建 优化前: pt-query-degist分析结果: # Query 23: 0.00 QPS, 0.00x concurrency, ID 0x78761E301CC7 ...

  5. MongoDB索引创建(5)

    索引创建 1:索引提高查询速度,降低写入速度,权衡常用的查询字段,不必在太多列上建索引 2. 在mongodb中,索引可以按字段升序/降序来创建,便于排序 3. 默认是用btree来组织索引文件,2. ...

  6. 数据结构二叉树的java实现,包括二叉树的创建、搜索、删除和遍历

    根据自己的学习体会并参考了一些网上的资料,以java写出了二叉树的创建.搜索.删除和遍历等操作,尚未实现的功能有:根据先序和中序遍历,得到后序遍历以及根据后序和中序遍历,得到先序遍历,以及获取栈的深度 ...

  7. 索引-mysql索引创建、查看、删除及使用示例

    mysql索引创建.查看.删除及使用示例 1.创建索引: ALTER TABLE用来创建普通索引.UNIQUE索引或PRIMARY KEY索引. ALTER TABLE table_name ADD ...

  8. solr索引创建流程

    solr索引创建流程: 分词组件Tokenizer 分词组件(Tokenizer)会做以下几件事情(这个过程称为:Tokenize),处理得到的结果是词汇单元(Token). 1.将文档分成一个一个单 ...

  9. ArcEngine创建IElement简单例子

    转自IT-GIS终结者原文ArcEngine创建IElement简单例子 代码下载地址:http://files.cnblogs.com/ogis/MapControlApplication2.rar ...

随机推荐

  1. jquery 让指定导航隐藏

    $(function(){ var aLink=$('.nav-content .nav li a'); // 选中所有a var aText=['星网服务','在线搭配','星网学院','推客联盟' ...

  2. C语言自动类型转换

    自动转换遵循以下规则: 1) 若参与运算量的类型不同,则先转换成同一类型,然后进行运算. 2) 转换按数据长度增加的方向进行,以保证精度不降低.(eg:int型和long型运算时,先把int量转成lo ...

  3. arcpagelistarclist列表分页

    arcpagelistarclist列表分页 (DedeCMS 5.6) 名称:arcpagelist 功能:通过制定arclist的pagesize及tagid属性,配合arcpagelist标签进 ...

  4. linux cat /proc/cpuinfo

    #cat /proc/cpuinfo processor : 0 #逻辑处理器的唯一标识符 vendor_id : AuthenticAMD #CPU厂商ID信息,如果处理器为英特尔处理器,则vend ...

  5. (转)反射发送实战(-)InvokeMember

    反射是.net中的高级功能之一,利用反射可以实现许多以前看来匪夷所思的功能,下面是我看了<Programming C#>(O'Reilly)之后对于反射的一点实践,本想直接做个应用程序来说 ...

  6. Hadoop shuffle与排序

    Mapreduce为了确保每个reducer的输入都按键排序.系统执行排序的过程-----将map的输出作为输入传给reducer 称为shuffle.学习shuffle是如何工作的有助于我们理解ma ...

  7. MVC---404页面配置

    参考地址1:http://benfoster.io/blog/aspnet-mvc-custom-error-pages 参考地址2:https://msdn.microsoft.com/en-us/ ...

  8. javascript返回顶部几种代码总结

    纯js代码 /** * 回到页面顶部 * @param acceleration 加速度 * @param time 时间间隔 (毫秒) **/ function goTop(acceleration ...

  9. uva12489 Combating cancer(树同构)

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud https://uva.onlinejudge.org/index.php?opt ...

  10. 关于在transform下的子元素设置fixed无效的困惑

    最近的项目是要实现一个点击显示隐藏边栏的效果,而且需要边栏随着滚动而滚动. 思路简单,不就一个css的动画和一个position为fixed,搞定!但不想,设为fixed的子元素竟然无法fixed,这 ...