Lucene之——设置高亮核心代码

来源:转载

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/49532465

不多说,不废话,直接上代码

package com.lyz.d;import org.apache.lucene.search.Query;import org.apache.lucene.search.highlight.Formatter;import org.apache.lucene.search.highlight.Highlighter;import org.apache.lucene.search.highlight.QueryScorer;import org.apache.lucene.search.highlight.Scorer;import org.apache.lucene.search.highlight.SimpleFragmenter;import org.apache.lucene.search.highlight.SimpleHTMLFormatter;/** * 高亮工具类 * @author liuyazhuang * */public class HighlighterUtil { private static Formatter formatter = null; private static Scorer scorer = null; static{ formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>"); } /** * 设置高亮 * @param query:查询的query * @param field:高亮的字段 * @param value:高亮的值 * @param size:大小 * @return:高亮后的数据 */ public static String setHighData(Query query, String field, String value, int size){ String result = null; scorer = new QueryScorer(query); //高亮工具类 Highlighter highlighter = new Highlighter(formatter, scorer); //设置数据长度 highlighter.setTextFragmenter(new SimpleFragmenter(size)); try { result = highlighter.getBestFragment(Configuration.getAnalyzer(), field, value); if(result == null){ if(value.length() > size){ result = value.substring(0, size); }else{ result = value; } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } return result; }}



分享给朋友:
您可能感兴趣的文章:
随机阅读: