elasticsearch-js Documentation

Official Elasticsearch client library for Node.js

5,300 stars TypeScript TypeScript 1 file Β· ~4,674 tokens #client#elasticsearch#javascript#nodejs#rest
RAW Doc

File: README.md

Elasticsearch Node.js client

The official Node.js client for Elasticsearch.

Try Elasticsearch and Kibana locally

If you want to try Elasticsearch and Kibana locally, you can run the following command:

bash
curl -fsSL https://elastic.co/start-local | sh

This will run Elasticsearch at http://localhost:9200 and Kibana at http://localhost:5601.

More information is available here.

Alternatively, you can download the latest version of Elasticsearch manually, or
sign-up for a free trial of Elastic Cloud.

Installation

Refer to the Installation section
of the getting started documentation.

Connecting

Refer to the Connecting section
of the getting started documentation.

Compatibility

The Elasticsearch client is compatible with currently maintained JS versions.

Language clients are forward compatible; meaning that clients support
communicating with greater or equal minor versions of Elasticsearch without
breaking. It does not mean that the client automatically supports new features
of newer Elasticsearch versions; it is only possible after a release of a new
client version. For example, a 8.12 client version won't automatically support
the new features of the 8.13 version of Elasticsearch, the 8.13 client version
is required for that. Elasticsearch language clients are only backwards
compatible with default distributions and without guarantees made.

Elasticsearch Version Elasticsearch-JS Branch
main main
9.x 9.x
8.x 8.x
7.x 7.x

Usage

Node.js support

NOTE: The minimum supported version of Node.js is v20.

The client versioning follows the Elastic Stack versioning, this means that
major, minor, and patch releases are done following a precise schedule that
often does not coincide with the Node.js release times.

To avoid support insecure and unsupported versions of Node.js, the
client will drop the support of EOL versions of Node.js between minor releases.
Typically, as soon as a Node.js version goes into EOL, the client will continue
to support that version for at least another minor release. If you are using the client
with a version of Node.js that will be unsupported soon, you will see a warning
in your logs (the client will start logging the warning with two minors in advance).

Unless you are always using a supported version of Node.js,
we recommend defining the client dependency in your
package.json with the ~ instead of ^. In this way, you will lock the
dependency on the minor release and not the major. (for example, ~7.10.0 instead
of ^7.10.0).

Node.js Version Node.js EOL date End of support
8.x December 2019 7.11 (early 2021)
10.x April 2021 7.12 (mid 2021)
12.x April 2022 8.2 (early 2022)
14.x April 2023 8.8 (early 2023)
16.x September 2023 8.11 (late 2023)
18.x April 2025 9.1 (mid 2025)

Browser

[!WARNING]
There is no official support for the browser environment. It exposes your Elasticsearch instance to everyone, which could lead to security issues.
We recommend that you write a lightweight proxy that uses this client instead, you can see a proxy example here.

Documentation

Install multiple versions

If you are using multiple versions of Elasticsearch, you need to use multiple versions of the client. In the past, install multiple versions of the same package was not possible, but with npm v6.9, you can do that via aliasing.

The command you must run to install different version of the client is:

sh
npm install <alias>@npm:@elastic/elasticsearch@<version>

So for example if you need to install 7.x and 6.x, you will run:

sh
npm install es6@npm:@elastic/elasticsearch@6
npm install es7@npm:@elastic/elasticsearch@7

And your package.json will look like the following:

json
"dependencies": {
  "es6": "npm:@elastic/elasticsearch@^6.7.0",
  "es7": "npm:@elastic/elasticsearch@^7.0.0"
}

You will require the packages from your code by using the alias you have defined.

js
const { Client: Client6 } = require('es6')
const { Client: Client7 } = require('es7')

const client6 = new Client6({
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' }
})
const client7 = new Client7({
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' }
})

client6.info().then(console.log, console.log)
client7.info().then(console.log, console.log)

Finally, if you want to install the client for the next version of Elasticsearch
(the one that lives in Elasticsearch’s main branch), you can use the following
command:

