我刚刚发现 Lucene 支持使用searchAfter
方法进行分页,因此我将其添加到我的实现中。不幸的是,它返回与前一个查询相同的结果,我不明白为什么。
基本上我正在做的是调用我的search
方法并存储Query
返回的ScoreDoc
和最后collector.topDocs()
。然后,当用户想要加载下一页时,我会调用searcher.searchAfter(previousResult, previousQuery, MAX_HITS)
,但我会收到与运行searcher.search(query, collector)
时收到的相同的结果。
请注意,我每页返回15个文档,我的查询有32个匹配,所以我希望它至少有2页。
以下是代码:
private Query previousQuery;
private ScoreDoc previousResult;
private float previousMaxScore;
private ScoreDoc[] search(String query) throws ParseException, IOException {
Query q = parser.parse(query);
TopScoreDocCollector collector = TopScoreDocCollector.create(MAX_HITS_PER_PAGE);
searcher.search(q, collector);
TopDocs result = collector.topDocs();
// Let's normalize scores
for (ScoreDoc scoreDoc : result.scoreDocs) {
scoreDoc.score /= result.getMaxScore();
}
// If the query had some results then we save the last one to support paging
if (collector.getTotalHits() > 0) {
previousQuery = q;
previousResult = result.scoreDocs[result.scoreDocs.length - 1];
previousMaxScore = result.getMaxScore();
}
return result.scoreDocs;
}
private ScoreDoc[] searchNextPage() throws IOException {
// previosuResult is CORRECT, it's the last one from the previous query so it's not part of the issue.
TopDocs result = searcher.searchAfter(previousResult, previousQuery, MAX_HITS_PER_PAGE);
// Let's normalize scores
for (ScoreDoc scoreDoc : result.scoreDocs) {
scoreDoc.score /= previousMaxScore;
}
// Let's update previous result with the new one
if (result.scoreDocs.length > 0) {
previousResult = result.scoreDocs[result.scoreDocs.length - 1];
}
return result.scoreDocs;
}
我做错了什么?