跳到主要内容

查询操作符

RxDB 使用统一的 RuleGroup 结构描述查询条件。

结构

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'
| 'notContains'
| 'startsWith'
| 'notStartsWith'
| 'endsWith'
| 'notEndsWith'
| 'in'
| 'notIn'
| 'between'
| 'notBetween'
| 'exists'
| 'notExists';
提示

判断 null: 使用 operator: '='value: null,底层生成 IS NULL

操作符

  • 比较: =, !=, <, >, <=, >=
  • 集合: in, notIn (值为数组)
  • 区间: between, notBetween (值为 [min, max])
  • 字符串: contains, startsWith, endsWith (及 not 版本)
  • 存在性: exists, notExists (用于关联子查询)

示例

基础

const where = {
combinator: 'and',
rules: [
{ field: 'completed', operator: '=', value: false },
{ field: 'title', operator: 'contains', value: keyword }
]
} as const;

嵌套

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;

关系字段

const where = {
combinator: 'and',
rules: [{ field: 'owner.name', operator: 'startsWith', value: 'A' }]
};

存在性查询

const where = {
combinator: 'and',
rules: [
{
field: 'children',
operator: 'exists',
value: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: true }]
}
}
]
};
const where = {
combinator: 'and',
rules: [
{
field: 'subTasks',
operator: 'exists',
where: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: true }]
}
}
]
};

// 查询没有任何子任务的任务
const where = {
combinator: 'and',
rules: [
{
field: 'subTasks',
operator: 'notExists'
}
]
};

null 判断

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

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

注意事项与最佳实践

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

参考