一、 连接(Connecting)
本页包含使用官方 Node.js 客户端连接并操作 Elasticsearch 所需的信息。
二、认证(Authentication)
下面的代码片段展示了如何连接不同的 Elasticsearch 部署与提供商。
三、Elastic Cloud
使用 Elastic Cloud 时,客户端提供了便捷的 cloud
选项。你需要在 Cloud 控制台找到 Cloud ID ,并在 auth
中提供用户名与密码。
注意
连接到 Elastic Cloud 时,客户端会默认启用请求与响应压缩 ,以获得显著吞吐提升;并会将
tls.secureProtocol
默认设为TLSv1_2_method
(除非你显式覆盖)。
重要
不要启用 sniffing。Elastic Cloud 的节点位于负载均衡器之后,Cloud 会自动处理节点发现与连接,你无需干预。
js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { username: 'elastic', password: 'changeme' }
})
3.1. 连接 Elastic Cloud Serverless 实例
Node.js 客户端对 Elastic Cloud Serverless 提供了专门支持。将 serverMode
设为 "serverless"
后,客户端会调整若干默认选项以更适配无服务器环境。
js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { username: 'elastic', password: 'changeme' },
serverMode: 'serverless'
})
四、连接自管(Self-managed)集群
默认情况下,Elasticsearch 启动时会开启安全特性(认证与 TLS)。要成功连接,你需要在 Node.js 客户端中使用 HTTPS ,并配置由 Elasticsearch 生成的 CA 证书。
首次启动 Elasticsearch 时,日志会输出类似下述信息(可能需要回滚查看):
-> Elasticsearch security features have been automatically configured!
-> Authentication is enabled and cluster connections are encrypted.
-> Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
lhQpLELkjkrawaBoaz0Q
-> HTTP CA certificate SHA-256 fingerprint:
a52dd93511e8c6045e21f16654b77c9ee0f34aea26d9f40320b531c474676228
...
根据环境与权限,你可以用两种方式 校验 HTTPS 连接:直接使用 CA 证书 ,或使用 CA 指纹(fingerprint)。
4.1. TLS 配置(使用 CA 证书)
生成的根 CA 证书位于 $ES_CONF_PATH/certs/http_ca.crt
。在 Docker 中运行时,请参见官方文档以获取该证书。
在最基础配置下,只要 URL 用 https://
,客户端就会验证服务端证书链。若想关闭证书校验,可在顶层配置传入 tls
并设置 rejectUnauthorized: false
(仅测试环境使用 )。tls
的默认值与 Node.js tls.connect()
保持一致。
js
const fs = require('node:fs')
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: { username: 'elastic', password: 'changeme' },
tls: {
ca: fs.readFileSync('./http_ca.crt'),
rejectUnauthorized: false
}
})
4.2. CA 指纹(CA fingerprint / pinning)
如果无法或不便直接分发 CA 文件,可以通过 CA 指纹固定 (pinning):提供签发服务器证书的 CA 证书 SHA-256 指纹,客户端将对服务端证书链进行指纹匹配校验。
js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://example.com',
auth: { /* ... */ },
// 用于签发服务端证书的 CA 证书的 SHA256 指纹
caFingerprint: '20:0D:CA:FA:76:...',
tls: {
// 自签场景可能需要
rejectUnauthorized: false
}
})
计算指纹(已持有 CA 文件):
bash
openssl x509 -fingerprint -sha256 -noout -in /path/to/http_ca.crt
未持有 CA 文件时,可用 openssl s_client
拉取并计算根 CA 指纹(替换主机与端口):
bash
openssl s_client -connect localhost:9200 -servername localhost -showcerts </dev/null 2>/dev/null \
| openssl x509 -fingerprint -sha256 -noout -in /dev/stdin
输出示例:
SHA256 Fingerprint=A5:2D:D9:35:11:E8:C6:04:5E:21:F1:66:54:B7:7C:9E:E0:F3:4A:EA:26:D9:F4:03:20:B5:31:C4:74:67:62:28
4.3. 在未启用安全功能时连接
警告
强烈不建议在生产环境关闭安全特性。
若集群明确关闭了安全功能,可直接通过 HTTP 连接:
js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://example.com' })
五、认证方式(Authentication strategies)
5.1.API Key
在 auth
中提供 apiKey
。它可以是 base64 字符串 ,也可以是包含 id
与 api_key
的对象(可通过 create api key
接口获取)。
若同时提供 Basic 与 ApiKey ,ApiKey 会优先生效。
js
// base64
const client = new Client({
node: 'https://localhost:9200',
auth: { apiKey: 'base64EncodedKey' }
})
// 对象
const client2 = new Client({
node: 'https://localhost:9200',
auth: { apiKey: { id: 'foo', api_key: 'bar' } }
})
5.2.Bearer
在 auth.bearer
传入 Bearer Token (常用于服务账号令牌)。该客户端不负责自动刷新 Token。
js
const client = new Client({
node: 'https://localhost:9200',
auth: { bearer: 'token' }
})
5.3.Basic
在 auth
中传入 username/password
,或直接将凭据写入 node
URL。
若同时提供 Basic 与 ApiKey ,ApiKey 会优先生效。
js
// 方式一:auth
const client = new Client({
node: 'https://localhost:9200',
auth: { username: 'elastic', password: 'changeme' }
})
// 方式二:URL 内联
const client2 = new Client({
node: 'https://username:password@localhost:9200'
})
六、用法(Usage)
客户端覆盖 Elasticsearch 的所有公开 API,方法签名与 REST 一致。
js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const result = await client.search({
index: 'my-index',
query: { match: { hello: 'world' } }
})
默认返回 响应体(body) 。如需状态码、响应头等元数据,在第二个参数 传 { meta: true }
:
js
const result = await client.search(
{ index: 'my-index', query: { match: { hello: 'world' } } },
{ meta: true }
)
// 结构:
/*
{
body: object | boolean, // HEAD 接口时为 boolean
statusCode: number,
headers: object,
warnings: string[],
meta: object
}
*/
七、取消请求(Aborting a request)
可使用 AbortController 取消进行中的请求。被取消的请求会以 RequestAbortedError 失败。
js
// Node 18+ 内置 AbortController;若更老版本可使用 node-abort-controller
const AbortController = require('node-abort-controller')
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ cloud: { id: '<cloud-id>' }, auth: { apiKey: 'base64EncodedKey' } })
const abortController = new AbortController()
setImmediate(() => abortController.abort())
const result = await client.search(
{ index: 'my-index', query: { match: { hello: 'world' } } },
{ signal: abortController.signal }
)
八、每次请求的专用选项(Request specific options)
可在第二个参数传入仅对本次请求生效的选项:
js
const result = await client.search(
{ index: 'my-index', body: { query: { match: { hello: 'world' } } } },
{ ignore: [404], maxRetries: 3 }
)
选项 | 说明 | 默认值 |
---|---|---|
ignore |
number[] ;把这些 HTTP 状态视为非错误 |
null |
requestTimeout |
number /string ;本次请求的超时时间(毫秒),覆盖客户端默认(默认无超时) |
无超时 |
retryOnTimeout |
boolean ;对超时进行重试 |
false |
maxRetries |
number ;本次请求的最大重试次数(覆盖客户端默认) |
3 |
compression |
string /boolean ;启用请求体压缩,false 或 'gzip' |
false |
asStream |
boolean ;返回原始 Node.js 流而非已解析的 body |
false |
headers |
object ;自定义请求头 |
null |
querystring |
object ;自定义查询串 |
null |
id |
any ;自定义请求 ID(覆盖顶层生成器) |
null |
context |
any ;自定义对象,可用于在事件中携带数据 |
null |
opaqueId |
string ;设置 X-Opaque-Id 请求头 |
null |
maxResponseSize |
number ;校验未压缩 响应大小,超过即中止(上限受 buffer.constants.MAX_STRING_LENGTH 限制) |
null |
maxCompressedResponseSize |
number ;校验压缩后 响应大小(上限受 buffer.constants.MAX_LENGTH 限制) |
null |
signal |
AbortSignal ;用于取消请求 |
null |
meta |
boolean ;返回包含 body/statusCode/headers/meta 的对象 |
false |
redaction |
object ;错误元数据的敏感信息脱敏选项 |
--- |
retryBackoff |
(min, max, attempt) => number ;自定义重试退避(单位秒) |
内置指数退避 + 抖动 |
九、在 FaaS(函数计算)环境中使用
最佳实践:在函数外部(全局作用域)初始化客户端,以便复用连接、启用后台能力(如 sniffing),并提升性能。
GCP Cloud Functions
js
'use strict'
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ /* init */ })
exports.testFunction = async (req, res) => {
// use client
}
AWS Lambda
js
'use strict'
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ /* init */ })
exports.handler = async (event, context) => {
// use client
}
Azure Functions
js
'use strict'
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ /* init */ })
module.exports = async function (context, req) {
// use client
}
十、通过代理连接(Proxy)
自 v8.0+ 起,客户端默认使用 UndiciConnection ,不支持 代理配置。若需代理,请使用
@elastic/transport
提供的 HttpConnection。
js
import { Client } from '@elastic/elasticsearch'
import { HttpConnection } from '@elastic/transport'
const client = new Client({
node: 'http://localhost:9200',
proxy: 'http://localhost:8080',
Connection: HttpConnection
})
Basic 认证的代理:
js
const client = new Client({
node: 'http://localhost:9200',
proxy: 'http://user:pwd@localhost:8080',
Connection: HttpConnection
})
非 http(s) 代理(如 socks5/pac) :通过 agent
自定义。
js
const SocksProxyAgent = require('socks-proxy-agent')
const client = new Client({
node: 'http://localhost:9200',
agent () { return new SocksProxyAgent('socks://127.0.0.1:1080') },
Connection: HttpConnection
})
十一、错误处理(Error handling)
客户端暴露了一组错误类型(require('@elastic/elasticsearch').errors
),可用于增强你的错误分流与告警。
错误类型 | 说明 | 主要属性 |
---|---|---|
ElasticsearchClientError |
所有错误的基类 | name , message |
TimeoutError |
超过 requestTimeout |
name , message , meta |
ConnectionError |
连接或数据流错误 | name , message , meta |
RequestAbortedError |
主动中止请求 | name , message , meta |
NoLivingConnectionsError |
连接池找不到可用连接 | name , message , meta |
SerializationError |
序列化失败 | name , message , data |
DeserializationError |
反序列化失败 | name , message , data |
ConfigurationError |
配置或参数错误 | name , message |
ResponseError |
收到 4xx/5xx | name , message , meta , body , statusCode , headers |
十二、Keep-Alive(持久连接)
默认使用持久连接以减少每次请求的建连开销:
- UndiciConnection(默认) :连接池大小 256,keep-alive 10 分钟。
- HttpConnection(旧实现) :连接池大小 256,keep-alive 1 分钟。
如需禁用 keep-alive,可自定义或禁用 HTTP agent:
js
// 自定义 agent
const client = new Client({
node: 'http://localhost:9200',
agent: (opts) => new CustomAgent()
})
// 完全禁用 agent(同时禁用 keep-alive)
const client2 = new Client({
node: 'http://localhost:9200',
agent: false
})
12.1.关闭连接
需要主动关闭当前客户端管理的所有连接时,调用 close()
:
js
const client = new Client({ node: 'http://localhost:9200' })
client.close()
十三、自动产品检查(Automatic product check)
自 v7.14.0 起,客户端在首次调用前 会进行一次产品检查,以确认目标 Elasticsearch 版本。该预检会在首个 API 调用前额外发送一次 HTTP 请求;检查完成后,后续调用不会重复发送此请求。