在 REST 中使用 $after 分页

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

转到 本文档的 GraphQL 版本

快速浏览

概念 Description
$after 从前一个请求返回的不透明延续令牌
$first 每页提取的最大记录数
nextLink 下一页的 URL 包括 $after

基本分页

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

HTTP 请求

GET /api/books?$first=3

概念 SQL

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

示例响应

{
  "value": [
    { "id": 1, "title": "Dune" },
    { "id": 2, "title": "Foundation" },
    { "id": 3, "title": "Hyperion" }
  ],
  "nextLink": "/api/books?$first=3&$after=eyJpZCI6M30="
}

注释

如果在 next-link-relative=true 配置中, nextLink 则包含相对路径;否则为绝对 URL。

继续 $after

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

警告

$after 携带一个不透明标记,用于标识最后一页结束的位置。 将令牌视为不可变的,并且永远不会尝试构造或修改它们。

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

HTTP 请求

GET /api/books?$first=3&$after=eyJpZCI6M30=

概念 SQL

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

示例响应

{
  "value": [
    { "id": 4, "title": "I, Robot" },
    { "id": 5, "title": "The Left Hand of Darkness" },
    { "id": 6, "title": "The Martian" }
  ],
  "nextLink": "/api/books?$first=3&$after=eyJpZCI6Nn0="
}

数据结束

如果 nextLink 不存在,则没有更多要提取的记录。 最后一个页面响应仅包含一个 value 没有数组的 nextLink数组。

示例响应

{
  "value": [
    { "id": 7, "title": "Rendezvous with Rama" },
    { "id": 8, "title": "The Dispossessed" }
  ]
}

注释

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

示例配置

{
  "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 约定开头。