本实例使用的是:
lucene3.0.3
lucene-highlighter-3.0.3
package com.hpjianhua.lucene; import java.io.StringReader; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Query; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.util.Version; import org.wltea.analyzer.lucene.IKAnalyzer; /** * * @author hpjianhua * @version 1.0 * */ public class HighlighterTester { public static void main(String[] args) throws Exception { String text = "flower:A man can fail many times, but he isn't a failure until he begins to blame somebody else.flower wirter"; QueryParser parser = new QueryParser(Version.LUCENE_30, "field", new StandardAnalyzer(Version.LUCENE_30)); Query query = parser.parse("flower"); SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<font color=\"red\">","</font>"); Highlighter highlight = new Highlighter(formatter, new QueryScorer(query)); TokenStream tokens = new IKAnalyzer().tokenStream("field", new StringReader(text)); System.out.println(highlight.getBestFragment(tokens, text)); } }
output:
<font color="red">flower</font>:A man can fail many times, but he isn't a failure until he begins to blame somebody
jar包见下面: