使用Lucene全文检索并使用中文版和高亮显示

中文分词需要引入 中文分词发的jar 包,咱们从maven中获取

	<!-- lucene中文分词器 -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-smartcn</artifactId>
<version>5.3.1</version>
</dependency>

下面是分词和索引的事例

	package LuceneTest.LuceneTest;

	import java.nio.file.Paths;

	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.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;
import org.junit.Test; public class IndexChina { private Directory dir; //存放索引的位置 //准备一下用来测试的数据
private Integer ids[] = {1, 2, 3}; //用来标识文档
private String citys[] = {"上海", "南京", "青岛"};
private String descs[] = {
"上海是个繁华的城市。",
"南京是一个有文化的城市。",
"青岛是一个美丽的城市。"
}; //生成索引
@Test
public void index(String indexDir) throws Exception {
dir = FSDirectory.open(Paths.get(indexDir));
IndexWriter writer = getWriter();
for(int i = 0; i < ids.length; i++) {
Document doc = new Document();
doc.add(new IntField("id", ids[i], Store.YES));
doc.add(new StringField("city", citys[i], Store.YES));
doc.add(new TextField("desc", descs[i], Store.YES));
writer.addDocument(doc); //添加文档
}
writer.close(); //close了才真正写到文档中
} //获取IndexWriter实例
private IndexWriter getWriter() throws Exception {
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();//使用中文分词器
IndexWriterConfig config = new IndexWriterConfig(analyzer); //将标准分词器配到写索引的配置中
IndexWriter writer = new IndexWriter(dir, config); //实例化写索引对象
return writer;
} public static void main(String[] args) throws Exception {
new IndexChina().index("D:\\lucene2");
}
}

新建的查询

	package LuceneTest.LuceneTest;

	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.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
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; public class SearcherChina { public static void search(String indexDir, String q) throws Exception { Directory dir = FSDirectory.open(Paths.get(indexDir)); //获取要查询的路径,也就是索引所在的位置
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer(); //使用中文分词器
QueryParser parser = new QueryParser("desc", analyzer); //查询解析器
Query query = parser.parse(q); //通过解析要查询的String,获取查询对象 long startTime = System.currentTimeMillis(); //记录索引开始时间
TopDocs docs = searcher.search(query, 10);//开始查询,查询前10条数据,将记录保存在docs中
long endTime = System.currentTimeMillis(); //记录索引结束时间
System.out.println("匹配" + q + "共耗时" + (endTime-startTime) + "毫秒");
System.out.println("查询到" + docs.totalHits + "条记录"); for(ScoreDoc scoreDoc : docs.scoreDocs) { //取出每条查询结果
Document doc = searcher.doc(scoreDoc.doc); //scoreDoc.doc相当于docID,根据这个docID来获取文档
System.out.println(doc.get("city"));
System.out.println(doc.get("desc"));
String desc = doc.get("desc");
}
reader.close();
} public static void main(String[] args) {
String indexDir = "D:\\lucene2";
String q = "上海繁华"; //查询这个字符
try {
search(indexDir, q);
} catch (Exception e) {
e.printStackTrace();
}
}
}

搜索结果的高亮显示

引入jar文件

	 <!-- lucene高亮显示 -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>5.3.1</version>
</dependency>

新建查询并将查询的结果高亮

	package LuceneTest.LuceneTest;

	import java.io.StringReader;
import java.nio.file.Paths; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
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.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
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.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 SearcherChina { public static void search(String indexDir, String q) throws Exception { Directory dir = FSDirectory.open(Paths.get(indexDir)); //获取要查询的路径,也就是索引所在的位置
IndexReader reader = DirectoryReader.open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer(); //使用中文分词器
QueryParser parser = new QueryParser("desc", analyzer); //查询解析器
Query query = parser.parse(q); //通过解析要查询的String,获取查询对象 long startTime = System.currentTimeMillis(); //记录索引开始时间
TopDocs docs = searcher.search(query, 10);//开始查询,查询前10条数据,将记录保存在docs中
long endTime = System.currentTimeMillis(); //记录索引结束时间
System.out.println("匹配" + q + "共耗时" + (endTime-startTime) + "毫秒");
System.out.println("查询到" + docs.totalHits + "条记录"); //此处加入的是搜索结果的高亮部分
SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<b><font color=red>","</font></b>"); //如果不指定参数的话,默认是加粗,即<b><b/>
QueryScorer scorer = new QueryScorer(query);//计算得分,会初始化一个查询结果最高的得分
Fragmenter fragmenter = new SimpleSpanFragmenter(scorer); //根据这个得分计算出一个片段
Highlighter highlighter = new Highlighter(simpleHTMLFormatter, scorer);
highlighter.setTextFragmenter(fragmenter); //设置一下要显示的片段 for(ScoreDoc scoreDoc : docs.scoreDocs) { //取出每条查询结果
Document doc = searcher.doc(scoreDoc.doc); //scoreDoc.doc相当于docID,根据这个docID来获取文档
System.out.println(doc.get("city"));
System.out.println(doc.get("desc"));
String desc = doc.get("desc"); //显示高亮部分
if(desc != null) {
TokenStream tokenStream = analyzer.tokenStream("desc", new StringReader(desc));
String summary = highlighter.getBestFragment(tokenStream, desc);
System.out.println(summary);
} } reader.close();
} public static void main(String[] args) {
String indexDir = "D:\\lucene2";
String q = "南京文化"; //查询这个字符
try {
search(indexDir, q);
} catch (Exception e) {
e.printStackTrace();
}
}
}

