高亮显示搜索内容
本篇的基于上一篇
public class TestHighLighter {
public static void main(String[] args)throws Exception {
String fields[] = {"content"};
String keyWords = "安徽";
QueryParser queryParser = new MultiFieldQueryParser(LuceneUtils.getMatchVersion(), fields, LuceneUtils.getAnalyzer());
Query query = queryParser.parse(keyWords);
IndexSearcher indexSearcher = LuceneUtils.getIndexSearcher();
TopDocs topDocs = indexSearcher.search(query, 100);
/*
* 1.高亮成什么颜色
* 2.我们要将哪些关键字要进行高亮
*
*
*/
//1.高亮成什么颜色
Formatter formatter = new SimpleHTMLFormatter("<font color='red'>","</font>");
Scorer fragmentScorer = new QueryScorer(query);
//构造高亮器
Highlighter highlighter = new Highlighter(formatter, fragmentScorer);
for(ScoreDoc scoreDoc:topDocs.scoreDocs){
Document document = indexSearcher.doc(scoreDoc.doc);
String title = document.get("title");
String content = document.get("content");
System.out.println(document.get("content"));
//将某段文本高亮,返回高亮过后的结果
String highlightcontent = highlighter.getBestFragment(LuceneUtils.getAnalyzer(), "content", content);
System.out.println(highlightcontent);
}
}
}