其实接下来就是贴一下代码,熟悉一下Lucene的正常工作流程,或者说怎么使用这个API,更深层次的东西这篇文章不会讲到。

  上一篇文章也说了maven的配置,只要你电脑联网就可以下载下来。我贴一下代码。

package com.muyi.lucene.mavenlucene.Ltest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; 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.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.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range; import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook; /**
* @author xinghl
*
*/
public class IndexManager2{
private static IndexManager indexManager;
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; /**
* 创建索引管理器
* @return 返回索引管理器对象
*/
public IndexManager getManager(){
if(indexManager == null){
this.indexManager = new IndexManager();
}
return indexManager;
}
/**
* 创建当前文件目录的索引
* @param path 当前文件目录
* @return 是否成功
*/
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);
System.out.println("文件名字:"+file.getPath()+"文件内容"+content); }else if("doc".equalsIgnoreCase(type)){ content += doc2String(file);
System.out.println("文件名字:"+file.getPath()+"文件内容"+content); }else if("xls".equalsIgnoreCase(type)){ content += xls2String(file);
System.out.println("文件名字:"+file.getPath()+"文件内容"+content); }
try{
analyzer = new StandardAnalyzer();
directory = FSDirectory.open(FileSystems.getDefault().getPath(INDEX_DIR)); File indexFile = new File(INDEX_DIR);
if (!indexFile.exists()) {
indexFile.mkdirs();
}
IndexWriterConfig config = new IndexWriterConfig(analyzer);
indexWriter = new IndexWriter(directory, config);
indexWriter.deleteAll();// 清除以前的index
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{
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);//构造一个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(FileSystems.getDefault().getPath("D:\\luceneIndex"));
analyzer = new StandardAnalyzer();
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher isearcher = new IndexSearcher(ireader); QueryParser parser = new QueryParser("content", analyzer);
Query query = parser.parse(text); TopDocs topDocs = isearcher.search(query, 1000);
System.out.println(topDocs.totalHits);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
System.out.println("--------------------查找结果-----------------------");
for (ScoreDoc scoreDoc : scoreDocs) { // 7、根据searcher和ScoreDoc对象获取具体的Document对象
Document document = isearcher.doc(scoreDoc.doc); // 8、根据Document对象获取需要的值 System.out.println(document.get("filename") + document.get("content") + " " + document.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;
}
public static void main(String[] args){
Date date1 = new Date();
File fileIndex = new File(INDEX_DIR);
if(deleteDir(fileIndex)){
fileIndex.mkdir();
}else{
fileIndex.mkdir();
} createIndex(DATA_DIR);
searchIndex("黑山洞");
Date date2 = new Date();
System.out.println("执行耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
}
}

其实就是这几部,建立阅读器--建立索引--查找索引--获得结果--输出结果。

大概就是这些流程。Lucene先到此为止。我突然想学一些其他东西。

Lucene 个人领悟 (三)的更多相关文章

  1. Lucene 个人领悟 (二)

    想了想,还是继续写吧,因为,太无聊了,媳妇儿也还有半个小时才下班. 前面拖拖拉拉用了三篇文章来做铺垫,这一篇开始正经搞了啊. 首先,我要加几个链接 http://www.cnblogs.com/xin ...

  2. Lucene 个人领悟 (一)

    在上学的时候就对搜索有着极大地兴趣,图书馆也借了好多的书看过,也用过Python写过爬虫. 有好多人在初步学习Lucene的时候都以为他是一个搜索引擎,或者搜索工具. 在此我要特别强调一下,Lucen ...

  3. Lucene基础(三)-- 中文分词及高亮显示

    Lucene分词器及高亮 分词器 在lucene中我们按照分词方式把文档进行索引,不同的分词器索引的效果不太一样,之前的例子使用的都是标准分词器,对于英文的效果很好,但是中文分词效果就不怎么样,他会按 ...

  4. Lucene学习之一:使用lucene为数据库表创建索引,并按关键字查询

    最近项目中要用到模糊查询,开始研究lucene,期间走了好多弯路,总算实现了一个简单的demo. 使用的lucene jar包是3.6版本. 一:建立数据库表,并加上测试数据.数据库表:UserInf ...

  5. Lucene 工作原理 之倒排索引

      1.简介 倒排索引源于实际应用中需要根据属性的值来查找记录.这种索引表中的每一项都包括一个属性值和具有该属性值的各记录的地址.由于不是由记录来确定属性值,而是由属性值来确定记录的位置,因而称为倒排 ...

  6. lucene.net 3.0.3、结合盘古分词进行搜索的小例子(转)

    lucene.net 3.0.3.结合盘古分词进行搜索的小例子(分页功能)   添加:2013-12-25 更新:2013-12-26 新增分页功能. 更新:2013-12-27 新增按分类查询功能, ...

  7. Lucene工作原理

    Lucene是一个高性能的java全文检索工具包,它使用的是倒排文件索引结构.该结构及相应的生成算法如下: 0)设有两篇文章1和2 文章1的内容为:Tom lives in Guangzhou,I l ...

  8. [转载] Lucene 工作原理

    转载自http://www.cnblogs.com/dewin/archive/2009/11/24/1609905.html Lucene是一个高性能的java全文检索工具包,它使用的是倒排文件索引 ...

  9. Lucene 4.4.0中常用的几个分词器

    一.WhitespaceAnalyzer 以空格作为切词标准,不对语汇单元进行其他规范化处理.很明显这个实用英文,单词之间用空格. 二.SimpleAnalyzer 以非字母符来分割文本信息,并将语汇 ...