使用Lucene全文检索并使用中文版和高亮显示的更多相关文章

  1. Lucene全文检索技术

    Lucene全文检索技术 今日大纲 ●    搜索的概念.搜索引擎原理.倒排索引 ●    全文索引的概念 ●    使用Lucene对索引进行CRUD操作 ●    Lucene常用API详解 ●  ...

  2. lucene 全文检索工具的介绍

    Lucene:全文检索工具:这是一种思想,使用的是C语言写出来的 1.Lucene就是apache下的一个全文检索工具,一堆的jar包,我们可以使用lucene做一个谷歌和百度一样的搜索引擎系统 2. ...

  3. Apache Lucene(全文检索引擎)—创建索引

    目录 返回目录:http://www.cnblogs.com/hanyinglong/p/5464604.html 本项目Demo已上传GitHub,欢迎大家fork下载学习:https://gith ...

  4. lucene全文检索基础

    全文检索是一种将文件中所有文本与检索项匹配的文字资料检索方法.比如用户在n个小说文档中检索某个关键词,那么所有包含该关键词的文档都返回给用户.那么应该从哪里入手去实现一个全文检索系统?相信大家都听说过 ...

  5. Lucene 全文检索 Lucene的使用

    Lucene  全文检索  Lucene的使用 一.简介: 参考百度百科: http://baike.baidu.com/link?url=eBcEVuUL3TbUivRvtgRnMr1s44nTE7 ...

  6. Lucene全文检索_分词_复杂搜索_中文分词器

    1 Lucene简介 Lucene是apache下的一个开源的全文检索引擎工具包. 1.1 全文检索(Full-text Search)  1.1.1 定义 全文检索就是先分词创建索引,再执行搜索的过 ...

  7. Lucene 全文检索

    基于 lucene 8 1 Lucene简介 Lucene是apache下的一个开源的全文检索引擎工具包. 1.1 全文检索(Full-text Search) 全文检索就是先分词创建索引,再执行搜索 ...

  8. 【Lucene】Apache Lucene全文检索引擎架构之中文分词和高亮显示4

    前面总结的都是使用Lucene的标准分词器,这是针对英文的,但是中文的话就不顶用了,因为中文的语汇与英文是不同的,所以一般我们开发的时候,有中文的话肯定要使用中文分词了,这一篇博文主要介绍一下如何使用 ...

  9. lucene全文检索---打酱油的日子

    检索内容,一般的程序员第一时间想到的是sql的like来做模糊查询,其实这样的搜索是比较耗时的.已经有lucene帮我们 封装好了,lucene采用的是分词检索等策略. 1.lucene中的类描述 I ...

随机推荐

  1. OpenCms JSP 模板开发——创建一个简单的JSP模板

    OpenCms中的JSP模板就是一个普通的JSP页面,在特定的位置使用标签来包含内容,在这个的例子中,我们将要开发一个简单JSP模板,这个模板只是在内容(如<html>.<body& ...

  2. 【渗透课程】第三篇-体验http协议的应用

    之前我们都了解了,访问网页时,客户端与服务端之间的请求与响应数据交互.本篇就浅谈它的应用. 利用HTTP拦截突破前段验证 比方说,我们在某个网页提交某些数据(例如留言.上传.插入xss等),发生错误( ...

  3. [读书笔记] 一、Spring boot项目搭建与配置文件

    读书笔记:[JavaEE开发的颠覆者 Spring Boot实战] 作者:汪云飞 从今天开始坚持读书,并记录下此读书笔记. 一,初接触 Spring boot 项目Hello world搭建 1.po ...

  4. jQuery给表单设置值

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. appium的webdriver执行swipe

    # convenience method added to Appium (NOT Selenium 3) def swipe(self, start_x, start_y, end_x, end_y ...

  6. ASP.NET Core的身份认证框架IdentityServer4(7)- 使用客户端证书控制API访问

    前言 今天(2017-9-8,写于9.8,今天才发布)一口气连续把最后几篇IdentityServer4相关理论全部翻译完了,终于可以进入写代码的过程了,比较累.目前官方的文档和Demo以及一些相关组 ...

  7. 垃圾收集器Serial 、Parallel、CMS、G1

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt378 这里介绍4个垃圾收集器,如果进行了错误的选择将会大大的影响程序的性能. ...

  8. C++学习日记(二)————初始字符串类型

    使用频率高,但操作复杂的数据有哪些? 做下总结: int; double;float;char;bool这些类型用的比较频繁,但并不复杂.但对于字符串来说(char数组)用的频繁但操作又复杂,只能用一 ...

  9. Android studio 一些技术添加依赖,依赖库

    Recyclerview compile 'com.android.support:recyclerview-v7:21.0.+' butterKnife 的依赖compile 'com.jakewh ...

  10. Httpservlet 获取json对象字符窜

    使用的是google 的json转换jar import com.google.gson.JsonObject;import com.google.gson.JsonParser; import or ...