REST 中的字段选择(投影)

投影有助于仅返回客户端实际需要的内容。 较小的有效负载可提高性能、降低网络成本,并减少客户端分析开销。 数据 API 生成器 (DAB) 通过查询参数实现 REST 的 $select 投影。

注释

REST 查询参数名称(包括 $select)区分大小写。 字段名称也根据所配置或公开的内容区分大小写。

转到 本文档的 GraphQL 版本

基本选择

图案

GET /api/{entity}?$select=FieldA,FieldB,FieldC

如果$select省略,DAB 将返回调用方角色有权读取的所有字段(受配置和exclude字段级权限的约束include)。 没有通配符标记,例如 *,省略 $select 是请求完整允许的形状的方式。

例子

# Return all accessible fields
GET /api/author

# Return only first_name
GET /api/author?$select=first_name

# Return only first_name and last_name
GET /api/author?$select=first_name,last_name

内部列与响应列

不需要投影主键或排序字段。 如果省略,它们不会显示在 JSON 响应中。 但是,DAB 可能会内部提取强制实施安全策略(行级筛选器、字段掩码)和处理分页游标所需的额外列($after / nextLink)。

注释

除非显式请求这些列,否则这些内部提取的列在响应之前被删除。

Example

GET /api/book?$select=id,title&$orderby=publisher_id desc&$first=5

概念 SQL

SELECT TOP (6) -- first (5) + 1 probe row for paging
  [b].[id],
  [b].[sku_title] AS title
FROM dbo.books AS [b]
ORDER BY [b].[publisher_id] DESC, [b].[id] ASC;

响应

{
  "value": [
    { "id": 101, "title": "Example 1" },
    { "id": 77,  "title": "Example 2" },
    { "id": 42,  "title": "Example 3" },
    { "id": 33,  "title": "Example 4" },
    { "id": 5,   "title": "Example 5" }
  ],
  "nextLink": "..."
}

详细了解 分页和 after 关键字

额外的内部列和第六个探测行在有效负载中不可见。

存储过程

对于存储过程支持的实体, $select 不解释为投影子句。 相反,查询字符串键/值对(如等识别的系统参数除外$filter$orderby)被视为存储过程参数。 $select 不起作用;过程的结果集定义形状。

示例配置

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