简体   繁体   English

使用MongoDB进行批量API的结果分页

[英]Result pagination for bulk API with MongoDB

How does results pagination work for bulk API with MongoDB? MongoDB批量API如何进行结果分页?

API endpoint(just for context): API端点(仅针对上下文):

/team/listTeamsForUsers

Input: 输入:

{
   "userIds": ["userId1", "userId2", "userId3"...],
   "options": {
       "pageSize": 10,
       "pageIndex": 0
    }
}

A user can be associated with multiple teams. 一个用户可以与多个团队相关联。 Hence the API needs ability to paginate the results, based on pageSize and pageIndex . 因此,API需要基于pageSizepageIndex对结果进行分页的能力。

Pagination is possible for single userId input. 分页对于单个userId输入是可能的。 How do I support pagination for multiple inputs? 我如何支持多个输入的分页?

Example use case: 用例示例:
User01 is associated to 10 teams. User01与10个团队相关联。
User02 is associated to 20 teams. User02与20个团队相关联。

when pageSize=10 and pageIndex=0
    Teams 1-10 related to User01 should be returned.

when pageSize=10 and pageIndex=1
    Teams 1-10 related to User02 should be returned.

when pageSize=10 and pageIndex=2
    Teams 11-20 related to User02 should be returned.

It would be great to see examples of such implementation. 看到这种实现的例子将是很棒的。

Any suggestions? 有什么建议么?

Assumptions: 假设:

  • I suppose a user can be a member in multiple teams and a team has multiple members. 我想一个用户可以是多个团队的成员,而一个团队有多个成员。 Therefore, users and teams are in a many to many relationship. 因此,用户和团队之间存在多对多的关系。
  • I further assume you have a junction table that maps from userId to teamId in order to model the above relationship. 我进一步假设您有一个连接表,该连接表从userId映射到teamId以便对上述关系进行建模。

Table structures: 表结构:

  • Users table : id | 用户表: id | name 名称
  • Teams table : id | 球队表: id | name 名称
  • UsersTeams : userId | UsersTeams: userId | teamId teamId

Considering you get a list of userId as input, a SQL snippet for paging the teams associated with those users would look as follows (please note I did not test the below snippet). 考虑到您获得了一个userId列表作为输入,用于分页与这些用户关联的团队的SQL代码片段如下所示(请注意,我没有测试以下代码片段)。

select distinct t.name
    from team t, user u, userTeam ut
    where t.id = ut.teamId and u.id = ut.userId and u.id in (1, 2)
    order by t.name desc
    limit 0, 10;
  • The parameters passed to limit are the pageIndex*pageSize and (pageIndex+1)*pagSize . 传递给limit的参数是pageIndex*pageSize(pageIndex+1)*pagSize
  • The parameters passed to in are the userIds you get from the endpoint. 传递的参数inuserIds ,你从端点获得。

Although this approach is easy to understand and implement, it does not have the best performance. 尽管此方法易于理解和实施,但它没有最佳性能。 Please see https://www.xarg.org/2011/10/optimized-pagination-using-mysql/ for paging optimizations for MySQL (although you probably can translate most of that to any SQL database). 请参阅https://www.xarg.org/2011/10/optimized-pagination-using-mysql/了解MySQL的分页优化(尽管您可能可以将大多数转换为任何SQL数据库)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM