Elasticsearch 客户端 for JavaScript (Node.js) — @elastic/elasticsearch
Elasticsearch 是一个基于 Apache Lucene 构建的强大分布式搜索和分析系统。它支持实时全文搜索、数据聚合和日志分析。对于 Node.js 应用程序,官方客户端 @elastic/elasticsearch 提供了与 Elasticsearch 交互的便捷 API,涵盖从集群连接到复杂搜索查询的所有操作。
该库完全支持 Elasticsearch 7.x 和 8.x 的所有版本,基于 Promise 异步运行,非常适合构建高负载的搜索、分析和监控服务。本文将介绍 Node.js 环境下的安装、基本配置以及主要数据操作。
安装与连接
通过 npm 包管理器安装客户端:
npm install @elastic/elasticsearch安装后,需要创建客户端实例,指定 Elasticsearch 服务器地址,并根据需要配置认证参数:
const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200', auth: { username: 'elastic', password: 'changeme' }});对于 Elastic Cloud 云服务,可使用 cloud.id 和 auth.apiKey 参数。
索引操作
Elasticsearch 中的索引类似于关系型数据库中的数据库。以下是基本操作。
创建索引
async function createIndex() { const response = await client.indices.create({ index: 'products', body: { settings: { number_of_shards: 1, number_of_replicas: 1 }, mappings: { properties: { title: { type: 'text' }, description: { type: 'text' }, price: { type: 'float' }, created_at: { type: 'date' } } } } }); console.log('索引已创建:', response);}删除索引
async function deleteIndex() { await client.indices.delete({ index: 'products' }); console.log('索引已删除');}添加与更新文档
文档是 Elasticsearch 中的基本数据单元。以下示例向 products 索引添加几条记录:
async function addDocuments() { const doc1 = { title: 'Apple MacBook Pro 笔记本电脑', description: '为开发者和设计师打造的强大笔记本电脑', price: 2499.99, created_at: new Date() };
const doc2 = { title: 'Logitech 机械键盘', description: '带背光的无线键盘', price: 149.99, created_at: new Date() };
// 指定 ID 添加 await client.index({ index: 'products', id: '1', body: doc1 });
// 不指定 ID(自动生成) await client.index({ index: 'products', body: doc2 });
// 强制刷新到磁盘 await client.indices.refresh({ index: 'products' });}使用 update 方法进行部分更新:
await client.update({ index: 'products', id: '1', body: { doc: { price: 2399.99 } }});数据搜索
Elasticsearch 提供了强大的 DSL 用于构建查询。以下是几个示例。
全文搜索
async function searchProducts(query) { const response = await client.search({ index: 'products', body: { query: { match: { description: query } } } });
console.log('找到文档数:', response.hits.total.value); response.hits.hits.forEach