Lucene高亮显示,排序,过滤

Lucene高亮显示,排序过滤

/**
 * lucene高亮显示,排序,过滤
 * @author Administrator
 *
 */
public class TestlighterHighter {
	
	@Test
	public  void testLigghterhighter() throws IOException, ParseException, InvalidTokenOffsetsException{
		//创建目录 
		Directory directory=FSDirectory.open(new File("D://luceneDirluceneDir"));
		//版本
	    Version version  = Version.LUCENE_44;
		//分词器
		Analyzer analyzer = new StandardAnalyzer(version);
		
		//创建indexReader
		IndexReader indexReader = DirectoryReader.open(directory);
		IndexSearcher indexSearcher  = new IndexSearcher(indexReader);
		
		//关键字及查询字段
		String keyword = "全文检索";
		String [] fields = {"title","content"};
		
		//查询对象
		QueryParser queryParser = new MultiFieldQueryParser(version,fields,analyzer);
		Query query = queryParser.parse(keyword);
		
		//创建highlighter对象
		Formatter formatter  = new SimpleHTMLFormatter("<font color='green'>","</font>");
		Scorer fragmentScorer = new QueryScorer(query);
		Highlighter highlighter  = new Highlighter(formatter,fragmentScorer);
		
		//排序 
		SortField sortedField = new SortField("id",Type.INT,true);
		Sort sort  = new Sort(sortedField);
		//过滤器
		Filter filter = NumericRangeFilter.newIntRange("id", 1, 4, true, true);
		
	
		TopDocs topDocs  =indexSearcher.search(query, filter, 10, sort);
		
		System.out.println("total==="+topDocs.totalHits);
	
		
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			int docID = scoreDoc.doc;
			System.out.println("documentID===="+docID);
			Document document = indexSearcher.doc(docID);
			
			String id = document.get("id");
			String title = document.get("title");
			String content = document.get("content");
			
			String hightitle = highlighter.getBestFragment(analyzer, "title", title);
			String highcontent = highlighter.getBestFragment(analyzer, "content", content);
			
			System.out.println("id==="+id);
			System.out.println("title==="+title);
			System.out.println("content===="+content);
			
			System.out.println("hightitle===="+hightitle);
			System.out.println("highcontent==="+highcontent);
			System.out.println("------------------------------------------------------------------");
	       
			
		}
	
		
		
	}
   
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值