这里面用的是比较新的Lucene4.10.2 做的一个实例。(lucene的索引不能太大,要不然效率会很低。大于1G的时候就必须考虑分布索引的问题)

先介绍一下Lucene的几个参数意义:

IndexWriter:lucene中最重要的的类之一,它主要是用来将文档加入索引,同时控制索引过程中的一些参数使用。

Analyzer:分析器,主要用于分析搜索引擎遇到的各种文本。常用的有StandardAnalyzer分析器,StopAnalyzer分析器,WhitespaceAnalyzer分析器等。

Directory:索引存放的位置;lucene提供了两种索引存放的位置,一种是磁盘,一种是内存。一般情况将索引放在磁盘上;相应地lucene提供了FSDirectory和RAMDirectory两个类。

Document:文档;Document相当于一个要进行索引的单元,任何可以想要被索引的文件都必须转化为Document对象才能进行索引。

Field:字段。

IndexSearcher:是lucene中最基本的检索工具,所有的检索都会用到IndexSearcher工具;

Query:查询,lucene中支持模糊查询,语义查询,短语查询,组合查询等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些类。

QueryParser: 是一个解析用户输入的工具,可以通过扫描用户输入的字符串,生成Query对象。

话说Lucene就两个重要步骤,一个是创建索引,一个是查询索引,首先看下如何创建索引的代码。

import util.IOUtil;
/**
* @author ${朱良兴}
*2015-1-26
*/
public class CreateIndexer { public void createIndex() throws Exception{ IOUtil utils= new IOUtil();
// 一、创建索引
// 内存索引模板
Directory dir = new RAMDirectory();
Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_2,
analyzer);
IndexWriter indexWriter = new IndexWriter(dir, config);
//文件位置。
File fileDir = new File( "E:\\ftp" );
String path = "E:\\ftp";
long startTime = new Date().getTime();
String id;
//获取所有的文件名。
List <String> fileList = utils.getFileName(path);
for(int i=0; i<fileList.size();i++){
String content = utils.getFileContent(new File(fileList.get(i)), "GBK");
id ="id"+i;
indexPost(id, content);
} // 测试一下索引的时间
long endTime = new Date().getTime();
System.out .println( " 这花费了 " + (endTime - startTime) + " 毫秒来把文档增加到索引里面去! " + fileDir.getPath());
indexWriter.close(); }
@SuppressWarnings("deprecation")
private static void indexPost(String id,String content){
/* 这里放索引文件的位置 */
File indexDir = new File("E:\\index");
Analyzer analyzer = new IKAnalyzer();
TextField postIdField = new TextField("id", id, Store.YES); // 不要用StringField
TextField postContentField = new TextField("content", content, Store.YES); Document doc = new Document();
doc.add(postIdField);
doc.add(postContentField);
IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_4_10_2, analyzer);
iwConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
try {
Directory fsDirectory = FSDirectory.open(indexDir);
IndexWriter indexWriter = new IndexWriter(fsDirectory, iwConfig);
indexWriter.addDocument(doc);
indexWriter.close();
} catch (Exception e) {
e.printStackTrace();
} }

第二就是查询:

/**
* 查询索引
* @author ${朱良兴}
*2015-1-26
*/
public class DoSearch {
public static void main(String[] args) throws Exception {
//创建索引
CreateIndexer createIndexer = new CreateIndexer();
createIndexer.createIndex();
Analyzer analyzer = new IKAnalyzer();
File indexDir = new File("E:\\index");
try {
Directory fsDirectory = FSDirectory.open(indexDir);
DirectoryReader ireader = DirectoryReader.open(fsDirectory);
IndexSearcher isearcher = new IndexSearcher(ireader);
QueryParser qp = new QueryParser("content", analyzer); //使用QueryParser查询分析器构造Query对象
qp.setDefaultOperator(QueryParser.AND_OPERATOR);
Query query = qp.parse("么么哒"); // 搜索Lucene
long beginTime = new Date().getTime();
TopDocs topDocs = isearcher.search(query , 100); //搜索相似度最高的100条记录
long endTime = new Date().getTime();
System.out.println("命中:" + topDocs.totalHits);
System.out.println("搜索花费的时间:"+(endTime-beginTime)+"毫秒");
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (int i = 0; i < topDocs.totalHits; i++){
Document targetDoc = isearcher.doc(scoreDocs[i].doc);
System.out.println("内容:" + targetDoc.toString());
} } catch (Exception e) { }
}
}

用到的工具类代码:

package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List; /**
* IO 工具类。
* @author ${朱良兴}
*2015-1-26
*/
public class IOUtil{ List<String> fileList = new ArrayList<String>();
/**
* 根据文件的全路径获得所有的文件内容
* @param fileName
* @param charset
* @return
* @throws Exception
*/
public String getFileContent(File fileName, String charset) throws Exception{
BufferedReader reader = new BufferedReader( new InputStreamReader(
new FileInputStream(fileName), charset));
String line = new String();
String temp = new String();
while ((line = reader.readLine()) != null ) {
temp += line;
}
reader.close();
return temp;
}
/**
* 获取所有的文件名
* @param path
* @return
* @throws Exception
*/
public List<String> getFileName(String path) throws Exception{ String filenName ="";
//文件位置。
File fileDir = new File(path);
File[] textFiles = fileDir.listFiles();
if (textFiles!=null){ // 增加document到索引去
for ( int i = 0 ; i < textFiles.length; i ++ ) {
if (textFiles[i].isFile()) {
System.out.println( " File " + textFiles[i].getCanonicalPath()
+ " 正在被索引. " );
filenName=textFiles[i].getCanonicalPath();
fileList.add(filenName); }else{ getFileName(textFiles[i].getCanonicalPath());
}
}
}
return fileList; }
}

