19、学习Lucene3.5索引之高亮搜索

/**
 * Lucene高亮显示:
 * 1.引入“lucene-highlighter”包
 */
public class HighLighter {

    private IndexReader indexReader;

    public void highLightTest(){
        try {
            String str = "我是一只丑小鸭,咿呀咿呀呦!门前一只鸭,四五六七八;鹅鹅鹅,曲项向天歌,白毛浮绿水,红掌拨清波";
            QueryParser queryParser = new QueryParser(Version.LUCENE_35, "f", new MMSegAnalyzer());
            Query query = queryParser.parse("鸭 一只");
            //1.查询评分
            QueryScorer queryScorer = new QueryScorer(query);
            //2.对文本进行分段
            Fragmenter fragmenter = new SimpleSpanFragmenter(queryScorer);
            //3.设置高亮显示的样式
            Formatter formatter = new SimpleHTMLFormatter("", "");
            //4.高亮显示
            Highlighter highlighter = new Highlighter(formatter, queryScorer);
            //5.设置分段
            highlighter.setTextFragmenter(fragmenter);
            //6.得到分段后的高亮文本
            String txt = highlighter.getBestFragment(new MMSegAnalyzer(), "f", str);
            System.out.println(txt);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (InvalidTokenOffsetsException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



你可能感兴趣的:(全文搜索引擎lucene3.5)