1 public String highlight(Query query,String filedname,String text){ 2 try { 3 QueryScorer queryScorer=new QueryScorer(query); 4 Fragmenter fragmenter=new SimpleSpanFragmenter(queryScorer); 5 Formatter formatter=new SimpleHTMLFormatter("<strong>", "</strong>"); 6 Highlighter highlighter=new Highlighter(formatter,queryScorer); 7 highlighter.setTextFragmenter(fragmenter); 8 String str=highlighter.getBestFragment(new MMSegAnalyzer(), filedname, text); 9 return str; 10 } catch (IOException e) { 11 e.printStackTrace(); 12 } catch (InvalidTokenOffsetsException e) { 13 e.printStackTrace(); 14 } 15 return text; 16 }
1 public void search(String word){ 2 try { 3 IndexSearcher searcher=Utils.getIndexSearcher(); 4 MultiFieldQueryParser parser=new MultiFieldQueryParser(Version.LUCENE_35, new String[]{"title","summary"}, new MMSegAnalyzer()); 5 Query query=parser.parse(word); 6 TopDocs topDocs=searcher.search(query, 200); 7 ScoreDoc[] docs=topDocs.scoreDocs; 8 for(ScoreDoc s:docs){ 9 Document d=searcher.doc(s.doc); 10 System.out.println(this.highlight(query,"title", d.get("title"))); 11 System.out.println(this.highlight(query,"summary",d.get("summary"))); 12 } 13 } catch (CorruptIndexException e) { 14 e.printStackTrace(); 15 } catch (ParseException e) { 16 e.printStackTrace(); 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } 20 }
@Test public void testHighlight02(){ hl.search("百度"); }