(七)lucene之中文检索和高亮显示以及摘要
- 前提:本章节使用lucene5.3.0版本,luke也是此版本的。
1.1 生成索引
package com.shyroke.lucene; import java.io.IOException;
import java.nio.file.Paths; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory; public class Indexer { private Integer ids[]={1,2,3};
private String citys[]={"青岛","南京","上海"};
private String descs[]={
"青岛是一个美丽的城市。",
"南京是一个有文化的城市。南京是一个文化的城市南京,简称宁,是江苏省会,地处中国东部地区,长江下游,濒江近海。全市下辖11个区,总面积6597平方公里,2013年建成区面积752.83平方公里,常住人口818.78万,其中城镇人口659.1万人。[1-4] “江南佳丽地,金陵帝王州”,南京拥有着6000多年文明史、近2600年建城史和近500年的建都史,是中国四大古都之一,有“六朝古都”、“十朝都会”之称,是中华文明的重要发祥地,历史上曾数次庇佑华夏之正朔,长期是中国南方的政治、经济、文化中心,拥有厚重的文化底蕴和丰富的历史遗存。[5-7] 南京是国家重要的科教中心,自古以来就是一座崇文重教的城市,有“天下文枢”、“东南第一学”的美誉。截至2013年,南京有高等院校75所,其中211高校8所,仅次于北京上海;国家重点实验室25所、国家重点学科169个、两院院士83人,均居中国第三。[8-10] 。",
"上海是一个繁华的城市。"
}; private IndexWriter writer;
/**
* 实例化IndexWriter,这里使用中文分词器SmartChineseAnalyzer
* @param indexDir 存放索引的目录
* @return
* @throws IOException
*/
public IndexWriter getIndexWriter(String indexDir) throws IOException {
Directory dir=FSDirectory.open(Paths.get(indexDir));
// Analyzer analyzer=new StandardAnalyzer();
SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
IndexWriterConfig conf=new IndexWriterConfig(analyzer);
IndexWriter writer=new IndexWriter(dir, conf);
return writer;
} public void index(String indexDir) throws IOException {
this.writer=getIndexWriter(indexDir); for(int i=0;i<ids.length;i++) {
Document document=new Document();
document.add(new IntField("id", ids[i], Field.Store.YES));
document.add(new StringField("city", citys[i], Field.Store.YES));
document.add(new TextField("desc", descs[i], Field.Store.YES));
writer.addDocument(document);
} writer.close();
} public static void main(String[] args) {
try {
new Indexer().index("E:\\lucene6\\index");
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 橙色标注部分的SmartChineseAnalyzer 是中文的分词器,这样当执行main方法后生成的索引文件内容如下图:
可见,中文词语已经被分组了。
1.2 中文查询,并高亮显示摘要
package com.shyroke.lucene; import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Paths; import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
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.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory; public class Searcher { private IndexSearcher searcher;
private IndexReader reader; public Searcher(String indexDir) throws IOException {
Directory dir=FSDirectory.open(Paths.get(indexDir));
this.reader=DirectoryReader.open(dir);
this.searcher=new IndexSearcher(this.reader);
} public void search(String key) throws ParseException, IOException, InvalidTokenOffsetsException { SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
QueryParser parser=new QueryParser("desc",analyzer);
Query query=parser.parse(key); long start=System.currentTimeMillis();
TopDocs hits=searcher.search(query, 10);
long end=System.currentTimeMillis();
System.out.println("匹配 "+key+" ,总共花费"+(end-start)+"毫秒"+"查询到"+hits.totalHits+"个记录"); QueryScorer scorer=new QueryScorer(query);
Fragmenter fragmenter=new SimpleSpanFragmenter(scorer);
SimpleHTMLFormatter simpleHTMLFormatter=new SimpleHTMLFormatter("<b><font color='red'>","</font></b>");
Highlighter highlighter=new Highlighter(simpleHTMLFormatter, scorer);
highlighter.setTextFragmenter(fragmenter);
for(ScoreDoc scoreDoc:hits.scoreDocs){
Document doc=searcher.doc(scoreDoc.doc);
System.out.println(doc.get("city"));
String desc=doc.get("desc");
if(desc!=null){
TokenStream tokenStream=analyzer.tokenStream("desc", new StringReader(desc));
/**
* getBestFragment方法用于输出摘要(即权重大的内容)
*/
System.out.println(highlighter.getBestFragment(tokenStream, desc));
}
}
reader.close();
} public static void main(String[] args) throws InvalidTokenOffsetsException {
try {
new Searcher("E:\\lucene6\\index").search("南京 文化");
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 执行上述代码前请务必先运行1.1生成索引的代码。
- 结果:

如图可见,查询desc的值为“南京 文化”的document只有一个,且输出的结果是格式化后的带有html标签的内容,在html文档中就会呈现高亮显示,且highlighter.getBestFragment(tokenStream, desc) 用这种方法输出的是摘要信息,可以对比输出信息与

对比可知,输出的内容是权重比较大的摘要信息。
(七)lucene之中文检索和高亮显示以及摘要的更多相关文章
- lucene之中文分词及其高亮显示(五)
中文分词:即换个分词器 Analyzer analyzer = new StandardAnalyzer();// 标准分词器 换成 SmartChineseAnalyzer analyze ...
- lucene之中文分词及其高亮显示
参考:http://www.cnblogs.com/lirenzhujiu/p/5914174.html http://www.cnblogs.com/xing901022/p/3933675.htm ...
- 【Lucene】Apache Lucene全文检索引擎架构之中文分词和高亮显示4
前面总结的都是使用Lucene的标准分词器,这是针对英文的,但是中文的话就不顶用了,因为中文的语汇与英文是不同的,所以一般我们开发的时候,有中文的话肯定要使用中文分词了,这一篇博文主要介绍一下如何使用 ...
- Lucene基础(三)-- 中文分词及高亮显示
Lucene分词器及高亮 分词器 在lucene中我们按照分词方式把文档进行索引,不同的分词器索引的效果不太一样,之前的例子使用的都是标准分词器,对于英文的效果很好,但是中文分词效果就不怎么样,他会按 ...
- Linux下PHP+MySQL+CoreSeek中文检索引擎配置
说明: 操作系统:CentOS 5.X 服务器IP地址:192.168.21.127 Web环境:Nginx+PHP+MySQL 站点根目录:/usr/local/nginx/html 目的:安装co ...
- CoreSeek中文检索引擎
目的:安装coreseek中文检索引擎,配置MySQL数据库访问接口,使用PHP程序实现中文检索. CoreSeek官方网站: http://www.coreseek.cn/ http://www.c ...
- Mybatis使用MySQL进行模糊查询时输入中文检索不到结果
Mybatis使用MySQL进行模糊查询时输入中文检索时,需要在jdbcURL后增加参数 ?useUnicode=true&characterEncoding=UTF-8
- Mybatis使用MySQL模糊查询时输入中文检索不到结果怎么办--转自http://www.jb51.net/article/88236.htm
这篇文章主要介绍了Mybatis使用MySQL模糊查询时输入中文检索不到结果的解决办法的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 项目开发中,在做Mybatis动态查询时,遇到了 ...
- sphinx中文版Coreseek中文检索引擎安装和使用方法(Linux)
sphinx中文版Coreseek中文检索引擎安装和使用方法(Linux) 众所周知,在MYSQL数据库中,如果你在百万级别数据库中使用 like 的话那你一定在那骂娘,coreseek是一个 ...
随机推荐
- python arcgis
- Microsoft Visual C++ Runtime library not enough space for thread data
Microsoft Visual C++ Runtime library not enough space for thread data 电脑最近一直在运行的时候,弹出提示框,如下: 解决办 ...
- Linux 基于WEB开源的系统管理工具webmin
Webmin是目前功能最强大的基于Web的Unix系统管理工具.管理员通过浏览器访问Webmin的各种管理功能并完成相应的管理动作.目前Webmin支持绝大多数的Unix系统,这些系统除了各种版本的l ...
- opengl版本
OpenGL vendor string: IntelOpenGL renderer string: Intel(R) HD Graphics 630OpenGL version string: 4. ...
- Visual studio 正在从以下位置加载符号:Microsoft符号服务器 尝试取消禁用后续符号加载
正在从以下位置加载符号:Microsoft符号服务器 尝试取消禁用后续符号加载 进入VS---工具---选项----调试----符号,看右边有个“Microsoft符号服务器”,将前面的勾去掉,( ...
- 26Flutter 日期 和时间戳/格式化日期库/flutter异步/ 官方自带日期组件showDatePicker、时间组件showTimePicker以及国际化
/* 一.Flutter日期和时间戳 日期转换成时间戳 var now=newDateTime.now(); print(now.millisecondsSinceEpoch); //单位毫秒,13位 ...
- DTC & MSDTC (待研究)
相关学习文档: Database Systems: The Complete Book
- Qt pri文件
pri文件就是一个简单的文件夹包含或者动态库调用路径等说明,在pro文件里include了pri文件,相当于把pri文件的内容直接复制到pro文件中
- Qps 和 tps的解释
QPS:Queries Per Second意思是“每秒查询率”,是一台服务器每秒能够相应的查询次数,是对一个特定的查询服务器在规定时间内所处理流量多少的衡量标准. TPS:是Transactions ...
- MapReduce\Tez\Storm\Spark四个框架的异同
1) MapReduce:是一种离线计算框架,将一个算法抽象成Map和Reduce两个阶段进行 处理,非常适合数据密集型计算. 2) Spark:MapReduce计算框架不适合迭代计算和交互式计算, ...