标签:
本例使用 Lucene 5.3.1 的包
package com.wenniuwuren.lucene; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.Term; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; 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 java.io.StringReader; /** * 搜索结果高亮显示: 整体思路就是找到关键词, 然后在关键词两侧加入渲染标签, 达到高亮效果 * Created by wenniuwuren on 16/2/22. */ public class HighlightTest { public static void main(String args[]) { try { // 将被处理的文本 String searchResult = "chinese live in china"; // 创建查询 Query query = new TermQuery(new Term("country", "china")); // 对于符合条件的结果进行 score QueryScorer queryScorer = new QueryScorer(query, "country"); // 自定义高亮格式 SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<font color='red'>", "</font>"); Highlighter highlighter = new Highlighter(simpleHTMLFormatter, queryScorer); // 设置片段插入信息 highlighter.setTextFragmenter(new SimpleSpanFragmenter(queryScorer)); // 分词器, 这个只能分英文 StandardAnalyzer analyzer = new StandardAnalyzer(); // 结果处理 TokenStream tokenStream = analyzer.tokenStream("country", new StringReader(searchResult)); String finalResult = highlighter.getBestFragment(tokenStream, searchResult); System.out.println(finalResult); } catch (Exception e) { e.printStackTrace(); } } }
二. 运行结果
执行成功 ,china 关键词成功加上了 <font> 标签
标签:
原文地址:http://blog.csdn.net/wenniuwuren/article/details/50726104