随机推荐

  1. python-面向对象-06_私有属性和私有方法

    私有属性和私有方法 01. 应用场景及定义方式 应用场景 在实际开发中,对象 的 某些属性或方法 可能只希望 在对象的内部被使用,而 不希望在外部被访问到 私有属性 就是 对象 不希望公开的 属性 私 ...

  2. what's the 二叉树

    what's the 树 在了解二叉树之前,首先我们得有树的概念. 树是一种数据结构又可称为树状图,如文档的目录.HTML的文档树都是树结构,它是由n(n>=1)个有限节点组成一个具有层次关系的 ...

  3. Dockerfile语法解析

    Dockfile介绍 从上到下依次执行 每次执行一条指令就创建一个镜像层 第一条指令必须是FROM    表示需要构建的镜像是由哪个镜像为基础镜像   后续的指令运行于此基准镜像所提供的运行环境 可以 ...

  4. 006-Object.assign

    一.Object.assign简要使用 是ES6新添加的接口,主要的用途是用来合并多个JavaScript的对象. Object.assign()接口可以接收多个参数,第一个参数是目标对象,后面的都是 ...

  5. EscapeDataString URI 字符串太长

    /// <summary> /// 处理 无效的 URI: URI 字符串太长.问题 /// </summary> /// <param name="value ...

  6. vux 使用swiper 垂直滚动文字 报错[Intervention] Ignored...

    [Intervention] Ignored attempt to cancel a touchmove event with cancelable=false, for example becaus ...

  7. vue在页面嵌入别的页面或者是视频2

    vue在页面嵌入别的页面或者是视频 以下是嵌入页面 <iframe name="myiframe" id="myrame" src="http: ...

  8. boost生成json中的put操作

    ptree中的put操作后可以加<>,指定类型,不加<>采用默认的类型,感觉不加反而更好用.用法见下面例子. #include <iostream> #includ ...

  9. Python中__repr__和__str__区别(转)

    class Test(object): def __init__(self, value='hello, world!'): self.data = value >>> t = Te ...

  10. DL中train\dev\test集

    转自:https://blog.csdn.net/l8947943/article/details/80328721 training set:训练集是用来训练模型的.遵循训练集大,开发,测试集小的特 ...