论坛首页 综合技术论坛

一个Lucene3.0.3 高亮显示实例

浏览 4426 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-04-07  
一个没有索引,直接使用高亮显示的实例:使用的时候请注意lucene与highlighter的版本。

本实例使用的是:
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包见下面:
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics