Elasticsearch 客户端 for TypeScript (@elastic/elasticsearch)
在现代 Web 开发中,全文搜索和数据分析已成为许多应用程序不可或缺的一部分。Elasticsearch 是一个基于 Apache Lucene 构建的强大分布式搜索引擎。为了在 TypeScript 应用程序(无论是在 Node.js 服务器端还是浏览器中)中使用它,官方提供了 @elastic/elasticsearch 客户端。本文将详细介绍其安装、配置和主要功能。
什么是 @elastic/elasticsearch?
@elastic/elasticsearch 是官方的高性能 Elasticsearch 客户端,使用 TypeScript 编写。它提供了与 Elasticsearch 集群交互的完整 API 集合,包括:
- 文档的索引和删除
- 支持复杂查询的全文搜索
- 用于数据分析的聚合(分组、统计)
- 索引和映射管理
- 连接池、重试和负载均衡支持
得益于对 TypeScript 的全面支持,您可以在 IDE 中获得自动补全、类型检查和文档提示。
安装
首先,通过 npm 或 yarn 安装该包:
npm install @elastic/elasticsearch# 或yarn add @elastic/elasticsearch如果您使用 TypeScript,无需额外安装类型定义——它们已内置于包中。
连接和配置客户端
创建一个客户端实例,指定您的 Elasticsearch 集群 URL:
import { Client } from '@elastic/elasticsearch';
const client = new Client({ node: 'http://localhost:9200', // 或云端点 auth: { username: 'elastic', password: 'changeme' }, // 生产环境建议使用 TLS tls: { rejectUnauthorized: false // 仅用于开发! }});对于云部署(Elastic Cloud),请使用 cloud.id 和 auth.apiKey:
const client = new Client({ cloud: { id: 'my-cluster:dXMtZWFzdD...' }, auth: { apiKey: 'base64EncodedApiKey' }});基本操作
1. 索引文档
向索引中添加新文档:
interface Product { id: number; name: string; description: string; price: number; tags: string[];}
async function indexProduct(product: Product) { const response = await client.index({ index: 'products', id: String(product.id), body: product, refresh: 'wait_for' // 等待索引刷新 }); console.log('Document indexed:', response.result);}
indexProduct({ id: 1, name: '联想 ThinkPad 笔记本电脑', description: '适合开发的高性能笔记本电脑', price: 1200, tags: ['电子产品', '笔记本电脑']});2. 搜索文档
对 description 字段进行简单的全文搜索:
async function searchProducts(query: string) { const response = await client.search({ index: 'products', body: { query: { match: { description: query } }, // 分页 from: 0, size: 10 } });
const hits = response.hits.hits.map(hit => hit._source); console.log('Found products:', hits); return hits;}
searchProducts('笔记本电脑 开发');3. 聚合
按标签对商品进行分组:
async function aggregateByTags() { const response = await client.search({ index: 'products', body: { size: 0, // 不返回文档本身 aggs: { by_tag: { terms: { field: 'tags.keyword', size: 20 } }