java鬼混笔记:lucene 7、查询排序和分页

时间:2022-12-20 11:00:54

Query query = queryParser.parse("我");// 排序Sort sort = new Sort();sort.setSort(new SortField("title", Type.SCORE, false));// 根据title的得分来排序其中false是升序,true就是降序TopDocs top = searcher.search(query, 12, sort);


分页


分页目前找到2种解决方案,推荐用第2种,撑住大数据情况


第1种、比如查20-30条的记录,先查出前30条,后面for循环从i = 20开始就行

Query query = queryParser.parse("VPN");
int currentPage = 1;
int pageSize = 10;

TopDocs top = searcher.search(query, (currentPage*pageSize));

System.out.println("得到" + top.totalHits + "条记录");
ScoreDoc[] scoreDocs = top.scoreDocs;
if(scoreDocs != null && scoreDocs.length > 0){
int i = (currentPage-1)*pageSize;
for(;i < scoreDocs.length; i++) {
ScoreDoc s = scoreDocs[i];
System.out.println(s.score);
Document doc = searcher.doc(s.doc);
System.out.println(doc.get("title"));
System.out.println(doc.get("content"));
markKeyWord(query, doc, analyzer);
}
}
OK。。。

第2种、用searchAfter()方法
先生成一个ScoreDoc后用searchAfter方法

Query query = queryParser.parse("VPN");
int currentPage = 1;
int pageSize = 10;

ScoreDoc sd;

if(currentPage == 1) {
sd = null;
}else {
int num = pageSize*(currentPage-1);//获取上一页的最后是多少
TopDocs td = searcher.search(query, num);
sd = td.scoreDocs[num-1];
}

// 核心方法
TopDocs top = searcher.searchAfter(sd, query, 12);// 这里的12像hibernate,是在这一页上查12条

System.out.println("得到" + top.totalHits + "条记录");
ScoreDoc[] scoreDocs = top.scoreDocs;
if(scoreDocs != null && scoreDocs.length > 0){
int i = (currentPage-1)*pageSize;
for(;i < scoreDocs.length; i++) {
System.out.println(i);
ScoreDoc s = scoreDocs[0];
System.out.println(s.score);
Document doc = searcher.doc(s.doc);
System.out.println(doc.get("title"));
System.out.println(doc.get("content"));
markKeyWord(query, doc, analyzer);
}
}