这里是和IK Analyzer  结合使用的简单示例

Lucene 4.10.2开发示例的更多相关文章

  1. DevExpress .NET界面开发示例大全

    说到做.net界面开发,很多人应该都会想到DevExpress. 它的 .net界面开发系列一共有7个版本:WinForms.ASP.NET.MVC.WPF.Silverlight.Windows 8 ...

  2. Padrino 博客开发示例

    英文版出处:http://www.padrinorb.com/guides/blog-tutorial 楼主按 拿作者自己的话说:Padrino(谐音:派骓诺)是一款基于Sinatra的优雅的Web应 ...

  3. SharePoint 2013 APP 开发示例 (二)获取用户信息

    SharePoint 2013 APP 开发示例 (二)获取用户信息 这个示例里,我们将演示如何获取用户信息: 1. 打开 Visual Studio 2012. 2. 创建一个新的  SharePo ...

  4. SharePoint 2013 APP 开发示例 (六)服务端跨域访问 Web Service (REST API)

    上个示例(SharePoint 2013 APP 开发示例 (五)跨域访问 Web Service (REST API))是基于JavaScript,运行在web browser内去访问REST AP ...

  5. SharePoint 2013 APP 开发示例 (五)跨域访问 Web Service (REST API)

          虽然 JQuery 也能通过授权header实现跨域, 但SharePoint 提供了更简单的方法,它被实现在SP.RequestExecutor里 .它能访问跨域的服务包括REST AP ...

  6. SharePoint 2013 APP 开发示例 (四)JQuery访问REST

    这个示例里,我们将用JQuery AJAX去发送一个 REST请求,并查看返回结果.为了让我们更好地理解REST 接口,我们将添加一个输入框让用户可以指定REST的URL, 这将让我们尝试着用构造的U ...

  7. SharePoint 2013 APP 开发示例 (三)使用远程的web资源

    在这个示例里我们将详细介绍 TokenHelper 类, 我们将看到它是怎么简单地从远程web站点访问SharePoint的.我们还将取到它的一些值.这将帮助我们理解连接是怎么被构造的,同时也方便我们 ...

  8. Fedora 10编程开发工具

    1请问Fedora 10编程开发工具有什么 编辑器就用vim,编译用gcc,当然个人爱好随意 IDE的话推荐eclipse,如果做C/C++的,用codeblocks也是个不错的选择 输入gcc -v ...

  9. 多线程间通信之AutoResetEvent和ManualResetEvent的原理分析和开发示例

    AutoResetEvent 允许线程通过发信号互相通信. 通常,当线程需要独占访问资源时使用该类. 线程通过调用 AutoResetEvent 上的 WaitOne 来等待信号. 如果 AutoRe ...

随机推荐

  1. [转]mysql 导入导出数据库以及函数、存储过程的介绍

    本篇文章是对mysql中的导入导出数据库命令以及函数.存储过程进行了详细的分析介绍,需要的朋友参考下: mysql常用导出数据命令:1.mysql导出整个数据库  mysqldump -hhostna ...

  2. javascript基础学习(六)

    javascript之对象 学习要点: 对象的属性和方法 对象的原型 一.对象 对象其实就是一种引用类型,而对象的值就是引用对象的实例. 二.创建对象 在javascript中有两种对象,一种是系统内 ...

  3. 知识备忘phpcms 简单解析一 数据表字段

    PHPCMS V9帮助中心 数据结构 phpcms v9 数据... phpcms v9 数据... PHPSSO 数据库结... phpcms v9 数据表结构 在线版 PHPCMS V9 数据结构 ...

  4. Asp.Net MVC5 格式化输出时间日期

    刚好用到这个,网上找的全部是输出文本框内容的格式化日期时间 而我需要只是在一个表格中的单元个中输出单纯的文字 最后在MSDN上找到 HtmlHelper.FormatValue 方法 public s ...

  5. fragment 学习

    fragment需要id是必须属性 <fragment        android:id="@+id/frg1"        android:name="com ...

  6. SOA和微服务

    SOA和微服务 SOA和微服务到底是什么关系? 说实话,我确实不明白SOA和微服务到底有什么本质上的区别,两者说到底都是对外提供接口的一种架构设计方式.我倒觉得微服务其实就是随着互联网的发展,复杂的平 ...

  7. 转:如何找出发生SEGV内存错误的程序

    原文来自于:http://www.searchtb.com/2014/03/%E5%A6%82%E4%BD%95%E6%89%BE%E5%87%BA%E5%8F%91%E7%94%9Fsegv%E5% ...

  8. win32控制台实现按任意键退出的功能

    win7之后的五win32 控制台出现了程序运行完之后就立即结束的问题,程序员根本无法看输出的结果.未来让控制台运行完之后能够等待程序员的操作.可以使用: system("PAUSE&quo ...

  9. Dao 处理

    1. 写一个基础的接口和类来做基本的操作 /** * */ package com.wolfgang.dao; import java.util.List; /** * @author Adminis ...

  10. 【技术贴】7-zip 7z关联右键菜单后右键不弹出菜单的解决办法

    解决7z,7zip右键菜单 失效 右键菜单 无法弹出右键菜单 不正常 右键菜单 sb等各种疑难杂症. 1.首先先去7z的选项里面把右键关联给设置了. 用的好好的7z,正吃着火锅唱着歌忽然发现右键单文件 ...