lucene入门代码五(在搜索结果中使用高亮)

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 org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.search.highlight.TokenSources;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
/**
 * 
 * 为了简单起见,创建内存目录,存放索引,然后在contents高亮搜索关键字
 *
 */
public class HighlightAtSearchResult
{
	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
	{
		//创建索引
		RAMDirectory dir = new RAMDirectory();
		IndexWriter writer = new IndexWriter(dir,new StandardAnalyzer(
				Version.LUCENE_30), IndexWriter.MaxFieldLength.UNLIMITED);
		Document doc = new Document();
		doc.add(new Field("title","highlight matches in search results",Field.Store.NO,Field.Index.NOT_ANALYZED_NO_NORMS));
		doc.add(new Field("contents",text,Field.Store.YES,Field.Index.ANALYZED));
		writer.addDocument(doc);
		IndexReader reader = writer.getReader();
		//查询索引
		IndexSearcher searcher = new IndexSearcher(reader);
		TermQuery query = new TermQuery(new Term("contents", "term"));
		TopDocs hits = searcher.search(query,10);
		QueryScorer scorer = new QueryScorer(query, "contents");
		Highlighter highlighter = new Highlighter(scorer);
		highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));
		Analyzer analyzer = new SimpleAnalyzer();
		for(ScoreDoc sd :hits.scoreDocs){
			Document docs = searcher.doc(sd.doc);
			String contents = docs.get("contents");
			TokenStream tokens = TokenSources.getAnyTokenStream(searcher.getIndexReader(),sd.doc,"contents",analyzer);
			String fragment =
					highlighter.getBestFragments(tokens, contents,3,"...");
					System.out.println(fragment);
		}
		reader.close();
		searcher.close();
		writer.close();
		
	}
}

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