一:官方文件

  http://lucene.apache.org/core/4_0_0/

  ps:网上参考文章:http://www.cnblogs.com/xing901022/p/3933675.html

二:jar包

(1)lucene-core-4.0.0.jar

(2)lucene-analyzers-common-4.0.0.jar

(3)lucene-analyzers-smartcn-4.0.0.jar

(4)lucene-queries-4.0.0.jar

(5)lucene-queryparser-4.0.0.jar

(6)jxl.jar

(7)spring相关jar包

(8)poi包

注:目前最新的lucene6.2需要jdk1.8,貌似是myeclipse8.5不兼容jdk1.8,导致出错,所以还是选用了jdk1.6+lucene4.0

三:例子

package demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.DirectoryReader;
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.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; /**
* @author xinghl
*
*/
@Controller
@RequestMapping("/luceneController")
public class luceneController{
private static String content=""; private static String INDEX_DIR = "D:\\luceneIndex";
private static String DATA_DIR = "D:\\luceneData";
private static Analyzer analyzer = null;
private static Directory directory = null;
private static IndexWriter indexWriter = null; * 创建当前文件目录的索引
* @param path 当前文件目录
* @return 是否成功
*/
@SuppressWarnings({ "deprecation" })
public static boolean createIndex(String path){
Date date1 = new Date();
List<File> fileList = getFileList(path);
for (File file : fileList) {
content = "";
//获取文件后缀
String type = file.getName().substring(file.getName().lastIndexOf(".")+1);
if("txt".equalsIgnoreCase(type)){ content += txt2String(file); }else if("doc".equalsIgnoreCase(type)){ content += doc2String(file); }else if("xls".equalsIgnoreCase(type)){ content += xls2String(file); } System.out.println("name :"+file.getName());
System.out.println("path :"+file.getPath());
System.out.println(); try{
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(new File(INDEX_DIR)); File indexFile = new File(INDEX_DIR);
if (!indexFile.exists()) {
indexFile.mkdirs();
}
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
indexWriter = new IndexWriter(directory, config); Document document = new Document();
document.add(new TextField("filename", file.getName(), Store.YES));
document.add(new TextField("content", content, Store.YES));
document.add(new TextField("path", file.getPath(), Store.YES));
indexWriter.addDocument(document);
indexWriter.commit();
closeWriter(); }catch(Exception e){
e.printStackTrace();
}
content = "";
}
Date date2 = new Date();
System.out.println("创建索引-----耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
return true;
} /**
* 读取txt文件的内容
* @param file 想要读取的文件对象
* @return 返回文件内容
*/
public static String txt2String(File file){
String result = "";
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
result = result + "\n" +s;
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result;
} /**
* 读取doc文件内容
* @param file 想要读取的文件对象
* @return 返回文件内容
*/
public static String doc2String(File file){
String result = "";
try{
FileInputStream fis = new FileInputStream(file);
HWPFDocument doc = new HWPFDocument(fis);
Range rang = doc.getRange();
result += rang.text();
fis.close();
}catch(Exception e){
e.printStackTrace();
}
return result;
} /**
* 读取xls文件内容
* @param file 想要读取的文件对象
* @return 返回文件内容
*/
public static String xls2String(File file){
String result = "";
try{
FileInputStream fis = new FileInputStream(file);
StringBuilder sb = new StringBuilder();
jxl.Workbook rwb = Workbook.getWorkbook(fis);
Sheet[] sheet = rwb.getSheets();
for (int i = 0; i < sheet.length; i++) {
Sheet rs = rwb.getSheet(i);
for (int j = 0; j < rs.getRows(); j++) {
Cell[] cells = rs.getRow(j);
for(int k=0;k<cells.length;k++)
sb.append(cells[k].getContents());
}
}
fis.close();
result += sb.toString();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
/**
* 查找索引,返回符合条件的文件
* @param text 查找的字符串
* @return 符合条件的文件List
*/
public static void searchIndex(String text){
Date date1 = new Date();
try{
directory = FSDirectory.open(new File(INDEX_DIR));
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
DirectoryReader ireader = DirectoryReader.open(directory); //DATA_DIR目录下为空时,这里会报异常并被捕获
IndexSearcher isearcher = new IndexSearcher(ireader); QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "content", analyzer);
Query query = parser.parse(text); ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs; for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
System.out.println("____________________________");
System.out.println(hitDoc.get("filename"));
System.out.println(hitDoc.get("content"));
System.out.println(hitDoc.get("path"));
System.out.println("____________________________");
}
ireader.close();
directory.close();
}catch(Exception e){
e.printStackTrace();
}
Date date2 = new Date();
System.out.println("查看索引-----耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
}
/**
* 过滤目录下的文件
* @param dirPath 想要获取文件的目录
* @return 返回文件list
*/
public static List<File> getFileList(String dirPath) {
File[] files = new File(dirPath).listFiles();
List<File> fileList = new ArrayList<File>();
for (File file : files) {
if (isTxtFile(file.getName())) {
fileList.add(file);
}
}
return fileList;
}
/**
* 判断是否为目标文件,目前支持txt xls doc格式
* @param fileName 文件名称
* @return 如果是文件类型满足过滤条件,返回true;否则返回false
*/
public static boolean isTxtFile(String fileName) {
if (fileName.lastIndexOf(".txt") > 0) {
return true;
}else if (fileName.lastIndexOf(".xls") > 0) {
return true;
}else if (fileName.lastIndexOf(".doc") > 0) {
return true;
}
return false;
} public static void closeWriter() throws Exception {
if (indexWriter != null) {
indexWriter.close();
}
}
/**
* 删除文件目录下的所有文件
* @param file 要删除的文件目录
* @return 如果成功,返回true.
*/
public static boolean deleteDir(File file){
if(file.isDirectory()){
File[] files = file.listFiles();
for(int i=0; i<files.length; i++){
deleteDir(files[i]);
}
}
file.delete();
return true;
} @RequestMapping(params="test")
@ResponseBody
public String main(String value){ //value为前端传过来的要查询的字符串
File fileIndex = new File(INDEX_DIR);
if(deleteDir(fileIndex)){
fileIndex.mkdir();
}else{
fileIndex.mkdir();
} createIndex(DATA_DIR);
searchIndex(value);
return "success";
}
}

四:前端

<body>
<form id="testform" method="post" action="luceneController.do?test">
<button id="one">点我开始测试</button>
<input type="text" name="value"/>
</form>
</body>
<script type="text/javascript">
   $("#one").live("click",function(){
   $("#testform").submit();
   });
</script>

lucene 4.0学习的更多相关文章

  1. Lucene.net(4.8.0) 学习问题记录五: JIEba分词和Lucene的结合,以及对分词器的思考

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

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

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

  3. solr6.0学习

    solr6.0学习(一)环境搭建准备工作:目前最新版本6.0.下载solr 6.0:Solr6.0下载JDK8 下载jdk1.8:jdk1.8[solr6.0是基于jdk8开发的]tomcat8.0 ...

  4. Lucene.net入门学习

    Lucene.net入门学习(结合盘古分词)   Lucene简介 Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,即它不是一个完整的全 ...

  5. 关于Lucene 3.0升级到Lucene 4.x 备忘

    最近,需要对项目进行lucene版本升级.而原来项目时基于lucene 3.0的,很古老的一个版本的了.在老版本中中,我们主要用了几个lucene的东西: 1.查询lucene多目录索引. 2.构建R ...

  6. Servlet3.0学习总结——基于Servlet3.0的文件上传

    Servlet3.0学习总结(三)——基于Servlet3.0的文件上传 在Servlet2.5中,我们要实现文件上传功能时,一般都需要借助第三方开源组件,例如Apache的commons-fileu ...

  7. DirectX 总结和DirectX 9.0 学习笔记

    转自:http://www.cnblogs.com/graphics/archive/2009/11/25/1583682.html DirectX 总结 DDS DirectXDraw Surfac ...

  8. [EntLib]微软企业库5.0 学习之路——第一步、基本入门

    话说在大学的时候帮老师做项目的时候就已经接触过企业库了但是当初一直没明白为什么要用这个,只觉得好麻烦啊,竟然有那么多的乱七八糟的配置(原来我不知道有配置工具可以进行配置,请原谅我的小白). 直到去年在 ...

  9. Bootstrap3.0学习14

    Bootstrap3.0学习第十四轮(分页.徽章)   前言 阅读之前您也可以到Bootstrap3.0入门学习系列导航中进行查看http://www.cnblogs.com/aehyok/p/340 ...

随机推荐

  1. appDelegate中的委托协议方法以及使用观察者模式获取其触发方法

    //当应用程序将要进入非活动状态执行,在此期间,应用程序不接受消息或事件,比如来电 - (void)applicationWillResignActive:(UIApplication *)appli ...

  2. Linux下用dump实现备份和还原 ux下用dump实现备份和还原

    对于系统而言,我们可以有很多种办法去备份(还原)系统或文件,之所以要去做备份,就是为了在系统或文件遭到损害时,能及时恢复,把损失减小到最小.当然,对于企业服务器而言,备份的重要性是举足轻重.咱们今天就 ...

  3. WordPress搭建Personal Blog

    早就想搭建一个专属于自己的博客了,用来记录自己生活.学习的点点滴滴.之所以选WordPress,主要是因为它可以支持Latex,而且特别喜欢其简约的风格. WordPress有个the famous ...

  4. Github 上的 iOS 开源项目

    在 Github 上 Star 太多了,有时候很难找到自己想要的开源库,所以在此记录下来.便于自己开发使用,也顺便分享给大家. 动画 awesome-ios-animation收集了iOS平台下比较主 ...

  5. 设置su和sudo为不需要密码

    设置su和sudo为不需要密码 一 设置sudo为不需要密码   有时候我们只需要执行一条root权限的命令也要su到root,是不是有些不方便?这时可以用sudo代替.默认新建的用户不在sudo组, ...

  6. jemalloc源码结构分析(二):CPU字节对齐算法

    在调用arena_malloc_small过程中,要根据申请内存大小,进行对齐计算,然后分配一个整块儿.算法如下: 1)定义一个SIZE_CLASSES宏,它主要用于生成后面两个表,small_siz ...

  7. Python基础【第十一篇】文件操作(file()、open()方法和fileinput模块)

    一.file/open 内置函数 file函数的方法: 注:file 和 open的用法和功能相同这里只对file进行分析 file(‘filename’,’mode’) file(‘filename ...

  8. innodb对update的处理

    当更新非聚集索引上记录 和 聚集索引上的主键时,是标记删除,然后插入新的记录 当更新聚集索引上的非主键列时,是updated-in-place,也就是说原地修改,不会插入新记录. 之前一直以为都是以标 ...

  9. 关于XML文档的讲解

    1        XML的概述 1.1 什么是XML XML全称为Extensible Markup Language,意思是可扩展的标记语言.XML语法上和HTML比较相似,但HTML中的元素是固定 ...

  10. Redis集群

    一.Redis集群原理 集群技术是构建高性能网站架构的重要手段,试想在网站承受高并发访问压力的同时,还需要从海量数据中查询出满足条件的数据,并快速响应,我们必然想到的是将数据进行切片,把数据根据某种规 ...