跳到主要内容

查询操作符

RxDB 使用统一的规则结构 RuleGroup 来描述查询条件。你可以通过嵌套的 and/or 组合实现复杂查询。

规则结构

interface Rule<T = any, K extends keyof T = keyof T> {
field: K; // 字段名,支持关系字段(如 'user.name')
operator: OperatorName; // 操作符
value: any; // 值,不同操作符要求不同
}

interface RuleGroup<T = any> {
combinator: 'and' | 'or';
rules: Array<RuleGroup<T> | Rule<T>>; // 可递归嵌套
}

type OperatorName =
| '='
| '!='
| '<'
| '>'
| '<='
| '>='
| 'contains'
| 'notContain'
| 'beginWith'
| 'notBeginWith'
| 'endWith'
| 'notEndWith'
| 'in'
| 'notIn'
| 'between'
| 'notBetween';

说明:判断 null/not null 请使用 operator: '=' | '!='value: null,底层会自动生成 IS NULL/IS NOT NULL

操作符说明

  • 比较类:=, !=, <, >, <=, >=(适用于 string/number/integer/date/boolean 等)
  • 集合类:in, notIn(值为数组)
  • 区间类:between, notBetween(值为 [min, max]
  • 字符串:contains/notContainbeginWith/notBeginWithendWith/notEndWith
  • JSON/数组(stringArray/numberArray/keyValue):contains/notContain(匹配简单包含)

基础示例

// 未完成且标题包含 keyword 的任务
const where = {
combinator: 'and',
rules: [
{ field: 'completed', operator: '=', value: false },
{ field: 'title', operator: 'contains', value: keyword }
]
} as const;

复杂嵌套示例

// (未完成 AND (高优先级 OR 24 小时内到期))
const where = {
combinator: 'and',
rules: [
{ field: 'completed', operator: '=', value: false },
{
combinator: 'or',
rules: [
{ field: 'priority', operator: '=', value: 'high' },
{ field: 'dueDate', operator: '<=', value: new Date(Date.now() + 86400000) }
]
}
]
} as const;

关系字段查询

关系字段可以通过点语法访问,例如 owner.name, parent.title,甚至多级关系:order.owner.idCard.no。底层会自动生成所需的 JOIN。

// 查询拥有者姓名以 A 开头的 Todo
const where = {
combinator: 'and',
rules: [{ field: 'owner.name', operator: 'beginWith', value: 'A' }]
};

null 判断

// 父节点为空(根节点)
{ field: 'parentId', operator: '=', value: null }

// 邮箱非空
{ field: 'email', operator: '!=', value: null }

注意事项与最佳实践

  • 值类型要与字段类型匹配(如 date 使用 Date 或 ISO 字符串)
  • 大量 offset 分页可能较慢,优先使用 findByCursor
  • 对经常查询/排序的字段建立索引(或设为唯一)
  • 关系字段深度过深会增加 JOIN 成本,适度使用

参考