Lucene_demo08_Hightlighter高亮

Lucene_demo08_Hightlighter高亮



/*
 * 1、使关键字变色 <font color='red'>总冠军</font>
 * 2、控制摘要的大小
 */
public class HightlighterTest {
	@Test
	public void testSearchIndex() throws Exception {
		IndexSearcher indexSearcher = new IndexSearcher(LuceneUtils.directory);
		QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_30, new String[] { "title", "content" }, LuceneUtils.analyzer);
		Query query = queryParser.parse("总冠军");
		TopDocs topDocs = indexSearcher.search(query, 25);
		int count = topDocs.totalHits;// 总的记录数
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		List<Article> articleList = new ArrayList<Article>();

		// 设置高亮器
		Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");// 给关键词指定前缀和后缀
		Scorer scorer = new QueryScorer(query);// 指定关键词
		Highlighter highlighter = new Highlighter(formatter, scorer);
		Fragmenter fragmenter = new SimpleFragmenter(50);// 查询出来显示内容的长度
		highlighter.setTextFragmenter(fragmenter);

		for (int i = 0; i < scoreDocs.length; i++) {
			int index = scoreDocs[i].doc;
			Document document = indexSearcher.doc(index);
			// 第一个参数 找到关键词 第二个参数 对哪个字段的关键词进行高亮
			String titleText = highlighter.getBestFragment(LuceneUtils.analyzer, "title", document.get("title"));
			String contentText = highlighter.getBestFragment(LuceneUtils.analyzer, "content", document.get("content"));
			Article article = DocumentUtils.document2Article(document);
			if (titleText != null || !titleText.equals("")) {// 保证要搜索的字段中有关键词
				article.setTitle(titleText);
			}
			if (contentText != null || !contentText.equals("")) {
				article.setContent(contentText);
			}
			articleList.add(article);
		}

		// 输出查询结果
		for (Article article : articleList) {
			System.out.println(article.getId());
			System.out.println(article.getTitle());
			System.out.println(article.getContent());
		}
	}
}



你可能感兴趣的:(Lucene_demo08_Hightlighter高亮)