分頁查詢只需要傳入每頁顯示多少條記錄,當前是第幾頁就可以了。
當然是對搜尋返回的結果進行分頁,並不是對搜尋結果的總數量進行分頁,因為我們搜尋的時候都是返回前n條記錄。
例如indexSearcher.search(query, 100);//只返回前100條記錄
/** * 對搜尋返回的前n條結果進行分頁顯示 * @param keyWord 查詢關鍵詞 * @param pageSize每頁顯示記錄數 * @param currentPage當前頁 * @throws ParseException * @throws CorruptIndexException * @throws IOException */public void paginationQuery(String keyWord,int pageSize,int currentPage) throws ParseException, CorruptIndexException, IOException {String[] fields = {"title","content"};QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_36,fields,analyzer);Query query = queryParser.parse(keyWord);IndexReader indexReader = IndexReader.open(directory);IndexSearcher indexSearcher = new IndexSearcher(indexReader);//TopDocs 搜尋返回的結果TopDocs topDocs = indexSearcher.search(query, 100);//只返回前100條記錄int totalCount = topDocs.totalHits; // 搜尋結果總數量ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 搜尋返回的結果集合//查詢起始記錄位置int begin = pageSize * (currentPage - 1) ;//查詢終止記錄位置int end = Math.min(begin + pageSize, scoreDocs.length);//進行分頁查詢for(int i=begin;i<end;i++) {int docID = scoreDocs[i].doc;Document doc = indexSearcher.doc(docID);int id = NumericUtils.prefixCodedToInt(doc.get("id"));String title = doc.get("title");System.out.println("id is : "+id);System.out.println("title is : "+title);}}@Testpublic void testPaginationQuery() throws CorruptIndexException, ParseException, IOException{//每頁顯示5條記錄,顯示第三頁的記錄paginationQuery("思想",5,3);}