Elasticsearch client for TypeScript: @elastic/elasticsearch

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Elasticsearch client for TypeScript: @elastic/elasticsearch



The @elastic/elasticsearch library is the official and most comprehensive client for interacting with the Elasticsearch search engine from TypeScript and JavaScript applications. It provides a convenient API for performing all basic operations: indexing, searching, updating, deleting data, as well as cluster management and executing complex aggregations. Thanks to full TypeScript support, developers get strict typing, IDE autocompletion, and fewer errors at compile time.



Installation

To install the client, run the command in the terminal:

npm install @elastic/elasticsearch

Additionally, it is recommended to install types for Node.js if you are working in a Node environment:

npm install -D @types/node


Basic connection setup

Create a client instance by specifying the URL of your Elasticsearch server. Port 9200 is used by default.

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

const client = new Client({ node: 'http://localhost:9200', // For cloud clusters use cloud: { id: '...' } // auth: { apiKey: '...' } or { username: '...', password: '...' }});


Response typing

One of the main advantages of TypeScript is the ability to type documents. The client supports generics, allowing you to strictly define the data structure:

interface Book {  title: string;  author: string;  year: number;  isbn: string;  rating?: number; // optional field}

// Now all operations on the 'books' index will be typedasync function addBook(book: Book) { const result = await client.index<Book>({ index: 'books', document: book, }); return result;}


CRUD operations

Creating/indexing a document

const book: Book = {  title: 'War and Peace',  author: 'Leo Tolstoy',  year: 1869,  isbn: '978-5-17-123456-7',};

const response = await client.index({ index: 'books', id: '1', // optional, can be omitted — Elasticsearch will generate an ID document: book,});console.log('Document indexed:', response._id);


Getting a document by ID

const getResponse = await client.get({  index: 'books',  id: '1',});console.log('Found document:', getResponse._source); // typed as Book


Updating a document

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


Deleting a document

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


Data search

The main method for full-text search is search. It accepts Elasticsearch Query DSL (Domain Specific Language).

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'], // search across multiple fields }, }, });

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

// Usageconst books = await searchBooks('Tolstoy');console.log(books); // array of Book objects


Aggregations

Aggregations allow you to get statistical data on an index, for example, the number of books by year.

async function getBooksByYear() {  const result = await client.search({    index: 'books',    size: 0, // do not return the documents themselves, only aggregations    aggs: {      books_per_year: {        terms: { field: 'year' },      },    },                    

Recommendations