Lucene 4.7 --高亮显示

时间:2023-12-20 23:28:08

jar

lucene-analyzers-common-4.7.0.jar
lucene-analyzers-smartcn-4.7.0.jar
lucene-core-4.7.0.jar
lucene-queryparser-4.7.0.jar
lucene-memory-4.7.0.jar
lucene-queries-4.7.0.jar
lucene-highlighter-4.7.0.jar

先一段查询代码

Set<String> fields = new HashSet<String>();
fields.add("carId");
fields.add("carName"); org.apache.lucene.document.Document document = searcher.doc(scoreDoc.doc, fields);
CarVO resultVO = new CarVO();
resultVO.setCarId(document.getValues("carId")[0]);
resultVO.setCarName(document.getValues("carName")[0]);
return resultVO;

在这里,如果说我们通过carName搜索到了某个car,那么我们希望能够高亮显示这个carName中匹配的值,那么就对这个resultVO中setCarName时进行高亮处理,方法如下:

这样调用:

resultVO.setCarName(highlightFormat(document.getValues("carName")[0],"carName",query,scoreDoc,document));

实现方法:

private String highlightFormat(String value, String field,
Query query, ScoreDoc scoreDoc, Document document) throws Exception { QueryScorer scorer = new QueryScorer(query,field);
SimpleHTMLFormatter hlightFormater = new SimpleHTMLFormatter("<span class=\"hlight\">", "</span>");
Highlighter hl = new Highlighter(hlightFormater,scorer);
hl.setTextFragmenter(new SimpleSpanFragmenter(scorer));
TokenStream stream = TokenSources.getAnyTokenStream(
searcher.getIndexReader(), scoreDoc.doc, field, document, analyzer); String valueWithHighlight = hl.getBestFragment(stream, value);
return valueWithHighlight;
}

searcher就是IndexSearcher,anlyzer是分词器,这个我一般都作为静态变量长时间持有

其余的这一“大堆”东西我并不打算做太多说明,一则是这里和原来的版本变化不大,二是基本按照这些点已经足够满足基本的开发应用需求了,唯一需要大家关注的,也需要大家自己处理得,就是

SimpleHTMLFormatter hlightFormater = new SimpleHTMLFormatter("<span class=\"hlight\">", "</span>");  

当然这里提醒一句,如果是你的carName这种属性是可以让用户自定义输入的,请一定要注意对注入攻击的拦截