lucene设置高亮

一、文档中的代码修改下Filter:

 

Directory dir=FSDirectory.open(new File("E:\\lucene\\test_lucene\\index"));
		IndexReader r=DirectoryReader.open(dir);
		//IndexSearcher   search=new IndexSearcher(r);
		IndexSearcher searcher = new IndexSearcher(r);
		Analyzer analyzer=new SmartChineseAnalyzer(Version.LUCENE_42);
		QueryParser parser = new QueryParser(Version.LUCENE_42, "countent", analyzer);
		Query query = parser.parse("红纸包绿纸包");
		
		TopDocs hits = searcher.search(query, 10);
		
		SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter("<font color=\"red\">", "</font>");
		Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query));
		for (int i = 0; i < hits.scoreDocs.length; i++) {
			
			int id = hits.scoreDocs[i].doc;
			Document doc = searcher.doc(id);
			String text = doc.get("countent");
			TokenStream tokenStream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), id, "countent", analyzer);
			TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, text, false, 10);//highlighter.getBestFragments(tokenStream, text, 3, "...");
			for (int j = 0; j < frag.length; j++) {
				if ((frag[j] != null) && (frag[j].getScore() > 0)) {
					System.out.println((frag[j].toString()));
				}
			}
			//Term vector
			text = doc.get("Path");
			tokenStream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), hits.scoreDocs[i].doc, "Path", analyzer);
			frag = highlighter.getBestTextFragments(tokenStream, text, false, 10);
			for (int j = 0; j < frag.length; j++) {
				if ((frag[j] != null) && (frag[j].getScore() > 0)) {
					System.out.println((frag[j].toString()));
				}
			}
			System.out.println("-------------");
		}
	}

 二、效果如下


lucene设置高亮
 
lucene设置高亮
 

你可能感兴趣的:(Lucene)