2016-12-15 项目中需要加载下面几个工具包



 1 package com.cn.shupu.util;

 import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
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.index.LogByteSizeMergePolicy;
import org.apache.lucene.index.LogMergePolicy;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
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.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory; public class LuneceTest { // 用来文件
public static List<File> files = new ArrayList<File>(); // 保存索引文件
public static List<File> saveFile(File sourceFile) { File[] fs = sourceFile.listFiles(); for (int i = 0; i < fs.length; i++) { if (fs[i].isFile()) { files.add(fs[i]);
} else { saveFile(fs[i]);
} } return files; } // 获取文件中的内容
public static String saveContent(File file) { String content = ""; try { // 创建一个字符输入流
FileInputStream fis = new FileInputStream(file); // 创建一个桥梁让字节流转化为字符流
InputStreamReader isr = new InputStreamReader(fis, "GBK");
// 创建一个字符流缓存区
BufferedReader br = new BufferedReader(isr); String s = null; while ((s = br.readLine()) != null) { // 把内容拼接起来
content = content + "\n" + s; } // 关闭流
br.close();
isr.close();
fis.close(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return content; } // 创建索引
public static void createIndex(String sourcePath, String indexPath) { // 要索引的文件路径
File sourceFile = new File(sourcePath); // 获取索引文件的文件
List<File> fs = saveFile(sourceFile); Date date1 = new Date(); // 对文件进行索引
// 索引文件存放路径
Directory dir; try { // 索引优化
RAMDirectory rd = new RAMDirectory();
// 这里的路径为保存索引的路径
dir = FSDirectory.open(Paths.get(indexPath));
// 创建一个分词器
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);// 初始化索引器
// 创建索引器
// IndexWriter writer = new IndexWriter(dir, iwc);//
// 第一个参数为索引存放的位置,第二参数为初始化参数 IndexWriter writer = new IndexWriter(rd, iwc); IndexWriterConfig iwc2 = new IndexWriterConfig(analyzer);// 初始化索引器
iwc2.setOpenMode(OpenMode.CREATE_OR_APPEND);
iwc2.setMaxBufferedDocs(256);
iwc2.setRAMBufferSizeMB(100); // SetMergeFactor是控制segment合并频率的,其决定了一个索引块中包括多少个文档,当硬盘上的索引块达到多少时,
// 将它们合并成一个较大的索引块。当MergeFactor值较大时,生成索引的速度较快。MergeFactor的默认值是10,建议在建立索引前将其设置的大一些。
LogMergePolicy mergePolicy = new LogByteSizeMergePolicy();
mergePolicy.setMergeFactor(100);
iwc2.setMergePolicy(mergePolicy); // 把缓存在 RAMDirectory 中的所有数据写入 FSDirectory
IndexWriter is = new IndexWriter(dir, iwc2); for (int i = 0; i < fs.size(); i++) { String content = ""; // 只对.txt文件进行索引
// 获取文件类型
int a = fs.get(i).getName().lastIndexOf("."); String fileType = fs.get(i).getName().substring(a + 1); if ("txt".equals(fileType)) { content = saveContent(fs.get(i)); // System.out.println(content); // System.out.println(fs.get(i).getName());
Document doc = new Document(); // doc.add(new TextField("filename", fs.get(i).getName(),
// Store.YES));
doc.add(new TextField("path", fs.get(i).getAbsolutePath(), Store.YES));
doc.add(new TextField("content", content, Store.YES));
writer.addDocument(doc); } }
writer.commit();
writer.close();
//
is.addIndexes(new Directory[] { rd });
is.forceMerge(5);
is.forceMerge(100);
is.maybeMerge();
is.close(); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} Date date2 = new Date();
System.out.println("创建索引-----耗时:" + (date2.getTime() - date1.getTime()) + "ms\n"); } // 搜索文件
public static void search(String indexPath, String keyword) { Date date1 = new Date(); Directory dir; try { dir = FSDirectory.open(Paths.get(indexPath)); // 创建分词器
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
// 打开索引的存放位置
DirectoryReader dr = DirectoryReader.open(dir); // 创建检索器
IndexSearcher is = new IndexSearcher(dr); QueryParser parser = new QueryParser("content", analyzer);// 第一个参数为要搜索的字段名,第二额分词器 Query query = parser.parse(keyword); TopDocs results = is.search(query, 100); ScoreDoc[] hits = results.scoreDocs;// 检索得到结果集 for (int i = 0; i < hits.length; i++) { // 获取一个条记录
Document doc = is.doc(hits[i].doc); // 获取路径
String path = doc.get("path");
// 获取 内容
String content = doc.get("content");
String filename = doc.get("filename"); String s = hight(query, analyzer, "content", content, 200); System.out.println("____________________________"); // System.out.println("文件名--------" + filename);
//
// sSystem.out.println("内容:---------" + s); System.out.println("文件路径-----" + path); System.out.println("____________________________"); } dr.close();
dir.close(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} Date date2 = new Date();
System.out.println("查看索引-----耗时:" + (date2.getTime() - date1.getTime()) + "ms\n"); } /**
* 获取高亮显示结果的html代码
*
* @param query
* 查询
* @param analyzer
* 分词器
* @param fieldName
* 域名
* @param fieldContent
* 域内容
* @param fragmentSize
* 结果的长度(不含html标签长度)
* @return 结果(一段html代码)
* @throws IOException
* @throws InvalidTokenOffsetsException
*/
public static String hight(Query query, Analyzer analyzer, String filedname, String filedContent, int fragmentSize)
throws IOException, InvalidTokenOffsetsException { // 创建一个高亮器
Highlighter hightlighter = new Highlighter(new SimpleHTMLFormatter("<font color='red'>", "</font>"),
new QueryScorer(query)); // 查询结果的内容长度设定
Fragmenter framenter = new SimpleFragmenter(fragmentSize); hightlighter.setTextFragmenter(framenter); return hightlighter.getBestFragment(analyzer, filedname, filedContent);
} public static void main(String[] args) { createIndex("D:\\图书文件", "c:\\expal"); search("c:\\expal", "炎");// 22385ms 10380ms 35221ms 96583ms 66798ms
// 169438ms 179478ms }

lunece全文检索的入门与简单优化的更多相关文章

  1. Elasticsearch全文检索工具入门

    Elasticsearch全文检索工具入门: 1.下载对应系统版本的文件 elasticsearch-2.4.0.zip 1.1运行elasticsearch-2.4.0\elasticsearch- ...

  2. 2,turicreate入门 - 一个简单的回归模型

    turicreate入门系列文章目录 1,turicreate入门 - jupyter & turicreate安装 2,turicreate入门 - 一个简单的回归模型 3,turicrea ...

  3. 踢爆IT劣书出版黑幕——由清华大学出版社之《C语言入门很简单》想到的(1)

    1.前言与作者 首先声明,我是由于非常偶然的机会获得<C语言入门很简单>这本书的,绝对不是买的.买这种书实在丢不起那人. 去年这书刚出版时,在CU论坛举行试读推广,我当时随口说了几句(没说 ...

  4. 一次千万级别的SQL查询简单优化体验

    背景:从两张有关联的表查询数据,A表数据量1400万,B表数据量8000万.A与B通过ID逻辑关联,没有实际的外键.B表是后来扩展出来的. 问题:根据某个ID查询时超时,运行时跑不出结果. 原因:使用 ...

  5. [电子书] 《Android编程入门很简单》

    <Android编程入门很简单>是一本与众不同的Android学习读物,是一本化繁为简,把抽象问题具体化,把复杂问题简单化的书.本书避免出现云山雾罩.晦涩难懂的讲解,代之以轻松活泼.由浅入 ...

  6. 双数组trie树的基本构造及简单优化

    一 基本构造 Trie树是搜索树的一种,来自英文单词"Retrieval"的简写,可以建立有效的数据检索组织结构,是中文匹配分词算法中词典的一种常见实现.它本质上是一个确定的有限状 ...

  7. [mysql] 2进制安装和简单优化

    ##################################mysql 2进制安装和简单优化################################################## ...

  8. 封装ajax,让调用变得简单优化

    思考一下: 通常我们在使用ajax来发送接口请求时,每一次都会调用ajax固定的元素,比如data.url.method.success.error等.那么我们想一下能不能先把ajax封装起来,在每次 ...

  9. linux简单优化

    1.简单优化 #关闭firewalld,selinux,NetworkManager systemctl(管理服务的命令) stop(关服务) firewalld (服务名称,d是demo的意思) s ...

随机推荐

  1. Linux mkdir 创建文件夹命令

    介绍: 该命令创建指定的目录名,要求创建目录的用户在当前目录中具有写权限,并且指定的目录名不能是当前目录中已有的目录 语法: mkdir [-m] [-p] 目录名 选项介绍: -m: 对新建目录设置 ...

  2. Lua手动编译姿势

    LUA-5.3.3.tar.gz Lua源码+链接2016年5月30日更新 手动编译姿势: 已经装有VS2010 使用VS自带的 cl.exe以及 VS命令簿 打开文件地址 运行自己的bat文件 my ...

  3. re.search 和 re.match

    相同点: 都返回找到的第一个匹配对象 >>> import re >>> m = re.search('(\w+) (\w+)', 'aaa bbb ccc ddd ...

  4. AngularJS 初用总结

    一直用惯jquery,初用Angularjs的初段时间,需要先了解一下她的类MVC思想. 初学时几个比较基本的概念: 1.客户端模板 2. Model View Controller (MVC) 3. ...

  5. MySQL 5.7 学习:新增配置参数

    背景: 继上次介绍 初识 MySQL 5.6 新功能.参数完之后,刚好MySQL 5.7又GA了,在官方测试里看到,MySQL5.7在功能.性能.可用性.安全和监控上又提升了很高.现在看看和MySQL ...

  6. C#通过事件跨类调用WPF主窗口中的控件

    xaml.cs文件: using System; using System.Timers; using System.Windows; using System.Windows.Forms; name ...

  7. iOS - 使用自定义字体-苹方字体

    苹方提供了六个字重,font-family 定义如下:苹方-简 常规体font-family: PingFangSC-Regular, sans-serif;苹方-简 极细体font-family: ...

  8. 在shell 上执行mongo 查询

    需求 在写小工具的时候,经常遇到需要从mongodb 里面查东西来用,因为要跟其他bash 工具链结合在一起用,所以最理想的方法是能够在shell 上执行查询,然后pipe 给接下来的工具做处理. 方 ...

  9. Asp.net通过模板(.dot/Html)导出Word,同时导出图片

    一.Office组件导出Word(服务器配置麻烦) 需要引用Office的DLL,在下文的附件中,不同的Offic版本用的不一样,虽然高级版本可以兼容低级的,不过,还是统一版本最好 贴上核心代码(转载 ...

  10. LeetCode——Best Time to Buy and Sell Stock I (股票买卖时机问题1)

    问题: Say you have an array for which the ith element is the price of a given stock on day i. If you w ...