Elasticsearch client for Node.js (@elastic/elasticsearch)
The @elastic/elasticsearch library is the official, high-performance HTTP client for interacting with Elasticsearch from the Node.js environment. It provides a convenient API for performing all operations: from simple document indexing to complex search queries and aggregations. The library fully supports all versions of Elasticsearch 7.x and 8.x, including working with clusters, authentication, and data compression.
Installation
Use npm or yarn to install:
npm install @elastic/elasticsearch# oryarn add @elastic/elasticsearchBasic Connection
Create a client instance by specifying the Elasticsearch server address. For version 8.x, TLS configuration and an API key or login/password are required.
const { Client } = require('@elastic/elasticsearch');
// Connecting to a local server (Elasticsearch 7.x)const client = new Client({ node: 'http://localhost:9200' });
// Connecting to an Elastic Cloud server (8.x)const cloudClient = new Client({ cloud: { id: 'my-cloud-id' }, auth: { apiKey: 'base64EncodedApiKey' }});Basic Operations
1. Indexing (adding) a document
The index method adds or replaces a document in the specified index.
async function indexDocument() { const result = await client.index({ index: 'articles', id: '1', body: { title: 'Elasticsearch client for Node.js', content: 'Detailed description of the library...', tags: ['elasticsearch', 'node.js'], published: true, views: 150 } }); console.log('Document indexed:', result.result);}indexDocument();2. Searching documents
The search method performs full-text search using 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('Documents found:', body.hits.total.value); body.hits.hits.forEach(hit => { console.log(`- ${hit._source.title} (relevance: ${hit._score})`); });}searchDocuments();3. Getting a document by ID
async function getDocument() { try { const { body } = await client.get({ index: 'articles', id: '1' }); console.log('Document:', body._source); } catch (error) { if (error.meta.statusCode === 404) { console.log('Document not found'); } else { console.error('Error:', error); } }}getDocument();4. Updating a document (partial)
async function updateDocument() { const { body } = await client.update({ index: 'articles', id: '1', body: { doc: { views: 151, updated_at: new Date().toISOString() } } }); console.log('Document updated, version:', body._version);}updateDocument();5. Deleting a document
async function deleteDocument() { const { body } = await client.delete({ index: 'articles', id: '1' }); console.log('Deletion result:', body.result);}deleteDocument();Working with Aggregations
Aggregations allow you to obtain statistical data based on search results.
async function aggregateByTags() { const { body } = await client.search({ index: 'articles', body: { size: 0, // do not return the documents themselves aggs: { popular_tags: { terms: { field: 'tags.keywor