#ES Client
oor/native/es 与 oor/es 都不创建、不持有、不关闭 ES client。client 的生命周期完全由你的应用管理。
TypeScript
import { Client } from '@elastic/elasticsearch'
const client = new Client({ node: process.env.ES_URL })
// 鉴权、节点池、重试策略、关闭时机……全部由你决定
#交给 oor 的两种方式
#带 client 的 Table(oor/native/es)
TypeScript
import { TABLE } from 'oor/native/es'
// 1. 直接传 client
const User = TABLE(client, 'users', EsUserSchema, options)
// 2. 传工厂函数(可异步),每次操作前解析一次
const User = TABLE(() => client, 'users', EsUserSchema, options)
与 SQL 系 native 入口一致:批量操作(insertBatch / deleteByIds)只解析一次 provider,整个批次复用同一个 client。工厂应返回稳定的 client,避免单次操作内拿到不同实例。
#免连接构建器(oor/es)
oor/es 完全不接触 client,只返回 SearchRequest,由你交给 client 执行:
TypeScript
import { searchRequest } from 'oor/es'
const request = searchRequest('users', { ageGte: 18 })
const result = await client.search(request)
适合已有 client 封装(连接池、中间件、多集群路由)的项目:oor 只负责把查询 DSL 编译对,怎么发请求是你自己的事。
#getById 的 404 语义
getById 优先走 client 的 get API:
- 文档不存在时 ES 返回 404,oor 捕获后返回
null,不会把 404 抛给业务层; - client 没有
get方法时退化为按 rowKey 的条件查询,查不到同样返回null; - 既没有 rowKey 也没有
client.get时才抛错。
TypeScript
const user = await User.getById('not-exists')
// => null(而不是 ResponseError: 404)
这一行为与 SQL 系入口一致:getBy* 系列查不到一律返回 null。
#相关
- Elasticsearch:oor/native/es 与 oor/es 的能力总览
- PostgreSQL / MySQL:provider 传法与批量解析规则同样适用于 SQL 入口