Elasticsearch Node.js Client

repository·main·Indexed 26 days ago

https://github.com/elastic/elasticsearch-js

The official Node.js client for Elasticsearch (version 9.6.0), providing a programmatic interface to interact with Elasticsearch clusters, manage indices, and perform search operations. It supports Node.js v20 and above. Key capabilities include index management, search queries (such as pinned and has_child queries), inference task configuration, and cluster administration.

Tokens
358.7K
Snippets
1.4K
Records
1.9K
Agent score
89%

What's inside @elastic/elasticsearch

  1. Overview of Elasticsearch Node.js client features

    main

    The official Elasticsearch Node.js client provides several key features for interacting with Elasticsearch:

    • One-to-one mapping with REST API: The client methods map directly to Elasticsearch REST API endpoints.
    • Pluggable architecture: A generalized and extensible design.
    • Automatic discovery: Configurable discovery of cluster nodes.
    • Connection management: Persistent, Keep-Alive connections.
    • Load balancing: Distributes requests across all available nodes.
    • Child client support: Ability to support child clients.
    • TypeScript support: Built-in TypeScript support for type safety.
  2. Manage connector sync jobs with client.connector

    main
    The client.connector namespace provides APIs for managing connector sync jobs. These APIs are primarily used by services implementing the connector protocol to communicate with Elasticsearch. For self-managed connectors, you must deploy the Elastic connector service on your own infrastructure.
  3. Enable API versioning compatibility for v8 migration

    main

    To upgrade from Elasticsearch 7.x to 8.x without immediate client upgrades, you can signal the server to use the 7.x request/response body format by adding the Accept: application/vnd.elasticsearch+json; compatible-with=7 header.

    To enable this, set the environment variable ELASTIC_CLIENT_APIVERSIONING to true.

  4. Manage dangling indices

    main

    Dangling indices are index data that is absent from the current cluster state (e.g., if an Elasticsearch node was offline during index deletions). Use the danglingIndices namespace to list, import, or delete them.

    • List: client.danglingIndices.listDanglingIndices()
    • Import: client.danglingIndices.importDanglingIndex({ index_uuid, accept_data_loss }) (Requires accept_data_loss: true as data integrity cannot be guaranteed).
    • Delete: client.danglingIndices.deleteDanglingIndex({ index_uuid, accept_data_loss }) (Requires accept_data_loss: true to acknowledge permanent data loss).
  5. Install the client from the main branch

    main

    To install the client version corresponding to the next version of Elasticsearch (the one currently in the main branch), install directly from the GitHub repository.

    npm install esmain@github:elastic/elasticsearch-js
  6. Browser usage warning

    main

    There is no official support for the browser environment. Using the client directly in a browser exposes your Elasticsearch instance to the public, which creates significant security risks.

    Recommended Pattern: Write a lightweight proxy that uses the @elastic/elasticsearch client on the server side to communicate with your Elasticsearch instance.

  7. Stop the msearch helper

    main

    To prevent memory leaks, always call the .stop() method on an msearch helper instance once you have finished using it.

    Note: The stop method stops the execution of the processor, but if concurrency is greater than one, operations already in progress will not be stopped. The stop method can accept an optional error that will be dispatched to all subsequent search requests.

    const { Client } = require('@elastic/elasticsearch')
    
    const client = new Client({
      cloud: { id: '<cloud-id>' },
      auth: { apiKey: 'base64EncodedKey' }
    })
    const m = client.helpers.msearch()
    
    m.search(
        { index: 'stackoverflow' },
        { query: { match: { title: 'javascript' } } }
      )
      .then(result => console.log(result.body))
      .catch(err => console.error(err))
    
    m.search(
        { index: 'stackoverflow' },
        { query: { match: { title: 'ruby' } } }
      )
      .then(result => console.log(result.body))
      .catch(err => console.error(err))
    
    setImmediate(() => m.stop())
  8. Connect through an HTTP(S) proxy

    main

    In versions 8.0+, the default Connection type is UndiciConnection, which does not support proxies. To use a proxy, you must use the HttpConnection class from @elastic/transport.

    import { HttpConnection } from '@elastic/transport'
    
    // Basic proxy configuration
    const client = new Client({
      node: 'http://localhost:9200',
      proxy: 'http://localhost:8080',
      Connection: HttpConnection,
    })
    
    // Proxy with basic authentication
    const clientAuth = new Client({
      node: 'http://localhost:9200',
      proxy: 'http:user:pwd@//localhost:8080',
      Connection: HttpConnection,
    })
    
    // Using a custom agent (e.g., SOCKS proxy)
    const SocksProxyAgent = require('socks-proxy-agent')
    const clientSocks = new Client({
      node: 'http://localhost:9200',
      agent () {
        return new SocksProxyAgent('socks://127.0.0.1:1080')
      },
      Connection: HttpConnection,
    })
  9. Use the Elasticsearch Client for API calls

    main

    The Client supports all public Elasticsearch APIs. By default, every method returns the response body. To access metadata like statusCode or headers, pass { meta: true } as the second argument to the request.

    const { Client } = require('@elastic/elasticsearch')
    const client = new Client({
      cloud: { id: '<cloud-id>' },
      auth: { apiKey: 'base64EncodedKey' }
    })
    
    // Standard usage (returns body)
    const result = await client.search({
      index: 'my-index',
      query: {
        match: { hello: 'world' }
      }
    })
    
    // Usage with metadata (returns object with body, statusCode, headers, etc.)
    const resultWithMeta = await client.search({
      index: 'my-index',
      query: {
        match: { hello: 'world' }
      }
    }, { meta: true })