Elasticsearch 的 TypeScript 客户端:@elastic/elasticsearch

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Elasticsearch 的 TypeScript 客户端:@elastic/elasticsearch



@elastic/elasticsearch 库是与 Elasticsearch 搜索引擎进行交互的官方且最全面的客户端,适用于 TypeScript 和 JavaScript 应用程序。它提供了便捷的 API 来执行所有基本操作:索引、搜索、更新、删除数据,以及集群管理和执行复杂聚合。得益于对 TypeScript 的全面支持,开发者可以获得严格的类型检查、IDE 中的自动补全功能,并在编译阶段减少错误。



安装

要安装客户端,请在终端中执行以下命令:

npm install @elastic/elasticsearch

此外,如果您在 Node 环境中工作,建议安装 Node.js 的类型定义:

npm install -D @types/node


基本连接配置

创建一个客户端实例,并指定您的 Elasticsearch 服务器 URL。默认端口为 9200。

import { Client } from '@elastic/elasticsearch';

const client = new Client({ node: 'http://localhost:9200', // 对于云集群,请使用 cloud: { id: '...' } // auth: { apiKey: '...' } 或 { username: '...', password: '...' }});


响应类型化

TypeScript 的主要优势之一是可以对文档进行类型化。客户端支持泛型,从而可以严格定义数据结构:

interface Book {  title: string;  author: string;  year: number;  isbn: string;  rating?: number; // 可选字段}

// 现在,所有针对 'books' 索引的操作都将具有类型async function addBook(book: Book) { const result = await client.index<Book>({ index: 'books', document: book, }); return result;}


CRUD 操作

创建/索引文档

const book: Book = {  title: '战争与和平',  author: '列夫·托尔斯泰',  year: 1869,  isbn: '978-5-17-123456-7',};

const response = await client.index({ index: 'books', id: '1', // 可选,如果不指定,Elasticsearch 将生成 ID document: book,});console.log('文档已索引:', response._id);


根据 ID 获取文档

const getResponse = await client.get({  index: 'books',  id: '1',});console.log('找到文档:', getResponse._source); // 类型为 Book


更新文档

await client.update({  index: 'books',  id: '1',  doc: {    rating: 4.8, // 部分更新  },});


删除文档

await client.delete({  index: 'books',  id: '1',});


数据搜索

用于全文搜索的主要方法是 search。它接受 Elasticsearch 的 Query DSL(领域特定语言)。

interface SearchResult {  hits: {    total: { value: number };    hits: Array<{ _source: Book }>;  };}

async function searchBooks(query: string) { const result = await client.search<SearchResult>({ index: 'books', query: { multi_match: { query: query, fields: ['title', 'author'], // 多字段搜索 }, }, });

const books = result.hits.hits.map(hit => hit._source); return books;}

// 使用示例const books = await searchBooks('托尔斯泰');console.log(books); // Book 对象数组


聚合

聚合允许您获取索引的统计数据,例如按年份统计书籍数量。

async function getBooksByYear() {  const result = await client.search({    index: 'books',    size: 0, // 不返回文档本身,只返回聚合结果    aggs: {      books_per_year: {        terms: { field: 'year' },      },    },                    

推荐