分页

这是 GraphQL 库版本 7 的文档。对于长期支持 (LTS) 版本 5,请参考GraphQL 库版本 5 LTS

Neo4j GraphQL 库提供两种分页机制

  • 基于偏移量的分页 - 基于偏移量的分页,通常与按页导航相关联。

  • 基于游标的分页 - 基于游标的分页,通常与无限滚动应用程序相关联。

基于偏移量的分页

基于偏移量的分页,通常与按页导航相关联,可以通过在查询数据时使用 offsetlimit 选项来实现。

使用以下类型定义

type User @node {
    name: String!
}

通过执行以下操作获取每页 10 个数据的第一页

query {
    users(limit: 10) {
        name
    }
}

然后在后续调用中,引入 offset 参数并在每次调用时将其递增 10。

获取第二页,使用

query {
    users(offset: 10, limit: 10) {
        name
    }
}

获取第三页,使用

query {
    users(offset: 20, limit: 10) {
        name
    }
}

依此类推。

总页数

您可以使用其计数查询获取特定类型的记录总数,然后将该数字除以每页条目数以计算总页数。这决定了最后一页是哪一页,以及是否存在下一页。

有关如何执行这些查询的详细信息,请参阅计数查询。

关系字段分页

假设除了上面的 User 类型外,还有一个 Post 类型,一个 User 可以拥有多个 Post。您也可以获取一个 User,然后对其帖子进行分页。

query {
  users(where: { name: { eq: "Billy" } }) {
    name
    posts(offset: 20, limit: 10) {
      content
    }
  }
}

基于游标的分页

在关系字段上,您可以利用基于游标的分页,这通常与无限滚动应用程序相关联。

使用以下类型定义

type User @node {
    name: String!
    posts: [Post!]! @relationship(type: "HAS_POST", direction: OUT)
}

type Post @node {
    content: String!
}

如果您想一次获取用户“John Smith”的 10 个帖子,您首先需要获取 10 个

query {
  users(where: { name: { eq: "John Smith" } }) {
    name
    postsConnection(first: 10) {
      edges {
        node {
          content
        }
      }
      pageInfo {
        endCursor
        hasNextPage
      }
    }
  }
}

在返回值中,如果 hasNextPagetrue,您将把 endCursor 传递到下一个 10 个数据的查询中。您可以使用变量来做到这一点,例如在以下查询中的 $after

query Users($after: String) {
    users(where: { name: { eq: "John Smith"} }) {
        name
        postsConnection(first: 10, after: $after) {
            edges {
                node {
                    content
                }
            }
            pageInfo {
                endCursor
                hasNextPage
            }
        }
    }
}

您可以继续,直到返回中的 hasNextPagefalse——这意味着您已到达数据的末尾。

totalCount

Connection 字段还提供一个 totalCount 字段,可用于计算页码。如果您想通过游标分页但在应用程序中使用页码,这会很有用。

添加 totalCount 字段,它返回与所用过滤器匹配的结果总数,例如

query Users {
  users(where: { name: { eq: "John Smith" } }) {
    name
    postsConnection(first: 10) {
      edges {
        node {
          content
        }
      }
      pageInfo {
        endCursor
        hasNextPage
      }
      totalCount
    }
  }
}
© . All rights reserved.