lucene3.5高亮设置

import java.io.IOException;
import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.util.Version;

public class HighlighterDemo {
	public static String toHighlighter(Query query, Document doc, String field) throws IOException, InvalidTokenOffsetsException {
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
		SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<font color=\"red\">", "</font>");
		Highlighter highlighter = new Highlighter(simpleHtmlFormatter,new QueryScorer(query));
		TokenStream tokenStream = analyzer.tokenStream(field,new StringReader(doc.get(field)));
		String highlighterStr = highlighter.getBestFragment(tokenStream, doc.get(field));
		return highlighterStr == null ? doc.get(field) : highlighterStr;
	}
}

你可能感兴趣的:(Lucene,highlighter,tokenstream)