@elastic/elasticsearch 是 Elastic 官方推出的新一代 Node.js 客户端,专为现代异步编程设计,全面支持 Promise 和 async/await,并提供了完整的 TypeScript 类型定义。它是目前官方唯一推荐用于新项目的版本,紧跟 Elasticsearch 服务端的更新节奏。
elasticsearch 是该生态的旧版官方客户端(通常指 16.x 及更早版本)。它主要基于回调函数(Callback)模式设计,虽然社区曾通过封装使其支持 Promise,但其核心架构已不再适应现代 Node.js 开发标准。该包已进入维护模式(Maintenance Mode),官方明确建议所有新用户迁移至 @elastic/elasticsearch。
在 Node.js 生态中连接 Elasticsearch 时,开发者常面临两个包的选择:@elastic/elasticsearch 和 elasticsearch。这不仅仅是版本号的差异,而是两种截然不同的编程范式和维护状态的对抗。作为架构师,理解这两者的底层区别对于构建稳定、可维护的后端服务至关重要。
这是两者最根本的区别,直接决定了你的代码风格和维护成本。
@elastic/elasticsearch 是专为现代 JavaScript 设计的。它原生返回 Promise,完美契合 async/await 语法。这意味着你的代码可以是线性的、易读的,并且错误处理可以通过标准的 try/catch 块完成,无需陷入“回调地狱”。
// @elastic/elasticsearch: 原生 Promise 支持
const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });
async function searchDocs() {
try {
const result = await client.search({
index: 'products',
body: { query: { match: { name: 'laptop' } } }
});
console.log(result.hits.hits);
} catch (error) {
console.error('Search failed:', error);
}
}
elasticsearch (旧版) 设计于 Promise 普及之前,核心 API 基于回调函数。虽然可以通过 util.promisify 或第三方库进行封装,但这增加了代码的复杂性和出错概率。原生写法需要嵌套回调,导致逻辑支离破碎。
// elasticsearch (旧版): 基于回调
const { Client } = require('elasticsearch');
const client = new Client({ host: 'http://localhost:9200' });
function searchDocs() {
client.search({
index: 'products',
body: { query: { match: { name: 'laptop' } } }
}, function (error, response) {
if (error) {
console.error('Search failed:', error);
return;
}
console.log(response.hits.hits);
});
}
在现代前端和全栈开发中,类型安全是架构稳健性的基石。
@elastic/elasticsearch 是用 TypeScript 重写的,或者至少提供了极其完善的类型定义文件。当你输入代码时,IDE 能自动提示 API 参数、响应结构以及具体的字段类型。如果 Elasticsearch 服务端更新了 API,客户端类型也会随之更新,编译器会帮你拦截不兼容的调用。
// @elastic/elasticsearch: 完整的类型推断
import { Client, SearchRequest } from '@elastic/elasticsearch';
const client = new Client({ node: 'http://localhost:9200' });
// TS 会检查 'index' 和 'body' 的结构,错误会在编译时报出
const req: SearchRequest = {
index: 'products',
body: { query: { match: { name: 'laptop' } } }
};
// result 对象具有明确的类型结构
const result = await client.search(req);
// @ts-expect-error: hits 属性存在,但 total 结构在 v8 中有变化,TS 会提示
console.log(result.hits.total.value);
elasticsearch 缺乏官方的现代类型定义。虽然社区有 @types/elasticsearch,但它们往往更新滞后,无法覆盖所有 API,且对复杂嵌套结构的推断能力较弱。在大型项目中,这意味著你失去了编译期的安全保障,必须依赖大量的运行时测试来发现接口变更带来的问题。
// elasticsearch (旧版): 类型支持薄弱
import * as ES from 'elasticsearch';
// 往往需要任何类型断言,或者忍受不准确的类型提示
const client = new ES.Client({ /* ... */ });
// 这里的 response 结构主要靠文档记忆,TS 无法精确提示
client.search({ /* ... */ }, (err, response) => {
// 容易因字段名拼写错误导致运行时崩溃
console.log(response.hits.total);
});
随着 Elasticsearch 安全特性的增强,客户端的认证方式也发生了巨大变化。
@elastic/elasticsearch 原生支持现代认证机制,包括 API Keys(推荐)、Bearer Token 以及基本的用户名密码认证。配置简洁且安全,特别是 API Key 方式,避免了在代码中硬编码敏感密码的风险。
// @elastic/elasticsearch: 支持 API Key 认证
const client = new Client({
node: 'https://localhost:9200',
auth: {
apiKey: {
id: 'my_api_key_id',
api_key: 'my_api_key_secret'
}
},
tls: { rejectUnauthorized: false } // 开发环境示例
});
elasticsearch 对新版安全特性的支持非常有限。虽然可以通过 HTTP 头手动注入 Token,但这需要开发者自行处理编码和刷新逻辑,容易出错。它主要设计用于较旧版本的 Elasticsearch,对于 ES 8.x 强制启用的安全特性,配置起来非常繁琐且容易踩坑。
// elasticsearch (旧版): 手动处理认证头
const client = new ES.Client({
host: 'https://localhost:9200',
// 旧版没有原生的 apiKey 配置项,需手动设置 headers
requestTimeout: 30000,
headers: {
authorization: "ApiKey " + Buffer.from("id:key").toString('base64')
}
});
这是做架构决策时最关键的非功能性指标。
@elastic/elasticsearch 是官方 actively maintained(积极维护)的版本。Elastic 团队确保它与每一个 Elasticsearch 服务端版本(7.x, 8.x 及未来版本)保持同步。当你升级数据库时,客户端能立即支持新 API(如 ESQL、新的向量搜索功能等)。
elasticsearch 已被官方标记为 Maintenance Mode(维护模式)。这意味着它不会再有新功能加入,只会修复严重的安全漏洞。官方文档已明确指出:“The old client is in maintenance mode. We recommend using the new client.”(旧客户端处于维护模式,我们推荐使用新客户端)。
继续使用旧版客户端意味着:
| 特性 | @elastic/elasticsearch (新版) | elasticsearch (旧版) |
|---|---|---|
| 编程模型 | 原生 Promise / async-await | 回调函数 (Callback) |
| TypeScript 支持 | ✅ 官方完整类型定义 | ⚠️ 社区维护,滞后且不全 |
| 认证方式 | 原生支持 API Key, Bearer, Basic | 需手动构造 Header |
| 维护状态 | 🟢 积极开发,紧跟 ES 版本 | 🟡 维护模式,无新功能 |
| ES 8.x 支持 | ✅ 完美支持 | ❌ 支持有限或不支持 |
| 代码可读性 | 高 (线性逻辑) | 低 (嵌套回调) |
毫不犹豫地选择 @elastic/elasticsearch。
在任何新项目中,旧版 elasticsearch 都不再是一个可接受的选项。它代表的是一种过时的开发模式,会给团队带来不必要的技术债务。新版客户端不仅让代码更简洁、更安全,还确保了你的应用能够平滑演进到未来的 Elasticsearch 版本。
如果你正在维护一个使用旧版客户端的遗留系统,建议制定一个渐进式重构计划:
@elastic/elasticsearch。技术选型不仅是选工具,更是选未来。@elastic/elasticsearch 才是通往未来的正确路径。
如果你正在启动一个新项目,或者希望代码库保持现代标准,必须选择 @elastic/elasticsearch。它原生支持 async/await,拥有完美的 TypeScript 类型支持,能显著减少运行时错误并提升开发体验。此外,只有新版客户端才能完整支持 Elasticsearch 8.x 引入的新特性(如 API 密钥认证、新的聚合语法等)。
仅当你在维护一个无法轻易重构的遗留系统,且该系统深度依赖旧版客户端的特定回调模式或私有插件时,才考虑暂时保留 elasticsearch。对于任何新开发的功能模块,即便在旧项目中,也强烈建议引入 @elastic/elasticsearch 而非继续使用旧包,因为旧包已停止功能更新,存在安全和技术债务风险。
The official Node.js client for Elasticsearch.
If you want to try Elasticsearch and Kibana locally, you can run the following command:
curl -fsSL https://elastic.co/start-local | sh
This will run Elasticsearch at http://localhost:9200 and Kibana at http://localhost:5601.
More information is available here.
Alternatively, you can download the latest version of Elasticsearch manually, or sign-up for a free trial of Elastic Cloud.
Refer to the Installation section of the getting started documentation.
Refer to the Connecting section of the getting started documentation.
The Elasticsearch client is compatible with currently maintained JS versions.
Language clients are forward compatible; meaning that clients support communicating with greater or equal minor versions of Elasticsearch without breaking. It does not mean that the client automatically supports new features of newer Elasticsearch versions; it is only possible after a release of a new client version. For example, a 8.12 client version won't automatically support the new features of the 8.13 version of Elasticsearch, the 8.13 client version is required for that. Elasticsearch language clients are only backwards compatible with default distributions and without guarantees made.
| Elasticsearch Version | Elasticsearch-JS Branch |
|---|---|
| main | main |
| 9.x | 9.x |
| 8.x | 8.x |
| 7.x | 7.x |
NOTE: The minimum supported version of Node.js is v20.
The client versioning follows the Elastic Stack versioning, this means that major, minor, and patch releases are done following a precise schedule that often does not coincide with the Node.js release times.
To avoid support insecure and unsupported versions of Node.js, the client will drop the support of EOL versions of Node.js between minor releases. Typically, as soon as a Node.js version goes into EOL, the client will continue to support that version for at least another minor release. If you are using the client with a version of Node.js that will be unsupported soon, you will see a warning in your logs (the client will start logging the warning with two minors in advance).
Unless you are always using a supported version of Node.js,
we recommend defining the client dependency in your
package.json with the ~ instead of ^. In this way, you will lock the
dependency on the minor release and not the major. (for example, ~7.10.0 instead
of ^7.10.0).
| Node.js Version | Node.js EOL date | End of support |
|---|---|---|
8.x | December 2019 | 7.11 (early 2021) |
10.x | April 2021 | 7.12 (mid 2021) |
12.x | April 2022 | 8.2 (early 2022) |
14.x | April 2023 | 8.8 (early 2023) |
16.x | September 2023 | 8.11 (late 2023) |
18.x | April 2025 | 9.1 (mid 2025) |
[!WARNING] There is no official support for the browser environment. It exposes your Elasticsearch instance to everyone, which could lead to security issues. We recommend that you write a lightweight proxy that uses this client instead, you can see a proxy example here.
If you are using multiple versions of Elasticsearch, you need to use multiple versions of the client. In the past, install multiple versions of the same package was not possible, but with npm v6.9, you can do that via aliasing.
The command you must run to install different version of the client is:
npm install <alias>@npm:@elastic/elasticsearch@<version>
So for example if you need to install 7.x and 6.x, you will run:
npm install es6@npm:@elastic/elasticsearch@6
npm install es7@npm:@elastic/elasticsearch@7
And your package.json will look like the following:
"dependencies": {
"es6": "npm:@elastic/elasticsearch@^6.7.0",
"es7": "npm:@elastic/elasticsearch@^7.0.0"
}
You will require the packages from your code by using the alias you have defined.
const { Client: Client6 } = require('es6')
const { Client: Client7 } = require('es7')
const client6 = new Client6({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const client7 = new Client7({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
client6.info().then(console.log, console.log)
client7.info().then(console.log, console.log)
Finally, if you want to install the client for the next version of Elasticsearch (the one that lives in Elasticsearch’s main branch), you can use the following command:
npm install esmain@github:elastic/elasticsearch-js
This software is licensed under the Apache License 2.0.