`
hai0378
  • 浏览: 517014 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Lucene的分页查询

 
阅读更多

Lucene的分页查询

Posted on 2012-06-24 21:19 CN.programmer.Luxh 阅读(2422) 评论(4编辑 收藏

  分页查询只需要传入每页显示多少条记录,当前是第几页就可以了。

  当然是对搜索返回的结果进行分页,并不是对搜索结果的总数量进行分页,因为我们搜索的时候都是返回前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);
    }

  

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics