Lucene的分頁查詢

來源:互聯網
上載者:User

  分頁查詢只需要傳入每頁顯示多少條記錄,當前是第幾頁就可以了。

  當然是對搜尋返回的結果進行分頁,並不是對搜尋結果的總數量進行分頁,因為我們搜尋的時候都是返回前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);}

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.