Lucene高亮显示内容

来源:互联网 发布:mac修图软件 编辑:程序博客网 时间:2024/05/01 15:22
public String highlight(Query query,String filedname,String text){
         try {
             QueryScorer queryScorer=new QueryScorer(query);
             Fragmenter fragmenter=new SimpleSpanFragmenter(queryScorer);
             Formatter formatter=new SimpleHTMLFormatter("<strong>", "</strong>");
             Highlighter highlighter=new Highlighter(formatter,queryScorer);
             highlighter.setTextFragmenter(fragmenter);
             String str=highlighter.getBestFragment(new MMSegAnalyzer(), filedname, text);
             return str;
         }  catch (IOException e) {
             e.printStackTrace();
         } catch (InvalidTokenOffsetsException e) {
             e.printStackTrace();
         }
         return text;

     }


public void search(String word){
         try {
             IndexSearcher searcher=Utils.getIndexSearcher();
             MultiFieldQueryParser parser=new MultiFieldQueryParser(Version.LUCENE_35, new String[]{"title","summary"}, new MMSegAnalyzer());
             Query query=parser.parse(word);
             TopDocs topDocs=searcher.search(query, 200);
             ScoreDoc[] docs=topDocs.scoreDocs;
             for(ScoreDoc s:docs){
                 Document d=searcher.doc(s.doc);
                 System.out.println(this.highlight(query,"title", d.get("title")));
                 System.out.println(this.highlight(query,"summary",d.get("summary")));
             }
         } catch (CorruptIndexException e) {
             e.printStackTrace();
         } catch (ParseException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }


 @Test    public void testHighlight02(){        hl.search("百度");    }