Skip to content

Latest commit

 

History

History
88 lines (70 loc) · 1.76 KB

File metadata and controls

88 lines (70 loc) · 1.76 KB
endpoint _connection
lang javascript
es_version 9.3
client @elastic/elasticsearch@9.3.0

Elasticsearch 9.3 connection management (JavaScript example)

Use the Client class from @elastic/elasticsearch to create a client. The simplest approach uses basic authentication with a username and password:

const { Client } = require("@elastic/elasticsearch");

const client = new Client({
  node: "http://localhost:9200",
  auth: {
    username: "elastic",
    password: "your-password",
  },
});

const info = await client.info();
console.log(`Connected to ${info.cluster_name} (v${info.version.number})`);

Install the client with npm:

npm install @elastic/elasticsearch@9.3.0

API key authentication

For production use, API keys are preferred over username/password. Pass the base64-encoded API key directly:

const client = new Client({
  node: "http://localhost:9200",
  auth: {
    apiKey: "your-base64-api-key",
  },
});

Or use an object with id and api_key if you have them separately:

const client = new Client({
  node: "http://localhost:9200",
  auth: {
    apiKey: {
      id: "key-id",
      api_key: "key-secret",
    },
  },
});

Connection options

Configure timeouts, retries, and TLS for production deployments:

const { Client } = require("@elastic/elasticsearch");
const { readFileSync } = require("fs");

const client = new Client({
  node: "https://my-cluster.example.com:9243",
  auth: { apiKey: "your-base64-api-key" },
  requestTimeout: 30000,
  maxRetries: 3,
  tls: {
    ca: readFileSync("/path/to/ca.crt"),
  },
});

To verify the connection is working:

const alive = await client.ping();
console.log(alive ? "Connected" : "Connection failed");