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 300null 判断
bash
?$filter=description eq null
?$filter=description ne nullURL 编码
| 字符 | 编码 |
|---|---|
| 空格 | %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 对照
| 操作 | REST | GraphQL |
|---|---|---|
| 等于 | title eq 'Dune' | { title: { eq: "Dune" } } |
| 大于 | year gt 2000 | { year: { gt: 2000 } } |
| 包含 | contains(title,'Dune') | { title: { contains: "Dune" } } |
| 逻辑与 | and | and: [...] |
| 逻辑或 | or | or: [...] |
| 逻辑非 | not | 不支持(用 neq 或 isNull: false 替代) |
| null | eq null / ne null | { isNull: true/false } |
限定
| 限定 | 说明 |
|---|---|
| 字段名大小写 | REST 路径参数区分大小写,字段名与 API 层名称一致 |
| 不支持的类型 | geography、geometry、xml 等数据库特定类型不支持筛选 |
| 存储过程 | 存储过程不支持 $filter 和 filter 参数 |
| 视图 | 视图支持筛选,规则与表相同 |
