`

Lucene3.6的分页查询

 
阅读更多

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

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

        }

        

    }

    

    @Test

    public void testPaginationQuery() throws CorruptIndexException, ParseException, IOException{

        //每页显示5条记录,显示第三页的记录

        paginationQuery("青春",5,3);

    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics