1.高亮显示
//演示Lucene的高亮显示
@Test
public void testHighLight() throws ParseException, IOException, InvalidTokenOffsetsException {
QueryParser parser = new QueryParser(Version.LATEST, "content", new IKAnalyzer());
Query query = parser.parse("谷歌");
//设置高亮显示格式,两个参数(html的头标签和尾标签)
SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
//创建高亮显示对象
Highlighter highlighter = new Highlighter(formatter, new QueryScorer(query));
//创建索引搜索器并指定索引库的位置
IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("e:/tmp"))));
TopDocs topDocs = indexSearcher.search(query, Integer.MAX_VALUE);
System.out.println(topDocs.totalHits);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc :
scoreDocs) {
Document doc = indexSearcher.doc(scoreDoc.doc);
String bestFragment = highlighter.getBestFragment(new IKAnalyzer(), "content", doc.get("content"));
System.out.println(bestFragment);
}
}
2.分页搜索
//测试Lucene的分页
@Test
public void testLucenePageable() throws IOException {
//设置页码
int pageNum = 1;
//设置总页数
int totalPagenum = 3;
//设置每页显示数量
int pageSize = 3;
//计算起始位置
int startIndex = (totalPagenum-pageNum)*pageSize;
//计算终点
int endIndex = pageNum*pageSize;
TermQuery query = new TermQuery(new Term("content", "谷歌"));
IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("e:/tmp"))));
TopDocs topDocs = indexSearcher.search(query, endIndex);
System.out.println(topDocs);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc :
scoreDocs) {
System.out.println(scoreDoc.doc);
Document doc = indexSearcher.doc(scoreDoc.doc);
System.out.println(doc.get("content"));
}
}