sh
npm install esmain@github:elastic/elasticsearch-js

License

This software is licensed under the Apache License 2.0.


File: docs/examples/proxy/README.md

Elasticsearch proxy example

This folder contains an example of how to build a lightweight proxy
between your frontend code and Elasticsearch if you don't
have a more sophisticated backend in place yet.

IMPORTANT: This is not a production ready code and it is only for demonstration purposes,
we make no guarantees on it's security and stability.

This project is designed to be deployed on Vercel, a cloud platform
for static sites and Serverless Functions. You can use other functions providers,
such as Google Cloud functions.

Project structure

The project comes with four endpoints:

  • /api/search: runs a search, requires 'read' permission
  • /api/autocomplete: runs an autocomplete suggestion, requires 'read' permission
  • /api/index: indexes or updates a document, requires 'write' permission
  • /api/delete: deletes a document, requires 'write' permission

Inside utils/authorize.js you can find the authorization logic for the endpoints.
In each endpoint you should configure the INDEX variable.

How to use

Create an account on Vercel, then create a deployment on Elastic Cloud. If you
don't have an account on Elastic Cloud, you can create one with a free 14-day trial
of the Elasticsearch Service.

Configure Elasticsearch

Once you have created a deployment on Elastic Cloud copy the generated Cloud Id and the credentials.
Then open utils/prepare-elasticsearch.js and fill your credentials. The script generates
an Api Key
that you can use for authenticating your request. Based on the configuration of the Api Key, you will be able
to perform different operation on the specified indices or index pattern.

Configure Vercel

Install the Vercel CLI to bootstrap the project,
or read the quickstart documentation.

If you are using the CLI, bootstrap the project by running vercel. Test the project locally
with vercel dev, and deploy it with vercel deploy.
Configure the ELASTIC_CLOUD_ID environment varible as well.
The Api Key is passed from the frontend app via a Authorization header as Bearer token and is
used to authorize the API calls to the endpoints as well.
Additional configuration, such as CORS, can be added to vercel.json.

Authentication

If you are using Elasticsearch only for search purposes, such as a search box, you can create
an Api Key with read permissions and store it in your frontend app. Then you can send it
via Authorization header to the proxy and run your searches.

If you need to ingest data as well, it's more secure to have a strong authentication in your application.
For such cases, use an external authentication service, such as Auth0
or Magic Link. Then create a different Api Key with read and write
permissions for authenticated users, that will not be stored in the frontend app.

License

This software is licensed under the Apache 2 license.


File: docs/reference/advanced-config.md


mapped_pages:


Advanced configuration [advanced-config]

If you need to customize the client behavior heavily, you are in the right place! The client enables you to customize the following internals:

  • ConnectionPool class
  • Connection class
  • Serializer class

::::{note}
For information about the Transport class, refer to Transport.
::::

`ConnectionPool` [_connectionpool]

This class is responsible for keeping in memory all the {{es}} connections that you are using. There is a single Connection for every node. The connection pool handles the resurrection strategies and the updates of the pool.

js
const { Client, ConnectionPool } = require('@elastic/elasticsearch')

class MyConnectionPool extends ConnectionPool {
  markAlive (connection) {
    // your code
    super.markAlive(connection)
  }
}

const client = new Client({
  ConnectionPool: MyConnectionPool,
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' }
})

`Connection` [_connection]

This class represents a single node, it holds every information we have on the node, such as roles, id, URL, custom headers and so on. The actual HTTP request is performed here, this means that if you want to swap the default HTTP client (Undici Pool), you should override the request method of this class.

js
const { Client, BaseConnection } = require('@elastic/elasticsearch')

class MyConnection extends BaseConnection {
  request (params, callback) {
    // your code
  }
}

const client = new Client({
  Connection: MyConnection,
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' }
})

@elastic/transport provides two Connection implementations:

  • UndiciConnection: manages HTTP connections using Undici, Node.js's high-performance HTTP client implementation; this is the default value of Connection and is recommended unless you have a use case that is not yet supported by Undici or UndiciConnection
  • HttpConnection: manages HTTP connections using the http package from Node.js's standard library

