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("------------------------------------------------------------------");
}
}
}