分頁查詢只需要傳入每頁顯示多少條記錄,當前是第幾頁就可以了。
當然是對搜索返回的結果進行分頁,並不是對搜索結果的總數量進行分頁,因爲我們搜索的時候都是返回前n條記錄。
例如indexSearcher.search(query, 100);//只返回前100條記錄
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
/** *
對搜索返回的前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); } } @Test public void testPaginationQuery()
throws CorruptIndexException,
ParseException, IOException{ //每頁顯示5條記錄,顯示第三頁的記錄 paginationQuery( "思想" , 5 , 3 ); } |