在 GraphQL 中使用 after 分页

分页将大型数据集缩小到更小的可管理页面。 在 GraphQL 中,数据 API 生成器(DAB)使用after键集分页的参数,通过有序结果提供稳定且高效的遍历。 每个游标对上一页中最后一条记录的位置进行编码,从而允许下一个查询从该点继续。 与偏移分页不同,键集分页可避免在请求之间更改数据时出现间隙或重复项。

转到 本文档的 REST 版本

快速浏览

概念 Description
after 上一请求中的延续标记
first 每页提取的最大记录数
hasNextPage 指示是否存在更多数据
endCursor 要包含在下一 after 个请求中的令牌

基本分页

GraphQL 查询

在此示例中,我们获得了前三本书。

query {
  books(first: 3) {
    items {
      id
      title
    }
    hasNextPage
    endCursor
  }
}

概念 SQL

SELECT TOP (3)
  id,
  sku_title AS title
FROM dbo.books
ORDER BY id ASC;

示例响应

{
  "data": {
    "books": {
      "items": [
        { "id": 1, "title": "Dune" },
        { "id": 2, "title": "Foundation" },
        { "id": 3, "title": "Hyperion" }
      ],
      "hasNextPage": true,
      "endCursor": "eyJpZCI6M30="
    }
  }
}

继续 after

after 参数指定下一页的延续标记。 该值是一个 base64 编码的游标,表示上一页的最后一条记录。

警告

after 参数携带一个不透明的标记,用于标记上一页结束的位置。 将令牌视为不可变的,并且永远不会尝试构造或编辑它们。

在此示例中,我们将在最后一页的光标之后获取接下来的三本书。

GraphQL 查询

query {
  books(first: 3, after: "eyJpZCI6M30=") {
    items {
      id
      title
    }
    hasNextPage
    endCursor
  }
}

概念 SQL

SELECT TOP (3)
  id,
  sku_title AS title
FROM dbo.books
WHERE id > 3
ORDER BY id ASC;

示例响应

{
  "data": {
    "books": {
      "items": [
        { "id": 4, "title": "I, Robot" },
        { "id": 5, "title": "The Left Hand of Darkness" },
        { "id": 6, "title": "The Martian" }
      ],
      "hasNextPage": true,
      "endCursor": "eyJpZCI6Nn0="
    }
  }
}

嵌套分页

分页可应用于相关集合,例如检索具有分页书籍列表的作者。

GraphQL 查询

query {
  authors {
    items {
      id
      name
      books(first: 2) {
        items {
          id
          title
        }
        hasNextPage
        endCursor
      }
    }
  }
}

概念 SQL

-- parent
SELECT
  id,
  name
FROM dbo.authors;

-- child
SELECT TOP (2)
  author_id,
  id,
  sku_title AS title
FROM dbo.books
WHERE author_id IN (@a1, @a2)
ORDER BY id ASC;

注释

任何架构或排序更改都使以前颁发的令牌失效。 客户端必须从第一页重启分页。

示例配置

{
  "runtime": {
    "pagination": {
      "default-page-size": 100,
      "max-page-size": 100000
    }
  },
  "entities": {
    "Book": {
      "source": {
        "type": "table",
        "object": "dbo.books"
      },
      "mappings": {
        "sku_title": "title",
        "sku_price": "price"
      },
      "relationships": {
        "book_category": {
          "cardinality": "one",
          "target.entity": "Category",
          "source.fields": [ "category_id" ],
          "target.fields": [ "id" ]
        }
      }
    },
    "Category": {
      "source": {
        "type": "table",
        "object": "dbo.categories"
      },
      "relationships": {
        "category_books": {
          "cardinality": "many",
          "target.entity": "Book",
          "source.fields": [ "id" ],
          "target.fields": [ "category_id" ]
        }
      }
    }
  }
}

另请参阅

概念 REST GraphQL 目的
投影 $select 物品 选择要返回的字段
Filtering $filter 滤波器 按条件限制行
排序 $orderby orderBy 定义排序顺序
页面大小 $first first 限制每页的项数
延续 $after 使用光标从最后一页继续

注释

REST 关键字以 $遵循 OData 约定开头。