Elasticsearch 客户端 for Node.js (@elastic/elasticsearch)
@elastic/elasticsearch 库是官方的高性能 HTTP 客户端,用于从 Node.js 环境与 Elasticsearch 进行交互。它提供了便捷的 API 来执行所有操作:从简单的文档索引到复杂的搜索查询和聚合。该库完全支持 Elasticsearch 7.x 和 8.x 的所有版本,包括集群操作、身份验证和数据压缩。
安装
使用 npm 或 yarn 进行安装:
npm install @elastic/elasticsearch# 或yarn add @elastic/elasticsearch基本连接
创建一个客户端实例,指定 Elasticsearch 服务器的地址。对于 8.x 版本,需要配置 TLS 以及 API 密钥或用户名/密码。
const { Client } = require('@elastic/elasticsearch');
// 连接到本地服务器 (Elasticsearch 7.x)const client = new Client({ node: 'http://localhost:9200' });
// 连接到 Elastic Cloud 云服务器 (8.x)const cloudClient = new Client({ cloud: { id: 'my-cloud-id' }, auth: { apiKey: 'base64EncodedApiKey' }});基本操作
1. 索引(添加)文档
index 方法用于在指定索引中添加或替换文档。
async function indexDocument() { const result = await client.index({ index: 'articles', id: '1', body: { title: 'Elasticsearch 客户端 for Node.js', content: '库的详细说明...', tags: ['elasticsearch', 'node.js'], published: true, views: 150 } }); console.log('文档已索引:', result.result);}indexDocument();2. 搜索文档
search 方法使用 Query DSL 执行全文搜索。
async function searchDocuments() { const { body } = await client.search({ index: 'articles', body: { query: { bool: { must: [ { match: { title: 'Elasticsearch' } }, { term: { published: true } } ], filter: [ { range: { views: { gte: 100 } } } ] } } } });
console.log('找到的文档数:', body.hits.total.value); body.hits.hits.forEach(hit => { console.log(`- ${hit._source.title} (相关性: ${hit._score})`); });}searchDocuments();3. 根据 ID 获取文档
async function getDocument() { try { const { body } = await client.get({ index: 'articles', id: '1' }); console.log('文档:', body._source); } catch (error) { if (error.meta.statusCode === 404) { console.log('未找到文档'); } else { console.error('错误:', error); } }}getDocument();4. 更新文档(部分更新)
async function updateDocument() { const { body } = await client.update({ index: 'articles', id: '1', body: { doc: { views: 151, updated_at: new Date().toISOString() } } }); console.log('文档已更新,版本:', body._version);}updateDocument();5. 删除文档
async function deleteDocument() { const { body } = await client.delete({ index: 'articles', id: '1' }); console.log('删除结果:', body.result);}deleteDocument();使用聚合
聚合允许您获取搜索结果的统计数据。
async function aggregateByTags() { const { body } = await client.search({ index: 'articles', body: { size: 0, // 不返回文档本身 aggs: { popular_tags: { terms: { field: 'tags.keywor