### Start a trial license with client.license.postStartTrial Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts a 30-day trial. Allowed only if the cluster has not already activated a trial for the current major product version. For example, a trial for v8.0 prevents a new trial until v9.0. Use the get trial status API to check status. ```TypeScript client.license.postStartTrial({ ... }) ``` -------------------------------- ### Start a basic license with client.license.postStartBasic Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts an indefinite basic license. Requires that you do not currently have a basic license. If the basic license does not support all current features, you must re-submit with the acknowledge parameter set to true. Use the get basic license API to check status. ```TypeScript client.license.postStartBasic({ ... }) ``` -------------------------------- ### Install the client with npm Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/getting-started.md Run this command to install the latest version of the @elastic/elasticsearch client. ```shell npm install @elastic/elasticsearch ``` -------------------------------- ### Start SLM with client.slm.start Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts snapshot lifecycle management. SLM starts automatically when a cluster is formed, so this is only needed if it was previously stopped. The request accepts optional master_timeout and timeout parameters. ```TypeScript client.slm.start({ ... }) ``` -------------------------------- ### Install @elastic/elasticsearch-mock Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/client-testing.md Install the mocking library as a dev dependency using npm. ```sh npm install @elastic/elasticsearch-mock --save-dev ``` -------------------------------- ### client.ilm.start Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts the ILM plugin. ILM is started automatically when the cluster is formed; this is only necessary after it has been stopped using the stop ILM API. ```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** (string | -1 | 0) - Optional - 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** (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. ### Request Example ```ts client.ilm.start({ ... }) ``` ### Response #### Success Response (200) No response body is documented. ``` -------------------------------- ### Start ILM plugin with client.ilm.start Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts the index lifecycle management plugin if it is currently stopped. ILM is started automatically when the cluster is formed; restarting is only necessary after it has been stopped using the stop ILM API. Accepts an optional request object with master_timeout and timeout parameters. ```TypeScript client.ilm.start({ ... }) ``` -------------------------------- ### client.slm.start Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts snapshot lifecycle management (SLM). SLM starts automatically when a cluster is formed, so this is only necessary if it was previously stopped using the stop SLM API. ```APIDOC ## client.slm.start ### Description Starts snapshot lifecycle management (SLM). SLM starts automatically when a cluster is formed, so this is only necessary if it was previously stopped using the stop SLM API. ### Method POST ### Endpoint /slm/start ### Parameters #### Request Body - **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`. ### Request Example ```ts client.slm.start({ ... }) ``` ### Response #### Success Response (200) No response body is documented. #### Response Example No response example is documented. ``` -------------------------------- ### Install main branch client from GitHub Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/index.md Installs the client from the main branch of the elasticsearch-js GitHub repository. This version is not considered stable. ```sh npm install esmain@github:elastic/elasticsearch-js ``` -------------------------------- ### Basic mock setup with Client Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/client-testing.md Create a mock instance and connect it to the client via the Connection option. Every request is handled by the mock, making tests faster and parallelizable. ```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) ``` -------------------------------- ### TypeScript client.get example Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Use the Elasticsearch JavaScript client's get method with an object containing the index and id parameters to retrieve a document. This is the programmatic equivalent of the HTTP GET request. ```ts client.get({ id, index }) ``` -------------------------------- ### Create a client with basic configuration Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/basic-config.md Shows how to instantiate the client with cloud ID, API key authentication, maxRetries, and sniffOnStart. ```javascript const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '' }, auth: { apiKey: 'base64EncodedKey' }, maxRetries: 5, sniffOnStart: true }) ``` -------------------------------- ### client.rollup.getJobs Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Gets the configuration, stats, and status of rollup jobs. Returns only active (STARTED or STOPPED) jobs. ```APIDOC ## GET /_rollup/job/{id} ### Description Gets the configuration, stats, and status of rollup jobs. This API returns only active (both STARTED and STOPPED) jobs. If a job was created, ran for a while, then was deleted, the API does not return any details about it. ### Method GET ### Endpoint /_rollup/job/{id} ### Parameters #### Path Parameters - **id** (Optional, string) - Identifier for the rollup job. If it is `_all` or omitted, the API returns all rollup jobs. ### Request Example ```ts client.rollup.getJobs({ ... }) ``` ### Response #### Success Response (200) - **jobs** (array) - An array of rollup job objects, each containing configuration, stats, and status. #### Response Example ```json { "jobs": [ { "config": {}, "stats": {}, "status": {} } ] } ``` ``` -------------------------------- ### Listen to serialization event Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/observability.md Emitted before starting serialization and compression. Measure time between this event and 'request' to get serialization duration. ```js client.diagnostic.on("serialization", (err, result) => { console.log(err, result) }) ``` -------------------------------- ### client.license.postStartBasic Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts an indefinite basic license. Requires acknowledging the license terms if the current license has features not supported by the basic license. ```APIDOC ## client.license.postStartBasic ### Description Start an indefinite basic license, which gives access to all the basic features. In order to start a basic license, you must not currently have a basic license. If the basic license does not support all of the features that are available with your current license, you are notified in the response and must re-submit the request with the `acknowledge` parameter 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. ### Request Example ```ts client.license.postStartBasic({ acknowledge: true }) ``` ### Response #### Success Response (200) - **acknowledged** (boolean) - Indicates whether the request was acknowledged. - **basic_was_started** (boolean) - Indicates whether the basic license was started. #### Response Example ```json { "acknowledged": true, "basic_was_started": true } ``` ``` -------------------------------- ### Get calendar events with client.ml.getCalendarEvents Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves events from one or more calendars. The calendar_id argument is required and can be a single ID, a list of IDs, a wildcard expression, or '_all'/'*' to get all calendars. Optional parameters include end, from, job_id, size, and start for filtering and pagination. ```typescript client.ml.getCalendarEvents({ calendar_id }) ``` -------------------------------- ### client.license.postStartTrial Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Starts a 30-day trial license with access to all subscription features. Requires acknowledging the trial terms and can only be started if the cluster has not already activated a trial for the current major version. ```APIDOC ## client.license.postStartTrial ### Description Start 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. ### 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. ### Request Example ```ts client.license.postStartTrial({ acknowledge: true, type: "trial" }) ``` ### Response #### Success Response (200) - **acknowledged** (boolean) - Indicates whether the request was acknowledged. - **trial_was_started** (boolean) - Indicates whether the trial license was started. #### Response Example ```json { "acknowledged": true, "trial_was_started": true } ``` ``` -------------------------------- ### Get rollup job information with client.rollup.getJobs Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves configuration, stats, and status of rollup jobs. Only active jobs (STARTED or STOPPED) are returned; deleted jobs are not included. ```ts client.rollup.getJobs({ ... }) ``` -------------------------------- ### List search applications with client.searchApplication.list Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Gets information about search applications. The request object supports optional 'q' (Lucene query), 'from' (starting offset), and 'size' (max results) parameters. ```TypeScript client.searchApplication.list({ ... }) ``` -------------------------------- ### Azure Functions: Initialize client in global scope Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/connecting.md Initialize the Elasticsearch client outside the Azure Function to reuse it across invocations. The example shows the client setup and a placeholder for the function logic. ```javascript 'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ // client initialisation }) module.exports = async function (context, req) { // use the client } ``` -------------------------------- ### TypeScript example: Index and search documents Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/typescript.md Shows how to use the client with TypeScript, including indexing documents, refreshing an index, and searching with a typed result. Requires TypeScript configuration with esModuleInterop set to true unless skipLibCheck is true. ```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) ``` -------------------------------- ### GCP Cloud Functions: Initialize client in global scope Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/connecting.md Initialize the Elasticsearch client outside the function handler to reuse it across invocations. The example shows the client setup and a placeholder for the function logic. ```javascript 'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ // client initialisation }) exports.testFunction = async function (req, res) { // use the client } ``` -------------------------------- ### Call putSettings method Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Example of calling the putSettings method on the client. ```ts client.indices.putSettings({ ... }) ``` -------------------------------- ### Get model snapshots with client.ml.getModelSnapshots Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves information about model snapshots for a specified anomaly detection job. The job_id argument is required. Optional arguments include snapshot_id, desc, end, page, sort, start, from, and size. ```TypeScript client.ml.getModelSnapshots({ job_id }) ``` -------------------------------- ### Get node statistics with client.nodes.stats Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Calls the nodes.stats API to retrieve statistics for nodes in the cluster. By default, all stats are returned; use the metric parameter to limit the information. The example shows the basic invocation without arguments. ```TypeScript client.nodes.stats({ ... }) ``` -------------------------------- ### Input as string example Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Shows the `input` argument specified as a single string. ```json "input": "some document text" ``` -------------------------------- ### GET /my-index-000001/_termvectors/1?fields=message Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Example HTTP request to retrieve term vectors for a specific document, specifying the 'message' field. Demonstrates the default behavior of returning term information and field statistics while excluding term statistics. ```http GET /my-index-000001/_termvectors/1?fields=message ``` -------------------------------- ### Index documents and search with term suggester Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/suggest_examples.md Use this example to index documents into the 'game-of-thrones' index and then perform a search with a term suggester on the 'quote' field. The example uses the @elastic/elasticsearch client with cloud authentication. It checks for bulk response errors and exits if any occur. The search includes a match query and a suggest block named 'gotsuggest' with text 'winter'. ```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) ``` -------------------------------- ### AWS Lambda: Initialize client in global scope Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/connecting.md Initialize the Elasticsearch client outside the Lambda handler to improve performance and enable background features like sniffing. The example shows the client setup and a placeholder for the handler logic. ```javascript 'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ // client initialisation }) exports.handler = async function (event, context) { // use the client } ``` -------------------------------- ### Input as string array example Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Shows the `input` argument specified as an array of strings. ```json "input": ["some document text", "some more document text"] ``` -------------------------------- ### Index documents and run SQL query with Elasticsearch JS client Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/sql_query_examples.md This example sets up a client with cloud credentials, indexes three documents into the 'game-of-thrones' index, and executes a SQL query to select documents where house equals 'stark'. It logs the raw result and then maps the rows into an array of objects using the column names. ```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.', house: 'stark' } }) await client.index({ index: 'game-of-thrones', document: { character: 'Arya Stark', quote: 'A girl is Arya Stark of Winterfell. And I\'m going home.', house: 'stark' } }) await client.index({ index: 'game-of-thrones', refresh: true, document: { character: 'Tyrion Lannister', quote: 'A Lannister always pays his debts.', house: 'lannister' } }) const result = await client.sql.query({ query: "SELECT * FROM \"game-of-thrones\" WHERE house='stark'" }) console.log(result) const data = result.rows.map(row => { const obj = {} for (let i = 0; i < row.length; i++) { obj[result.columns[i].name] = row[i] } return obj }) console.log(data) } run().catch(console.log) ``` -------------------------------- ### Get anomaly records with client.ml.getRecords Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves anomaly records for the specified anomaly detection job. The only required argument is job_id, which identifies the job. Optional arguments include desc, end, exclude_interim, page, record_score, sort, start, from, and size. ```TypeScript client.ml.getRecords({ job_id }) ``` -------------------------------- ### Configure proxy with and without credentials Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/basic-config.md Shows two client configurations using the proxy option, one without credentials and one with user and password. ```javascript const client = new Client({ node: 'http://localhost:9200', proxy: 'http://localhost:8080' }) const client = new Client({ node: 'http://localhost:9200', proxy: 'http://user:pwd@localhost:8080' }) ``` -------------------------------- ### Shared Undici Agent for connection limits Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/connecting.md Starting in client 9.0 with @elastic/transport 9.2.0 or later, provide a custom agent function that returns a shared Undici Agent instance to enforce client-wide connection limits. The total connection limit is maxOrigins * connections (50 in this example). ```typescript import { Agent } from 'undici' import { HttpConnection } from '@elastic/transport' // `maxOrigins * connections` (50 in this case) is the total connection limit const maxSocketAgent = new Agent({ keepAliveTimeout: 1000, maxOrigins: 5, connections: 10 }) const client = new Client({ node: '...', auth: { ... }, agent: () => maxSocketAgent }) ``` -------------------------------- ### Basic authentication with username and password Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/basic-config.md Shows how to configure basic authentication using the auth option. ```javascript auth: { username: 'elastic', password: 'changeme' } ``` -------------------------------- ### Get overall buckets with client.ml.getOverallBuckets Source: https://github.com/elastic/elasticsearch-js/blob/main/docs/reference/api-reference.md Retrieves overall bucket results that summarize bucket results across multiple anomaly detection jobs. The job_id argument is required and can be a job identifier, group name, list, or wildcard expression. Optional arguments include allow_no_match, bucket_span, end, exclude_interim, overall_score, start, and top_n. ```TypeScript client.ml.getOverallBuckets({ job_id }) ```