分页查询有两种实现方式:
1、再查询
public void searchPage(String query, int pageIndex, int pageSize) {
try {
Directory dir = FileIndexUtils.getDirectory();
IndexSearcher searcher = getSearcher(dir);
QueryParser parser = new QueryParser(Version.LUCENE_35, "content",new StandardAnalyzer(Version.LUCENE_35));
Query q = parser.parse(query);
TopDocs tds = searcher.search(q, 500);
ScoreDoc[] sds = tds.scoreDocs;
int start = (pageIndex - 1) * pageSize;
int end = pageIndex * pageSize;
for (int i = start; i < end; i++) {
Document doc = searcher.doc(sds[i].doc);
System.out.println(sds[i].doc + ":" + doc.get("path") + "-->" + doc.get("filename"));
}
searcher.close();
} catch (org.apache.lucene.queryParser.ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2、searchAfter(3.5之后才出现的)
/**
* 根据页码和分页大小获取上一次的最后一个ScoreDoc
*/
private ScoreDoc getLastScoreDoc(int pageIndex, int pageSize, Query query,
IndexSearcher searcher) throws IOException {
if (pageIndex == 1)
return null;//如果是第一页就返回空
int num = pageSize * (pageIndex - 1);//获取上一页的数量
TopDocs tds = searcher.search(query, num);
return tds.scoreDocs[num - 1];
}
public void searchPageByAfter(String query, int pageIndex, int pageSize) {
try {
Directory dir = FileIndexUtils.getDirectory();
IndexSearcher searcher = getSearcher(dir);
QueryParser parser = new QueryParser(Version.LUCENE_35, "content",new StandardAnalyzer(Version.LUCENE_35));
Query q = parser.parse(query);
//先获取上一页的最后一个元素
ScoreDoc lastSd = getLastScoreDoc(pageIndex, pageSize, q, searcher);
//通过最后一个元素搜索下页的pageSize个元素
TopDocs tds = searcher.searchAfter (lastSd, q, pageSize);
for (ScoreDoc sd : tds.scoreDocs) {
Document doc = searcher.doc(sd.doc);
System.out.println(sd.doc + ":" + doc.get("path") + "-->" + doc.get("filename"));
}
searcher.close();
} catch (org.apache.lucene.queryParser.ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}