Skip to content

GraphQL 查询参考

数据墙DBW 为每个实体自动生成查询入口。本文档完整描述 GraphQL 查询的所有参数和语法。

查询类型

每个实体自动生成两种查询:

查询类型语法返回
列表查询{entity-plural}匹配条件的记录列表,带分页
按主键查询{entity-singular}_by_pk单条记录或 null

列表查询

graphql
{
  books {
    items {
      id
      title
      year
      pages
    }
  }
}

所有字段必须显式声明——GraphQL 没有 SELECT * 通配符。

按主键查询

graphql
{
  book_by_pk(id: 1) {
    id
    title
    year
  }
}

主键不存在的记录返回 nullerrors(而非空列表)。

filter 参数

filter 用于条件筛选,支持字段级运算符和逻辑组合:

比较运算符

graphql
{
  books(filter: { year: { gte: 2000 }, pages: { gt: 300 } }) {
    items { id title }
  }
}
运算符含义
eq等于
neq不等于
gt大于
gte大于等于
lt小于
lte小于等于
contains字符串包含
startswith字符串开头
endswith字符串结尾
isNull是否为 null(值为 truefalse

逻辑组合

graphql
{
  books(filter: {
    and: [
      { year: { gte: 2000 } }
      { pages: { gt: 300 } }
    ]
  }) {
    items { id title }
  }
}
逻辑运算符说明
and所有条件同时满足
or至少一个条件满足

andor 可以嵌套实现复杂逻辑:

graphql
{
  books(filter: {
    and: [
      { year: { gte: 2000 } }
      {
        or: [
          { title: { contains: "Dune" } }
          { title: { contains: "Foundation" } }
        ]
      }
    ]
  }) { items { id title year } }
}

orderBy 参数

graphql
{
  books(orderBy: { year: DESC, title: ASC }) {
    items { id title year }
  }
}
方向说明
ASC升序(默认,可省略)
DESC降序

多字段排序按参数书写顺序依次应用。

分页参数

first

graphql
{
  books(first: 5) {
    items { id title }
    hasNextPage
    endCursor
  }
}
参数说明
first每页返回的记录数。-1 返回配置的 max-page-size

after

graphql
{
  books(first: 5, after: "eyJpZCI6NX0=") {
    items { id title }
    hasNextPage
    endCursor
  }
}
参数说明
after上一页返回的 endCursor 值,用于翻页

字段别名

在查询中可以为字段指定别名:

graphql
{
  books {
    items {
      bookId: id
      bookTitle: title
    }
  }
}

响应中字段使用别名:

json
{ "bookId": 1, "bookTitle": "示例书名" }

关系查询

实体间配置的关系自动在 GraphQL 架构中体现为嵌套字段:

多对一(单对象)

graphql
{
  books {
    items {
      title
      category {
        name
      }
    }
  }
}

一对一和多对一关系返回单个对象。

一对多(列表)

graphql
{
  categories {
    items {
      name
      books {
        items { title }
      }
    }
  }
}

一对多和多对多关系返回 items 数组,同样支持分页。

嵌套别名

graphql
{
  books {
    items {
      title
      bookCategory: category { catName: name }
    }
  }
}

字段选择

GraphQL 原生支持精确字段选择——查询中声明哪些字段,响应就只返回哪些字段。这与 REST API 中 $select 参数的功能对等,但更灵活(支持嵌套和别名)。

分页响应字段

字段类型说明
items[T]当前页的记录数组
hasNextPageBoolean是否还有下一页
endCursorString分页游标,传 after 参数获取下一页

GraphQL 特有的能力

能力GraphQLREST
按需字段选择原生支持$select 参数
嵌套关联查询支持(关系)不支持
字段别名支持不支持
聚合查询支持不支持
多重变更支持不支持
缓存不支持支持(L1/L2)

下一步

数据墙DBW 产品文档与开发指南。