全国服务热线:400-885-2225

Lucene4.1分页查询

// 测试分页
public static List<DocInfo> getDocInfosByPage(String indexFile,
Query query, int pageIndex, int pageSize) {
try {
IndexSearcher searcher = LuceneUtil.getSearcher(indexFile);
ScoreDoc lastScoreDoc = getLastScoreDoc(indexFile, query,
pageIndex, pageSize);
TopDocs topDocs = searcher.searchAfter(lastScoreDoc, query,
pageSize);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
List<DocInfo> docInfos = new ArrayList<DocInfo>();
for (ScoreDoc scoreDoc : scoreDocs) {
Document doc = searcher.doc(scoreDoc.doc);
DocInfo docInfo = new DocInfo(doc.get(DocInfo.FILE_ID),
doc.get(DocInfo.FILE_NAME),
doc.get(DocInfo.FILE_TITLE),
doc.get(DocInfo.FILE_CONTENT), new Date().getTime());
docInfos.add(docInfo);
}
return docInfos;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

        return null;
}
// 根据页码获取上一页最后一个ScoreDoc
public static ScoreDoc getLastScoreDoc(String indexFile, Query query,
int pageIndex, int pageSize) throws IOException {
ScoreDoc lastScoreDoc = null;
if (pageIndex > 1) {
IndexSearcher searcher = LuceneUtil.getSearcher(indexFile);
int num = (pageIndex - 1) * pageSize;
TopDocs topDocs = searcher.search(query, num);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
lastScoreDoc = scoreDocs[num - 1];
}
return lastScoreDoc;

    }
测试分页查询

@Test
    //测试分页查询
    public void testPrePageQuery(){
        Term term = new Term(DocInfo.FILE_NAME,"hibernate");
        TermQuery query = new TermQuery(term);
        List<DocInfo> docInfos = SearcherManager.getDocInfosByPage(indexFile, query, 2, 3);
        printDocInfos(docInfos);

    }

上一篇:Lucene分词器简介

下一篇:扩展QueryParser

 
点击QQ沟通