1、设置高亮
SolrQuery query = new SolrQuery();
...
query.setHighlight(true );
query.addHighlightField("path" );
query.addHighlightField("content" );
query.setHighlightSimplePre("<font color='red'>" );
query.setHighlightSimplePost("</font>" );
/**
* 高亮摘要的段数,默认为1
* 大于1时,返回多个包含关键字的摘要段落
* 等于1时,只返回包含关键字最多的段落
*/
query.setHighlightSnippets(3 );
/**
* 摘要段落的长度,默认100
*/
query.setHighlightFragsize(75 );
2、获取高亮
QueryResponse queryResponse = solr.query(query);
SolrDocumentList results = queryResponse.getResults();
Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
for (SolrDocument solrDocument : results){
TXDocument document = new TXDocument();
document.setId(solrDocument.get("id" ).toString());
Map<String, List<String>> map = highlighting.get(solrDocument.get("id" ));
if (map.get("path" ) != null ){
document.setPath(map.get("path" ).toString());
} else {
document.setPath(solrDocument.get("path" ).toString());
}
String matchContents = "" ;
List<String> list = map.get("content" );
if (list != null ){
for (int i=0 ;i<list.size();i++){
if (i != 0 ){
matchContents += " . . . " ;
}
matchContents += list.get(i);
}
} else {
String docContent = solrDocument.get("content" ).toString();
matchContents = (docContent.length() > 75 ?docContent.substring(0 , 75 ):docContent);
}
document.setContent(matchContents);
}
3、效果