#Elasticsearch
oor 的 ES 支持分两层:oor/native/es 是带 client 的 Table / View,oor/es 是免连接的纯 DSL 构建器。两者共享同一套查询 DSL。
#Native ES(oor/native/es)
TypeScript
import { z } from 'zod'
import { Client } from '@elastic/elasticsearch'
import { TABLE, VIEW } from 'oor/native/es'
const client = new Client({ node: process.env.ES_URL })
const EsUserSchema = z.object({
id: z.string(),
name: z.string(),
age: z.number()
})
const User = TABLE(client, 'users', EsUserSchema, {
rowKey: 'id',
columns: {
id: { type: 'string' },
name: { column: 'user_name', type: 'string' },
age: { type: 'number' }
}
})
await User.insert({ id: '1', name: 'ada', age: 20 })
const list = await User.query({ nameILike: 'ADA' })
- 方法与 SQL 系入口一致(
query/queryPagination/getById/insert/deleteByQuery…)。 - client 由你创建和管理;也可以传
() => client工厂。 - VIEW 不要求 rowKey;
getById在没有 rowKey 也没有client.get时才报错。
#免连接 DSL 构建器(oor/es)
oor/es 不导出 TABLE/VIEW,不接触 client,只返回 DSL / SearchRequest:
TypeScript
import { searchRequest, whereQuery } from 'oor/es'
const request = searchRequest('users', {
nameLike: 'ada',
ageGte: 18,
_pagition: { page: 1, size: 20, order: 'age', by: 'desc' }
}, {
map: {
name: { column: 'user_name', type: 'string' },
age: { column: 'age', type: 'number' }
}
})
const result = await client.search(request)
options.map 的格式与 oor/sql 的 columns 相同:实体字段名 → { column, type }。
#函数一览
| 函数 | 说明 |
|---|---|
where(whereParam, options?) | WhereParam → Query DSL |
whereQuery(queryParam, options?) | 魔法后缀 → Query DSL |
search(queryParam, options?) | Query DSL + sort + from/size |
searchRequest(index, queryParam, options?) | 完整 SearchRequest |
searchWhere(whereParam, page?, options?) | WhereParam 版 search |
searchWhereRequest(index, whereParam, page?, options?) | WhereParam 版完整 SearchRequest |
buildSearch(index, dslQuery, order?, sourceExcludes?, globalFilter?) | 用已有 DSL query 组装请求 |
fixQuery(globalFilter?, dslQuery?) | 合并全局过滤条件 |
sort(queryParam, options?) | 只生成 sort |
#DSL 映射规则
魔法后缀编译为 ES 查询的大致对应关系:
| 后缀 / op | ES 查询 |
|---|---|
等值 / In | term / terms |
Gt Gte Lt Lte Bt | range |
Like 系 | match / wildcard(按模式) |
IsNull / NotNull | bool.must_not.exists / exists |
| WhereParam 嵌套 | bool.must / should |
BtD / BtM / BtY 等日期后缀同样有效,值先按 UTC 扩展成区间再进入 range。