使用 $first REST 限制页面大小

在查询大型数据集时,限制页面大小可防止压倒性的客户端或服务器。 在 REST 中,数据 API 生成器(DAB)使用 $first 参数来控制单个响应中返回的记录数。 DAB 在内部应用基于游标的分页,但 $first 即使不需要延续,也可以使用。

注释

$first 限制返回但本身不处理延续的行数。 对于多个页面,请使用 $after

转到 本文档的 GraphQL 版本

概述

概念 Description
默认页面大小 runtime.pagination.default-page-size (默认值为 100)
最大页面大小 runtime.pagination.max-page-size (默认值为 100000)
客户端替代 $first
请求最大值 $first=-1 请求配置的最大页面大小

如果 $first 省略,则会自动应用默认页面大小。

使用模式

GET /api/{entity}?$first=N

Example

将结果限制为五本书。

GET /api/books?$first=5

概念 SQL

SELECT TOP (5)
  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" },
    { "id": 4, "title": "I, Robot" },
    { "id": 5, "title": "The Martian" }
  ]
}

验证规则

Input 结果
省略 使用 default-page-size
正整数≤最大值 已接受
-1 展开到 max-page-size
0 400 (无效)
< -1 400
> max-page-size 400

示例错误消息

Invalid number of items requested, first argument must be either -1 or a positive number within the max page size limit of 100000. Actual value: 0

示例配置

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