`Serializer` [_serializer]

This class is responsible for the serialization of every request, it offers the following methods:

  • serialize(object: any): string; serializes request objects.
  • deserialize(json: string): any; deserializes response strings.
  • ndserialize(array: any[]): string; serializes bulk request objects.
  • qserialize(object: any): string; serializes request query parameters.
  • encodeFloat32Vector(floats: number[]): string; encodes a float array to base64 for efficient vector ingestion.
  • decodeFloat32Vector(base64: string): number[]; decodes a base64 string back to a float array.
js
const { Client, Serializer } = require('@elastic/elasticsearch')

class MySerializer extends Serializer {
  serialize (object) {
    // your code
  }
}

const client = new Client({
  Serializer: MySerializer,
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' }
})

Redaction of potentially sensitive data [redaction]

When the client raises an Error that originated at the HTTP layer, like a ConnectionError or TimeoutError, a meta object is often attached to the error object that includes metadata useful for debugging, like request and response information. Because this can include potentially sensitive data, like authentication secrets in an Authorization header, the client takes measures to redact common sources of sensitive data when this metadata is attached and serialized.

If your configuration requires extra headers or other configurations that may include sensitive data, you may want to adjust these settings to account for that.

By default, the redaction option is set to { type: 'replace' }, which recursively searches for sensitive key names, case insensitive, and replaces their values with the string [redacted].

js
const { Client } = require('@elastic/elasticsearch')

const client = new Client({
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' },
})

try {
  await client.indices.create({ index: 'my_index' })
} catch (err) {
  console.log(err.meta.meta.request.options.headers.authorization) // prints "[redacted]"
}

If you would like to redact additional properties, you can include additional key names to search and replace:

js
const { Client } = require('@elastic/elasticsearch')

const client = new Client({
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' },
  headers: { 'X-My-Secret-Password': 'shhh it's a secret!' },
  redaction: {
    type: "replace",
    additionalKeys: ["x-my-secret-password"]
  }
})

try {
  await client.indices.create({ index: 'my_index' })
} catch (err) {
  console.log(err.meta.meta.request.options.headers['X-My-Secret-Password']) // prints "[redacted]"
}

Alternatively, if you know you’re not going to use the metadata at all, setting the redaction type to remove will remove all optional sources of potentially sensitive data entirely, or replacing them with null for required properties.

js
const { Client } = require('@elastic/elasticsearch')

const client = new Client({
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' },
  redaction: { type: "remove" }
})

try {
  await client.indices.create({ index: 'my_index' })
} catch (err) {
  console.log(err.meta.meta.request.options.headers) // undefined
}

Finally, if you prefer to turn off redaction altogether, perhaps while debugging on a local developer environment, you can set the redaction type to off. This will revert the client to pre-8.11.0 behavior, where basic redaction is only performed during common serialization methods like console.log and JSON.stringify.

::::{warning}
Setting redaction.type to off is not recommended in production environments.
::::

js
const { Client } = require('@elastic/elasticsearch')

const client = new Client({
  cloud: { id: '<cloud-id>' },
  auth: { apiKey: 'base64EncodedKey' },
  redaction: { type: "off" }
})

try {
  await client.indices.create({ index: 'my_index' })
} catch (err) {
  console.log(err.meta.meta.request.options.headers.authorization) // the actual header value will be logged
}

Migrate to v8 [_migrate_to_v8]

The Node.js client can be configured to emit an HTTP header Accept: application/vnd.elasticsearch+json; compatible-with=7 which signals to {{es}} that the client is requesting 7.x version of request and response bodies. This allows for upgrading from 7.x to 8.x version of {{es}} without upgrading everything at once. {{es}} should be upgraded first after the compatibility header is configured and clients should be upgraded second. To enable to setting, configure the environment variable ELASTIC_CLIENT_APIVERSIONING to true.