### Install @elastic/elasticsearch-mock Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/client-testing.md Install the mocking library as a development dependency. ```sh npm install @elastic/elasticsearch-mock --save-dev ``` -------------------------------- ### Start Trial License Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts a 30-day trial for all subscription features. A trial can only be started if one has not been activated for the current major product version. Acknowledge messages by setting `acknowledge` to `true`. ```javascript client.license.postStartTrial({ ... }) ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/elastic/elasticsearch-js/blob/main/AGENTS.md Use this command to install all project dependencies. Always use npm. ```bash npm install ``` -------------------------------- ### client.slm.start Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts the Snapshot Lifecycle Management (SLM) feature. This is typically automatic but can be manually started if it was previously stopped. ```APIDOC ## client.slm.start ### Description Start snapshot lifecycle management. SLM starts automatically when a cluster is formed. Manually starting SLM is necessary only if it has been stopped using the stop SLM API. ### Method POST (inferred from typical Elasticsearch API patterns for actions) ### Endpoint /_slm/start ### Parameters #### Request Body (object) - **`master_timeout`** (string | -1 | 0) - Optional - The period to wait for a connection to the master node. If no response is received before the timeout expires, the request fails and returns an error. To indicate that the request should never timeout, set it to `-1`. - **`timeout`** (string | -1 | 0) - Optional - The period to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. To indicate that the request should never timeout, set it to `-1`. ``` -------------------------------- ### Install the Elasticsearch Node.js client Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/getting-started.md Use npm to install the latest version of the client. ```shell npm install @elastic/elasticsearch ``` -------------------------------- ### Get Document Example Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/get_examples.md This example demonstrates how to get a JSON document from an index using its ID. It first indexes a document and then retrieves it. ```APIDOC ## GET _doc ### Description Retrieves a typed JSON document from the index based on its ID. ### Method GET ### Endpoint `/{index}/{type}/{id}` or `/{index}/_doc/{id}` ### Parameters #### Path Parameters - **index** (string) - Required - The name of the index. - **id** (string) - Required - The ID of the document. - **type** (string) - Optional - The type of the document (defaults to `_doc`). ### Request Example ```javascript await client.get({ index: 'game-of-thrones', id: '1' }) ``` ### Response #### Success Response (200) - **_index** (string) - The name of the index. - **_type** (string) - The type of the document. - **_id** (string) - The ID of the document. - **_version** (integer) - The version of the document. - **found** (boolean) - Indicates if the document was found. - **_source** (object) - The source document. #### Response Example ```json { "_index": "game-of-thrones", "_type": "_doc", "_id": "1", "_version": 1, "found": true, "_source": { "character": "Ned Stark", "quote": "Winter is coming." } } ``` ``` -------------------------------- ### Manually Start Elasticsearch Container Source: https://github.com/elastic/elasticsearch-js/blob/main/test/integration/README.md If Elasticsearch fails to start automatically, use this command to manually start the container and view startup logs. This is useful for debugging connection issues. ```sh DETACH=false .buildkite/run-elasticsearch.sh ``` -------------------------------- ### Start the ILM Plugin Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Use this method to start the Index Lifecycle Management plugin if it has been stopped. ILM typically starts automatically with the cluster, but this API is useful for restarting it after a manual stop. ```typescript client.ilm.start({ ... }) ``` -------------------------------- ### Install Elasticsearch Client from Main Branch Source: https://github.com/elastic/elasticsearch-js/blob/main/README.md Install the development version of the Elasticsearch client directly from the main branch of the GitHub repository. Use this for testing the latest unreleased features. ```sh npm install esmain@github:elastic/elasticsearch-js ``` -------------------------------- ### client.ml.startDatafeed Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts an Elasticsearch ML datafeed. The datafeed must be open and can be started and stopped multiple times. If restarted, it continues from the millisecond after it was stopped. ```APIDOC ## POST _ml.start_datafeed ### Description Starts an Elasticsearch ML datafeed. A datafeed must be open to retrieve data and can be started and stopped multiple times. If restarted, it continues processing input data from the next millisecond after it was stopped. ### Method POST ### Endpoint _ml.start_datafeed ### Parameters #### Request Body - **`datafeed_id`** (string) - Required - A numerical character string that uniquely identifies the datafeed. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. - **`end`** (Optional, string | Unit) - Refer to the description for the `end` query parameter. - **`start`** (Optional, string | Unit) - Refer to the description for the `start` query parameter. - **`timeout`** (Optional, string | -1 | 0) - Refer to the description for the `timeout` query parameter. ### Request Example ```json { "datafeed_id": "my_datafeed_id", "start": "2023-01-01T00:00:00Z", "end": "2023-01-01T12:00:00Z" } ``` ### Response #### Success Response (200) (Response details not provided in source text) #### Response Example (Response example not provided in source text) ``` -------------------------------- ### Update By Query Example Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/update_by_query_examples.md Performs an update on every document in the index that matches the query. This example adds a 'house' field to documents where the character is 'stark'. Ensure documents are indexed before running the update. ```javascript 'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' } }) async function run () { await client.index({ index: 'game-of-thrones', document: { character: 'Ned Stark', quote: 'Winter is coming.' } }) await client.index({ index: 'game-of-thrones', refresh: true, document: { character: 'Arya Stark', quote: 'A girl is Arya Stark of Winterfell. And I\'m going home.' } }) await client.updateByQuery({ index: 'game-of-thrones', refresh: true, script: { lang: 'painless', source: 'ctx._source["house"] = "stark"' }, query: { match: { character: 'stark' } } }) const result = await client.search({ index: 'game-of-thrones', query: { match_all: {} } }) console.log(result.hits.hits) } run().catch(console.log) ``` -------------------------------- ### client.xpack.info Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves information about the Elasticsearch installation, including build details, license status, and enabled features. ```APIDOC ## GET _xpack ### Description Get information about the Elasticsearch installation, including build details, license information, and feature availability. ### Method GET ### Endpoint /_xpack ### Parameters #### Query Parameters - **`categories`** (Optional, Enum("build" | "features" | "license")[]) - A list of the information categories to include in the response. For example, `build,license,features`. - **`accept_enterprise`** (Optional, boolean) - If used, this otherwise ignored parameter must be set to true. - **`human`** (Optional, boolean) - Defines whether additional human-readable information is included in the response. In particular, it adds descriptions and a tag line. ### Response #### Success Response (200) - **build** (object) - Build information including the build number and timestamp. - **license** (object) - License information about the currently installed license. - **features** (object) - Feature information for the features that are currently enabled and available under the current license. #### Response Example ```json { "build": { "build_flavor": "default", "build_type": "docker", "build_hash": "a792944c12317462113751933516037031732661", "build_date": "2023-09-18T07:41:31.041749373Z", "build_version": "8.10.0", "private": false, "commit": "a792944c12317462113751933516037031732661" }, "license": { "uid": "...", "type": "basic", "expiry_date": null }, "features": { "watcher": { "enabled": true, "available": true }, "ml": { "enabled": true, "available": true } } } ``` ``` -------------------------------- ### client.license.postStartBasic Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts an indefinite basic license, granting access to all basic features. Requires acknowledging terms by setting `acknowledge` to `true`. ```APIDOC ## POST _license/start_basic ### Description Starts an indefinite basic license, which gives access to all the basic features. You must not currently have a basic license. If the basic license does not support all features of your current license, you will be notified and must re-submit with `acknowledge` set to `true`. ### Method POST ### Endpoint /_license/start_basic ### Parameters #### Request Body - **`acknowledge`** (boolean) - Optional - To start a basic license, you must accept the acknowledge messages and set this parameter to `true`. - **`master_timeout`** (string | -1 | 0) - Optional - Period to wait for a connection to the master node. - **`timeout`** (string | -1 | 0) - Optional - Period to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. ``` -------------------------------- ### Cloud Configuration Example Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/basic-config.md Configure the client to connect to Elastic Cloud using the provided cloud ID and authentication credentials. ```javascript const client = new Client({ cloud: { id: '' }, auth: { username: 'elastic', password: 'changeme' } }) ``` -------------------------------- ### Get Built-in Privileges Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves a list of all available cluster and index privileges for the current Elasticsearch version. No specific setup is required beyond client initialization. ```typescript client.security.getBuiltinPrivileges() ``` -------------------------------- ### Basic Mock Setup Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/client-testing.md Set up a mock client by passing the mock's connection to the Elasticsearch client configuration. This intercepts all HTTP requests. ```js const { Client } = require('@elastic/elasticsearch') const Mock = require('@elastic/elasticsearch-mock') const mock = new Mock() const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' }, Connection: mock.getConnection() }) mock.add({ method: 'GET', path: '/' }, () => { return { status: 'ok' } }) client.info().then(console.log, console.log) ``` -------------------------------- ### Get X-Pack Information Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieve information about your Elasticsearch X-Pack installation, including build details, license status, and enabled features. You can filter the response by specifying categories. ```typescript client.xpack.info({ ... }) ``` -------------------------------- ### Get all tasks with X-Opaque-Id header Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md This example demonstrates how to retrieve all running tasks and track requests using the `X-Opaque-Id` header. The header is returned in the response and within the task information, allowing for request association. ```bash curl -i -H "X-Opaque-Id: 123456" "http://localhost:9200/_tasks?group_by=parents" ``` -------------------------------- ### Start a Rollup Job Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Use this snippet to start a specific rollup job by its ID. An exception occurs if the job does not exist, and nothing happens if it's already started. ```typescript client.rollup.startJob({ id }) ``` -------------------------------- ### Basic Client Initialization and Search Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/connecting.md Demonstrates how to initialize the Elasticsearch client with cloud ID and API key, and perform a basic search query. ```APIDOC ## Basic Client Initialization and Search ### Description Initialize the Elasticsearch client using your cloud ID and API key, then perform a search operation on a specified index. ### Method `client.search(params, options)` ### Endpoint N/A (Client method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **index** (string) - Required - The name of the index to search. - **query** (object) - Required - The search query definition. ### Request Example ```js const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' } }) const result = await client.search({ index: 'my-index', query: { match: { hello: 'world' } } }) ``` ### Response #### Success Response (200) - **body** (object | boolean) - The response body from Elasticsearch. #### Response Example ```json { "took": 10, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 1.0, "hits": [ { "_index": "my-index", "_id": "1", "_score": 1.0, "_source": { "hello": "world" } } ] } } ``` ``` -------------------------------- ### Start Snapshot Lifecycle Management Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Use this API to manually start the Snapshot Lifecycle Management (SLM) service if it has been previously stopped. SLM typically starts automatically when a cluster is formed. ```typescript client.slm.start({ ... }) ``` -------------------------------- ### Run Base64 Benchmark Test Source: https://github.com/elastic/elasticsearch-js/blob/main/test/ingest/README.md To run the base64 benchmark test, first install dependencies, then set the ES_URL, ES_USERNAME, and ES_PASSWORD environment variables, and finally execute the script. ```bash npm install ``` ```bash node test/ingest/base64.mjs ``` -------------------------------- ### client.license.postStartTrial Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Initiates a 30-day trial license, providing access to all subscription features. This can only be done if a trial for the current major product version has not already been activated. ```APIDOC ## POST _license/start_trial ### Description Starts a 30-day trial, which gives access to all subscription features. You are allowed to start a trial only if your cluster has not already activated a trial for the current major product version. For example, if you have already activated a trial for v8.0, you cannot start a new trial until v9.0. You can, however, request an extended trial. ### Method POST ### Endpoint /_license/start_trial ### Parameters #### Request Body - **`acknowledge`** (boolean) - Optional - To start a trial, you must accept the acknowledge messages and set this parameter to `true`. - **`type`** (string) - Optional - The type of trial license to generate. - **`master_timeout`** (string | -1 | 0) - Optional - Period to wait for a connection to the master node. ``` -------------------------------- ### Initialize Client with Proxy Configuration Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/basic-config.md Configure the client to use an HTTP or HTTPS proxy for connections. Supports basic proxy URLs and URLs with authentication. ```javascript const client = new Client({ node: 'http://localhost:9200', proxy: 'http://localhost:8080' }) ``` ```javascript const client = new Client({ node: 'http://localhost:9200', proxy: 'http://user:pwd@localhost:8080' }) ``` -------------------------------- ### Start ML Datafeed Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts an anomaly detection datafeed. The datafeed must be open and can be started and stopped multiple times. If restarting, it continues from the millisecond after it was stopped, potentially ignoring data indexed in that exact millisecond. ```typescript client.ml.startDatafeed({ datafeed_id }) ``` -------------------------------- ### Create a Snapshot Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Initiates the creation of a snapshot for a specified repository and snapshot name. This is the basic usage for taking a snapshot. ```javascript client.snapshot.create({ repository: "my-repository", snapshot: "my-snapshot" }) ``` -------------------------------- ### Start Basic License Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Initiates an indefinite basic license. Ensure no basic license is currently active. You must acknowledge any feature limitations by setting `acknowledge` to `true`. ```javascript client.license.postStartBasic({ ... }) ``` -------------------------------- ### client.rollup.startJob Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts a specified Elasticsearch rollup job. If the job does not exist, an exception is thrown. If the job is already started, this operation has no effect. ```APIDOC ## client.rollup.startJob [_rollup.start_job] ### Description Starts a specified Elasticsearch rollup job. If the job does not exist, an exception is thrown. If the job is already started, this operation has no effect. ### Method POST ### Endpoint _rollup/job/{id}/start ### Parameters #### Path Parameters - **`id`** (string) - Required - Identifier for the rollup job. ### Request Example ```json { "id": "your_job_id" } ``` ### Response #### Success Response (200) (No specific response fields documented in source) #### Response Example (No example provided in source) ``` -------------------------------- ### Install Specific Major Version of Elasticsearch Client Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/installation.md To install a particular major version of the client, replace `` with the desired version number. ```sh npm install @elastic/elasticsearch@ ``` -------------------------------- ### Configure Basic Authentication Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/basic-config.md Set up basic authentication using a username and password. ```javascript auth: { username: 'elastic', password: 'changeme' } ``` -------------------------------- ### Bulk Helper Usage Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/client-helpers.md Demonstrates the basic usage of the `client.helpers.bulk` method to index documents from a readable stream. ```APIDOC ## client.helpers.bulk ### Description Indexes a large number of documents efficiently using the Elasticsearch Bulk API. ### Method `client.helpers.bulk(options) ### Parameters #### `options` (Object) - **datasource** (Array | AsyncGenerator | ReadableStream) - Required - An array, async generator, or readable stream containing the data to be indexed. Can be an array of strings or objects, or a stream of JSON strings or JavaScript objects. If it's a stream, using `split2` is recommended. - **onDocument** (Function) - Required - A function called for each document. It should return the operation to execute for the document (e.g., `{ index: { _index: 'my-index' } }`). - **onDrop** (Function) - Optional - A function called when a document cannot be indexed after reaching the maximum number of retries. - **onSuccess** (Function) - Optional - A function called for each successful operation, receiving the Elasticsearch result and the original document. - **onFlush** (Function) - Optional - A callback invoked after each batch is sent to Elasticsearch, receiving cumulative statistics. - **flushBytes** (number) - Optional - The size in bytes of the bulk body before it is sent. Defaults to 5MB (5000000). - **flushInterval** (number) - Optional - The time in milliseconds to wait before flushing the body from the last document read. Defaults to 30000. - **concurrency** (number) - Optional - The number of requests to execute concurrently. Defaults to 5. - **retries** (number) - Optional - The number of times a document is retried before calling `onDrop`. Defaults to the client's maximum retries. - **wait** (number) - Optional - The time in milliseconds to wait before retries. Defaults to 5000. - **refreshOnCompletion** (boolean) - Optional - If true, performs a refresh on all indices or specified indices at the end of the bulk operation. Defaults to false. ### Request Example ```js const { createReadStream } = require('fs') const split = require('split2') const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' } }) const result = await client.helpers.bulk({ datasource: createReadStream('./dataset.ndjson').pipe(split()), onDocument (doc) { return { index: { _index: 'my-index' } } } }) console.log(result) ``` ### Response #### Success Response The `result` object contains cumulative statistics: - **total** (number) - Total documents processed so far. - **failed** (number) - Documents dropped/failed so far. - **retry** (number) - Total retry count so far. - **successful** (number) - Documents successfully indexed so far. - **time** (number) - Total time taken in milliseconds. - **bytes** (number) - Total bytes sent so far. - **aborted** (boolean) - Whether the bulk operation was aborted. #### Response Example ```json { "total": 1000, "failed": 0, "retry": 0, "successful": 1000, "time": 500, "bytes": 102400, "aborted": false } ``` ``` -------------------------------- ### Start Trained Model Deployment Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Initiates the deployment of a trained machine learning model. This action allocates the model to all available machine learning nodes in the cluster. ```javascript client.ml.startTrainedModelDeployment({ model_id }) ``` -------------------------------- ### Get Snapshot Repository Information Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves information about snapshot repositories. Omit the 'repository' parameter or use '*' to get details for all registered repositories. ```typescript client.snapshot.getRepository({ ... }) ``` -------------------------------- ### Create and use a child client Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/child.md Instantiate a parent client and then create a child client with custom headers. Both clients can then be used to make requests, sharing the same connection pool. ```javascript const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' } }) const child = client.child({ headers: { 'x-foo': 'bar' }, }) client.info().then(console.log, console.log) child.info().then(console.log, console.log) ``` -------------------------------- ### client.rollup.putJob Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Creates a rollup job with the specified configuration. Jobs are created in a STOPPED state and can be started later using the start rollup jobs API. ```APIDOC ## client.rollup.putJob Creates a rollup job. ### Method POST ### Endpoint _rollup.put_job/{id} ### Description Creates a rollup job with the specified configuration. Jobs are created in a STOPPED state and can be started later using the start rollup jobs API. ### Parameters #### Path Parameters - **`id`** (string) - Required - Identifier for the rollup job. This can be any alphanumeric string and uniquely identifies the data that is associated with the rollup job. The ID is persistent; it is stored with the rolled up data. If you create a job, let it run for a while, then delete the job, the data that the job rolled up is still be associated with this job ID. You cannot create a new job with the same ID since that could lead to problems with mismatched job configurations. #### Request Body - **`cron`** (string) - Required - A cron string which defines the intervals when the rollup job should be executed. When the interval triggers, the indexer attempts to rollup the data in the index pattern. The cron pattern is unrelated to the time interval of the data being rolled up. For example, you may wish to create hourly rollups of your document but to only run the indexer on a daily basis at midnight, as defined by the cron. The cron pattern is defined just like a Watcher cron schedule. - **`groups`** ({ `date_histogram`, `histogram`, `terms` }) - Required - Defines the grouping fields and aggregations that are defined for this rollup job. These fields will then be available later for aggregating into buckets. These aggs and fields can be used in any combination. Think of the groups configuration as defining a set of tools that can later be used in aggregations to partition the data. Unlike raw data, we have to think ahead to which fields and aggregations might be used. Rollups provide enough flexibility that you simply need to determine which fields are needed, not in what order they are needed. - **`index_pattern`** (string) - Required - The index or index pattern to roll up. Supports wildcard-style patterns (`logstash-*`). The job attempts to rollup the entire index or index-pattern. - **`page_size`** (number) - Optional - The number of bucket results that are processed on each iteration of the rollup indexer. A larger value tends to execute faster, but requires more memory during processing. This value has no effect on how the data is rolled up; it is merely used for tweaking the speed or memory cost of the indexer. - **`rollup_index`** (string) - Optional - The index that contains the rollup results. The index can be shared with other rollup jobs. The data is stored so that it doesn’t interfere with unrelated jobs. - **`metrics`** (Optional, { `field`, `metrics` }[]) - Optional - Defines the metrics to collect for each grouping tuple. By default, only the doc_counts are collected for each group. To make rollup useful, you will often add metrics like averages, mins, maxes, etc. Metrics are defined on a per-field basis and for each field you configure which metric should be collected. - **`timeout`** (Optional, string | -1 | 0) - Optional - Time to wait for the request to complete. - **`headers`** (Optional, Record) - Optional - Custom headers to send with the request. ### Request Example ```json { "id": "my_rollup_job_id", "cron": "0 30 2 * * ?", "groups": { "date_histogram": { "field": "timestamp", "fixed_interval": "1h" } }, "index_pattern": "my-logs-*", "rollup_index": "my-rollup-index", "metrics": [ { "field": "response_time", "metrics": ["avg", "max"] } ] } ``` ### Response #### Success Response (200) - **`acknowledged`** (boolean) - Indicates if the request was acknowledged. #### Response Example ```json { "acknowledged": true } ``` ``` -------------------------------- ### client.ilm.start Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts the Index Lifecycle Management (ILM) plugin. This is typically used to restart ILM after it has been explicitly stopped. ```APIDOC ## client.ilm.start ### Description Start the index lifecycle management plugin if it is currently stopped. ILM is started automatically when the cluster is formed. Restarting ILM is necessary only when it has been stopped using the stop ILM API. ### Method POST ### Endpoint /_ilm/start ### Parameters #### Request Body - **`master_timeout`** (Optional, string | -1 | 0) - Period to wait for a connection to the master node. If no response is received before the timeout expires, the request fails and returns an error. - **`timeout`** (Optional, string | -1 | 0) - Period to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. ### Request Example ```json { "master_timeout": "10s", "timeout": "30s" } ``` ### Response #### Success Response (200) - **acknowledged** (boolean) - Indicates if the request was acknowledged. #### Response Example ```json { "acknowledged": true } ``` ``` -------------------------------- ### Get Transform Configuration Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves configuration information for specified transforms. Use wildcard expressions or omit the ID to get information for multiple or all transforms. ```typescript client.transform.getTransform({ ... }) ``` -------------------------------- ### client.ml.startTrainedModelDeployment Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts a trained model deployment by allocating the model to every machine learning node. This operation allows for detailed configuration of the deployment process. ```APIDOC ## client.ml.startTrainedModelDeployment ### Description Starts a trained model deployment. It allocates the model to every machine learning node. ### Method POST ### Endpoint /_ml/trained_models/{model_id}/deployment/_start ### Parameters #### Path Parameters - **`model_id`** (string) - Required - The unique identifier of the trained model. Currently, only PyTorch models are supported. #### Request Body - **`adaptive_allocations`** (Optional, object) - Adaptive allocations configuration. When enabled, the number of allocations is set based on the current load. If adaptive_allocations is enabled, do not set the number of allocations manually. - **`enabled`** (boolean) - Whether adaptive allocations are enabled. - **`min_number_of_allocations`** (number) - The minimum number of allocations. - **`max_number_of_allocations`** (number) - The maximum number of allocations. - **`cache_size`** (Optional, string | number) - The inference cache size (in memory outside the JVM heap) per node for the model. The default value is the same size as the `model_size_bytes`. To disable the cache, `0b` can be provided. - **`deployment_id`** (Optional, string) - A unique identifier for the deployment of the model. - **`number_of_allocations`** (Optional, number) - The number of model allocations on each node where the model is deployed. All allocations on a node share the same copy of the model in memory but use a separate set of threads to evaluate the model. Increasing this value generally increases the throughput. If this setting is greater than the number of hardware threads it will automatically be changed to a value less than the number of hardware threads. If adaptive_allocations is enabled, do not set this value, because it’s automatically set. - **`priority`** (Optional, Enum("normal" | "low")) - The deployment priority. - **`queue_capacity`** (Optional, number) - Specifies the number of inference requests that are allowed in the queue. After the number of requests exceeds this value, new requests are rejected with a 429 error. - **`threads_per_allocation`** (Optional, number) - Sets the number of threads used by each model allocation during inference. This generally increases the inference speed. The inference process is a compute-bound process; any number greater than the number of available hardware threads on the machine does not increase the inference speed. If this setting is greater than the number of hardware threads it will automatically be changed to a value less than the number of hardware threads. - **`timeout`** (Optional, string | -1 | 0) - Specifies the amount of time to wait for the model to deploy. - **`wait_for`** (Optional, Enum("started" | "starting" | "fully_allocated")) - Specifies the allocation status to wait for before returning. ### Request Example ```json { "model_id": "your_model_id", "number_of_allocations": 1, "threads_per_allocation": 4, "priority": "normal", "timeout": "1h", "wait_for": "started" } ``` ### Response #### Success Response (200) - **`deployment_id`** (string) - The unique identifier for the deployment. - **`model_id`** (string) - The unique identifier of the trained model. - **`state`** (string) - The current state of the deployment. #### Response Example ```json { "deployment_id": "example_deployment_id", "model_id": "your_model_id", "state": "started" } ``` ``` -------------------------------- ### Get Datafeeds Configuration Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieve configuration information for one or more datafeeds. Use `_all` or `*` to get all datafeeds. This API returns a maximum of 10,000 datafeeds. ```typescript client.ml.getDatafeeds({ ... }) ``` -------------------------------- ### Get Index Information Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves high-level information about indices in a cluster. Use this to get shard counts, document counts, and storage metrics for each index. ```typescript client.cat.indices({ ... }) ``` -------------------------------- ### Basic TypeScript Example Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/typescript.md Demonstrates indexing and searching documents using the Elasticsearch JavaScript client with TypeScript. Ensure your client is configured with cloud ID and API key. ```typescript import { Client } from '@elastic/elasticsearch' const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' } }) interface Document { character: string quote: string } async function run () { // Let's start by indexing some data await client.index({ index: 'game-of-thrones', document: { character: 'Ned Stark', quote: 'Winter is coming.' } }) await client.index({ index: 'game-of-thrones', document: { character: 'Daenerys Targaryen', quote: 'I am the blood of the dragon.' } }) await client.index({ index: 'game-of-thrones', document: { character: 'Tyrion Lannister', quote: 'A mind needs books like a sword needs a whetstone.' } }) // here we are forcing an index refresh, otherwise we will not // get any result in the consequent search await client.indices.refresh({ index: 'game-of-thrones' }) // Let's search! const result= await client.search({ index: 'game-of-thrones', query: { match: { quote: 'winter' } } }) console.log(result.hits.hits) } run().catch(console.log) ``` -------------------------------- ### Get Document by ID Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/get_examples.md Indexes a document and then retrieves it using the get API. Ensure the client is configured with valid cloud ID and API key. ```javascript 'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' } }) async function run () { await client.index({ index: 'game-of-thrones', id: '1', document: { character: 'Ned Stark', quote: 'Winter is coming.' } }) const document = await client.get({ index: 'game-of-thrones', id: '1' }) console.log(document) } run().catch(console.log) ``` -------------------------------- ### Create an index Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/getting-started.md Use the client to create a new index named 'my_index'. ```javascript await client.indices.create({ index: 'my_index' }) ``` -------------------------------- ### Using the Client in a Function-as-a-Service Environment Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/connecting.md Illustrates best practices for leveraging the Elasticsearch client in a Function-as-a-Service (FaaS) environment, emphasizing client initialization in the global scope for performance and background functionality. ```APIDOC ## Using the Client in a Function-as-a-Service Environment ### Description Best practices for leveraging the {{es}} client in a Function-as-a-Service (FaaS) environment. The most influential optimization is to initialize the client outside of the function, in the global scope. ### GCP Cloud Functions ```js 'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ // client initialisation }) exports.testFunction = async function (req, res) { // use the client } ``` ### AWS Lambda ```js 'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ // client initialisation }) exports.handler = async function (event, context) { // use the client } ``` ``` -------------------------------- ### Get Field Mapping Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves mapping definitions for one or more fields. This is useful for getting specific field mappings without fetching the entire index mapping. ```typescript client.indices.getFieldMapping({ fields }) ``` -------------------------------- ### Install Multiple Elasticsearch Client Versions Source: https://github.com/elastic/elasticsearch-js/blob/main/README.md Use npm aliasing to install and manage different versions of the Elasticsearch client. This is useful when working with multiple Elasticsearch instances. ```sh npm install @npm:@elastic/elasticsearch@ ``` ```sh npm install es6@npm:@elastic/elasticsearch@6 npm install es7@npm:@elastic/elasticsearch@7 ``` -------------------------------- ### Start Watcher Service Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Use this snippet to start the Watcher service if it is not already running. The `master_timeout` argument is optional and specifies the period to wait for a connection to the master node. ```typescript client.watcher.start({ ... }) ``` -------------------------------- ### Index Documents and Perform Suggest Search Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/suggest_examples.md Use this snippet to index sample documents and then execute a search request that includes a suggest query. This is useful for retrieving similar terms based on the provided text. Ensure you have a running Elasticsearch instance and the necessary authentication details. ```javascript 'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' } }) async function run () { const bulkResponse = await client.bulk({ refresh: true, operations: [ { index: { _index: 'game-of-thrones' } }, { character: 'Ned Stark', quote: 'Winter is coming.' }, { index: { _index: 'game-of-thrones' } }, { character: 'Daenerys Targaryen', quote: 'I am the blood of the dragon.' }, { index: { _index: 'game-of-thrones' } }, { character: 'Tyrion Lannister', quote: 'A mind needs books like a sword needs a whetstone.' } ] }) if (bulkResponse.errors) { console.log(bulkResponse) process.exit(1) } const result = await client.search({ index: 'game-of-thrones', query: { match: { quote: 'winter' } }, suggest: { gotsuggest: { text: 'winter', term: { field: 'quote' } } } }) console.log(result) } run().catch(console.log) ``` -------------------------------- ### Index and Search Data Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/search_examples.md This example shows how to index documents into an Elasticsearch index and then perform a search query. Ensure the client is configured with your cloud ID and API key. A refresh is forced after indexing to make documents immediately searchable. ```javascript 'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' } }) async function run () { // Let's start by indexing some data await client.index({ index: 'game-of-thrones', document: { character: 'Ned Stark', quote: 'Winter is coming.' } }) await client.index({ index: 'game-of-thrones', document: { character: 'Daenerys Targaryen', quote: 'I am the blood of the dragon.' } }) await client.index({ index: 'game-of-thrones', // here we are forcing an index refresh, // otherwise we will not get any result // in the consequent search refresh: true, document: { character: 'Tyrion Lannister', quote: 'A mind needs books like a sword needs a whetstone.' } }) // Let's search! const result = await client.search({ index: 'game-of-thrones', query: { match: { quote: 'winter' } } }) console.log(result.hits.hits) } run().catch(console.log) ``` -------------------------------- ### Get Datafeed Statistics Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Use this snippet to get statistics for ML datafeeds. You can retrieve stats for a specific datafeed ID, multiple datafeeds using a wildcard, or all datafeeds. ```typescript client.ml.getDatafeedStats({ ... }) ``` -------------------------------- ### Initialize Elasticsearch Client Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/connecting.md Initialize the client with cloud ID and API key for authentication. This is the standard way to connect to Elasticsearch. ```javascript const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' } }) ``` -------------------------------- ### Get Field Usage Statistics Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Get field usage statistics for each shard and field of an index. Field usage statistics are automatically captured when queries are running on a cluster. ```typescript client.indices.fieldUsageStats({ index }) ``` -------------------------------- ### Install Multiple Elasticsearch Client Versions Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/index.md Use npm aliasing to install and manage different versions of the Elasticsearch client. This is useful when working with multiple Elasticsearch cluster versions. ```sh npm install @npm:@elastic/elasticsearch@ ``` ```sh npm install es6@npm:@elastic/elasticsearch@6 npm install es7@npm:@elastic/elasticsearch@7 ``` ```sh npm install esmain@github:elastic/elasticsearch-js ```