【问题标题】:How to perform pagination on MongoDB with spring?如何使用spring在MongoDB上执行分页?
【发布时间】:2017-07-20 16:30:03
【问题描述】:

我有这个使用 spring 框架从 MongoDB 获取项目列表的 java 代码:

    @Autowired
    private PersonsRepository personsRepository;
     ...
     ...


                         // the name field is NOT INDEXED!
    List<Person> dbRecords = personsRepository.findByName("John");
    for (Person person: dbRecords) {
           //do something
    }

我需要查询的字段未编入索引,近期无法更改。

由于 db 包含 1 亿条记录,而输出列表预计包含 10 亿条记录,我有几个问题:

  1. 查询本身 (getByName) 需要很长时间(几个小时后仍未完成)。我怎样才能做得更好?
  2. 如何通过分页查询数据?

谢谢

【问题讨论】:

  • 在没有适当索引的情况下查询具有数百万条记录的集合有点愚蠢...如果您甚至无法创建索引,那么甚至没有理由将主题作为分片提出因为那时你可能也无法改变它。
  • 您是否尝试过使用Pageable

标签: java spring mongodb pagination


【解决方案1】:

看来我找到了如何使用分页:

我在接口中添加了一个新方法:

Page<Person> findByName(@Param("name") String name, Pageable pageable);

在代码本身中我做了:

    Page<Person> nextPage;
    List<Person> dbRecords;
    boolean stop = false;
    Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC, SORT_FIELD));
    do {
        Pageable pageable = new PageRequest(0, PAGE_SIZE, sort);
        nextPage = personsRepository.findByName("john", pageable);           
        dbRecords = nextPage.getContent();
        if (dbRecords.size() > 0) {
            // do something
        } else {
            stop = true;
        }
    } while (nextPage.getSize() > 0 && !stop);

现在分页可以正常工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2014-09-12
    • 2018-06-26
    • 2020-09-15
    • 1970-01-01
    相关资源
    最近更新 更多