首先,导入下图所示库
然后,import org.apache.lucene.search.highlight.*;
下面,我们新建一个实现高亮显示功能的函数
public static String displayHtmlHighlight(Query query, String fieldName, String fieldContent) throws IOException, InvalidTokenOffsetsException { SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer(); //设置高亮标签,可以自定义 SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>"); /**创建QueryScorer*/ //评分 QueryScorer scorer=new QueryScorer(query); /**创建Fragmenter*/ Fragmenter fragmenter = new SimpleSpanFragmenter(scorer); //高亮分析器 Highlighter highlight=new Highlighter(formatter,scorer); highlight.setTextFragmenter(fragmenter); //fieldname是域名,如"title",fieldContent是d.get("title"); String str=highlight.getBestFragment(analyzer, fieldName, fieldContent); return str; }
最后,调用这个函数
res+=" <a href=""+d.get("link")+"" target="_blank"> <p>"+String.valueOf(cou)+". "+displayHtmlHighlight(query,"title", d.get("title"))+"</p> <p>[ "+d.get("class")+" ] "+d.get("link")+"</p> <p>"+displayHtmlHighlight(query,"sabstract", d.get("sabstract"))+" </p></a> ";
这样就实现了title和abstract的高亮显示关键词