日期:2014-05-17  浏览次数:20883 次

lucene入门代码四(使用css高亮文本)
1.本代码需要的jar包有:
lucene-core-3.0.0.jar
lucene-analyzers-3.0.0.jar
lucene-highlighter-3.0.0.jar

代码如下:
package com.yale.lucene;

import java.io.FileWriter;
import java.io.StringReader;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
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.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.util.Version;

/**
 * 
 * 使用CSS高亮terms
 *
 */
public class HighlightTermsUseCSS
{
	private static final String text =
			"In this section we'll show you how to make the simplest " +
			"programmatic query, searching for a single term, and then " +
			"we'll see how to use QueryParser to accept textual queries. " +
			"In the sections that follow, we’ll take this simple example " +
			"further by detailing all the query types built into Lucene. " +
			"We begin with the simplest search of all: searching for all " +
			"documents that contain a single term.";
	public static void main(String[] args) throws Exception
	{
		//将高亮后的html代码写入此文件
		String filename="F://新建文件夹//luceneTest//dataSource//highlight.html";
		//要搜索的关键字
		String searchText = "term";
		//创建QueryParser
		QueryParser parser = new QueryParser(Version.LUCENE_30,"f",new StandardAnalyzer(Version.LUCENE_30));
		//得到Query
		Query query = parser.parse(searchText);
		//要高亮的文本添加样式
		SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span class=\"highlight\">","</span>");
		//TokenStream用来分析文字流,按一定的规则罗列token
		TokenStream tokens = new StandardAnalyzer(Version.LUCENE_30).tokenStream("f",new StringReader(text));
		//声明查询记分器
		QueryScorer scorer = new QueryScorer(query,"f");
		//声明高亮的关键类
		Highlighter highlighter = new Highlighter(formatter,scorer);
		//设置段划分器;使用SimpleSpanFragmenter
		highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));
		//得到高亮的片段
		String result = highlighter.getBestFragments(tokens,text,3,"...");
		//写入文件操作
		FileWriter writer = new FileWriter(filename);
		writer.write("<html>");
		writer.write("<style>\n" +
		".highlight {\n" +
		" background: yellow;\n" +
		"}\n" +
		"</style>");
		writer.write("<body>");
		writer.write(result);
		writer.write("</body></html>");
		writer.close();
		System.out.println("完成");
			
	}
}

效果图如下: