Skip to content

filter 参数参考

filter (GraphQL) / $filter (REST) 参数用于按条件筛选返回的数据行。两者的功能对等,语法形式不同——REST 使用 OData URL 查询语法,GraphQL 使用嵌套对象语法。

REST:$filter

语法

?$filter={field} {operator} {value}

运算符两侧必须有空格。字符串值使用单引号,数字直接书写。

比较运算符

运算符含义示例
eq等于title eq 'Dune'
ne不等于year ne 2000
gt大于pages gt 300
ge大于等于year ge 2000
lt小于pages lt 100
le小于等于year le 2020

字符串函数

函数说明示例
contains(field, 'value')包含子字符串contains(title, 'Foundation')
startswith(field, 'value')以某字符串开头startswith(title, 'The')
endswith(field, 'value')以某字符串结尾endswith(title, 'Wakes')

逻辑组合

运算符说明示例
and同时满足year ge 2000 and pages gt 300
or至少一个满足title eq 'Dune' or title eq 'Foundation'
not取反not year lt 2000

括号控制优先级:

bash
?$filter=(year ge 2000 or title eq 'Dune') and pages gt 300

null 判断

bash
?$filter=description eq null
?$filter=description ne null

URL 编码

字符编码
空格%20
单引号 '%27
左括号 (%28
右括号 )%29

大多数 HTTP 客户端自动处理编码。

完整示例

bash
# 2000 年后出版、页数大于 200、标题包含 "Dune" 的书
curl "http://localhost:5000/api/Book?\$filter=year%20ge%202000%20and%20pages%20gt%20200%20and%20contains(title,%27Dune%27)"

GraphQL:filter

语法

graphql
{
  books(filter: { field: { operator: value } }) {
    items { ... }
  }
}

比较运算符

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

逻辑组合

graphql
{
  books(filter: {
    and: [
      { year: { gte: 2000 } }
      { pages: { gt: 300 } }
    ]
  }) { items { id title } }
}

嵌套逻辑:

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

null 判断

graphql
{ books(filter: { description: { isNull: true } }) { items { id } } }
{ books(filter: { description: { isNull: false } }) { items { id } } }

REST vs GraphQL 对照

操作RESTGraphQL
等于title eq 'Dune'{ title: { eq: "Dune" } }
大于year gt 2000{ year: { gt: 2000 } }
包含contains(title,'Dune'){ title: { contains: "Dune" } }
逻辑与andand: [...]
逻辑或oror: [...]
逻辑非not不支持(用 neqisNull: false 替代)
nulleq null / ne null{ isNull: true/false }

限定

限定说明
字段名大小写REST 路径参数区分大小写,字段名与 API 层名称一致
不支持的类型geographygeometryxml 等数据库特定类型不支持筛选
存储过程存储过程不支持 $filterfilter 参数
视图视图支持筛选,规则与表相同

下一步

  • orderby — 排序参数参考。
  • select — 字段选择参数参考。
  • first — 分页大小参数参考。

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