Compare commits

..

24 Commits

Author SHA1 Message Date
5be4ae40b8 Bump version to 9.0.0 (#2749) (#2751) 2025-04-15 14:46:35 -05:00
e564cb6c80 Update changelog to include fix for #2694 (#2745) (#2747)
Co-authored-by: Josh Mock <joshua.mock@elastic.co>
2025-04-15 13:41:56 -05:00
7b4c799fd8 Bug #2694 (#2731) (#2742)
Co-authored-by: Siddhu545 <Siddharthkhengare@gmail.com>
Co-authored-by: Josh Mock <joshua.mock@elastic.co>
Co-authored-by: Siddharth Khengare <67581382+Siddhu545@users.noreply.github.com>
2025-04-15 12:44:57 -05:00
7feb422c77 Auto-generated API code (#2741) 2025-04-14 12:51:13 -05:00
af0188d1d4 Update ESQL helper types (#2738) (#2739)
Co-authored-by: Josh Mock <joshua.mock@elastic.co>
2025-04-14 12:45:12 -05:00
f17bfaddf6 Merge branch 'main' of https://github.com/marciw/elasticsearch-js (#2729) (#2730)
(cherry picked from commit 8b4fcc8ce1)

Co-authored-by: Marci W <333176+marciw@users.noreply.github.com>
2025-04-11 16:34:36 +02:00
08777446c1 Restore troubleshooting content (#2727) (#2728)
Co-authored-by: Marci W <333176+marciw@users.noreply.github.com>
2025-04-10 09:58:46 -05:00
71fe13f7cb Auto-generated API code (#2720) 2025-04-08 11:42:30 -05:00
dd33c6fc0f Make example generation quiet by default (#2722) (#2725)
Co-authored-by: Josh Mock <joshua.mock@elastic.co>
2025-04-08 11:39:44 -05:00
8bf11b6e17 Update release notes and related files (#2717) (#2718)
Co-authored-by: Marci W <333176+marciw@users.noreply.github.com>
2025-04-08 11:20:22 -05:00
73ef18836e Auto-generated API code (#2715) 2025-04-07 14:42:06 -05:00
c988c44f66 Changelog for 9.0.0 (#2712) (#2713)
* Changelog for 9.0.0 (#2712)

* Changelog for 9.0.0

* Update title for release notes page

* Grammar tweak

* Adjustment to formatting

* Change title
2025-04-07 14:00:02 -05:00
60e745dbb4 Auto-generated API code (#2699) 2025-04-04 13:04:49 -05:00
3b6c2e1be6 Update helpers to use new multisearch types (#2697) (#2698)
* Update helpers to use correct multisearch types

The spec combined definitions for search and multisearch bodies in
https://github.com/elastic/elasticsearch-specification/pull/2960.

* Stop copying project files to Dockerfile

Slightly faster run times for codegen, hopefully.

(cherry picked from commit b2a490718d)

Co-authored-by: Josh Mock <joshua.mock@elastic.co>
2025-04-04 12:33:43 -05:00
1fec78ed36 Merge serverless functionality from @elastic/elasticsearch-serverless (#2695) (#2696)
* Expose a serverMode option to enable serverless-friendly defaults

* Update basic config docs to note how the serverMode flag works

* Docs cleanup

* Add another note to docs about connecting to serverless

(cherry picked from commit e8dc747c61)

Co-authored-by: Josh Mock <joshua.mock@elastic.co>
2025-04-03 14:43:45 -05:00
a3989d538c replace mis-converted table (#2685) (#2693)
(cherry picked from commit c5f9625463)

Co-authored-by: Marci W <333176+marciw@users.noreply.github.com>
2025-04-01 10:37:08 -05:00
41cb67e9df Auto-generated API code (#2681) 2025-03-24 12:36:12 -05:00
652fd8cec9 Updates navigation titles and descriptions for release notes (#2665) (#2671)
(cherry picked from commit 88270bf354)

Co-authored-by: Kaarina Tungseth <kaarina.tungseth@elastic.co>
2025-03-21 12:52:35 -05:00
844f4e6b0d [docs] Miscellaneous docs clean up (#2663) (#2672)
* remove unused substitutions

* move images

(cherry picked from commit 9de4dc5009)

Co-authored-by: Colleen McGinnis <colleen.mcginnis@elastic.co>
2025-03-21 12:52:07 -05:00
4d60acb5cd Assume codegen renders markdown, not asciidoc (#2664) (#2666)
* Assume codegen renders markdown, not asciidoc

* Drop accidental local dev tweak

(cherry picked from commit afc83338b0)

Co-authored-by: Josh Mock <joshua.mock@elastic.co>
2025-03-21 12:45:21 -05:00
1337d4332f SPDX license format (#2667) (#2668)
* Switch to SPDX license format for all non-codegen files

* Add test to ensure all committed JS files have SPDX header

(cherry picked from commit 461f9b7f66)

Co-authored-by: Josh Mock <joshua.mock@elastic.co>
2025-03-21 12:40:42 -05:00
d5552dca2a Auto-generated API code (#2657) 2025-03-21 12:34:10 -05:00
8ca68a4178 [docs] Clean up cross-repo links (#2640)
* clean up cross-repo links

* add docs-content to cross_links
2025-03-03 15:28:38 -06:00
3e5e568c07 [docs] Migrate docs from AsciiDoc to Markdown (#2635)
* delete asciidoc files

* add migrated files

* Apply suggestions from review

Co-authored-by: Josh Mock <josh@joshmock.com>

* Apply suggestions from review

Co-authored-by: Josh Mock <josh@joshmock.com>

* add the new ci checks (#2634)

---------

Co-authored-by: Marci W <333176+marciw@users.noreply.github.com>
Co-authored-by: Josh Mock <josh@joshmock.com>
2025-02-27 12:51:14 -05:00
197 changed files with 33624 additions and 10037 deletions

View File

@ -12,5 +12,3 @@ WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . .

View File

@ -25,6 +25,3 @@ USER ${BUILDER_UID}:${BUILDER_GID}
# install dependencies
COPY package.json .
RUN npm install
# copy project files
COPY . .

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* global $ argv */
@ -123,7 +109,7 @@ async function codegen (args) {
await $`rm -rf ${join(import.meta.url, '..', 'src', 'api')}`
await $`mkdir ${join(import.meta.url, '..', 'src', 'api')}`
await $`cp -R ${join(import.meta.url, '..', '..', 'elastic-client-generator-js', 'output')}/* ${join(import.meta.url, '..', 'src', 'api')}`
await $`mv ${join(import.meta.url, '..', 'src', 'api', 'reference.asciidoc')} ${join(import.meta.url, '..', 'docs', 'reference.asciidoc')}`
await $`mv ${join(import.meta.url, '..', 'src', 'api', 'reference.md')} ${join(import.meta.url, '..', 'docs', 'reference', 'api-reference.md')}`
await $`npm run build`
// run docs example generation

View File

@ -83,6 +83,9 @@ jobs:
run: |
npm run license-checker
- name: SPDX header check
run: npm run license-header
test-bun:
name: Test Bun
runs-on: ${{ matrix.os }}

View File

@ -23,38 +23,19 @@ jobs:
- run: npm install -g npm
- run: npm install
- run: npm test
- name: npm publish
run: |
version=$(jq -r .version package.json)
tag_meta=$(echo "$version" | cut -s -d '-' -f2)
if [[ -z "$tag_meta" ]]; then
npm publish --provenance --access public
else
tag=$(echo "$tag_meta" | cut -d '.' -f1)
npm publish --provenance --access public --tag "$tag"
fi
- run: npm publish --provenance --access public --tag alpha
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Publish version on GitHub
run: |
version=$(jq -r .version package.json)
tag_meta=$(echo "$version" | cut -s -d '-' -f2)
if [[ -z "$tag_meta" ]]; then
gh release create \
-n "[Changelog](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/$BRANCH_NAME/changelog-client.html)"
--target "$BRANCH_NAME" \
--title "v$version" \
"v$version"
else
tag_main=$(echo "$version" | cut -d '-' -f1)
gh release create \
-n "This is a $tag_main pre-release. Changes may not be stable." \
--latest=false \
--prerelease \
--target "$BRANCH_NAME" \
--title "v$version" \
"v$version"
fi
gh release create \
-n "This is a 9.0.0 pre-release alpha. Changes may not be stable." \
--latest=false \
--prerelease \
--target "$BRANCH_NAME" \
--title "v$version" \
"v$version"
env:
BRANCH_NAME: ${{ github.event.inputs.branch }}
GH_TOKEN: ${{ github.token }}

View File

@ -1,269 +0,0 @@
[[basic-config]]
=== Basic configuration
This page shows you the possible basic configuration options that the clients
offers.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' },
maxRetries: 5,
sniffOnStart: true
})
----
[cols=2*]
|===
|`node` or `nodes`
a|The Elasticsearch endpoint to use. +
It can be a single string or an array of strings:
[source,js]
----
node: 'http://localhost:9200'
----
Or it can be an object (or an array of objects) that represents the node:
[source,js]
----
node: {
url: new URL('http://localhost:9200'),
tls: 'tls options',
agent: 'http agent options',
id: 'custom node id',
headers: { 'custom': 'headers' }
roles: {
master: true,
data: true,
ingest: true,
ml: false
}
}
----
|`auth`
a|Your authentication data. You can use both basic authentication and
{ref}/security-api-create-api-key.html[ApiKey]. +
See <<authentication,Authentication>> for more details. +
_Default:_ `null`
Basic authentication:
[source,js]
----
auth: {
username: 'elastic',
password: 'changeme'
}
----
{ref}/security-api-create-api-key.html[ApiKey] authentication:
[source,js]
----
auth: {
apiKey: 'base64EncodedKey'
}
----
Bearer authentication, useful for https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-service-token.html[service account tokens]. Be aware that it does not handle automatic token refresh:
[source,js]
----
auth: {
bearer: 'token'
}
----
|`maxRetries`
|`number` - Max number of retries for each request. +
_Default:_ `3`
|`requestTimeout`
|`number` - Max request timeout in milliseconds for each request. +
_Default:_ No value
|`pingTimeout`
|`number` - Max ping request timeout in milliseconds for each request. +
_Default:_ `3000`
|`sniffInterval`
|`number, boolean` - Perform a sniff operation every `n` milliseconds. Sniffing might not be the best solution for you, take a look https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how[here] to know more. +
_Default:_ `false`
|`sniffOnStart`
|`boolean` - Perform a sniff once the client is started. Sniffing might not be the best solution for you, take a look https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how[here] to know more. +
_Default:_ `false`
|`sniffEndpoint`
|`string` - Endpoint to ping during a sniff. +
_Default:_ `'_nodes/_all/http'`
|`sniffOnConnectionFault`
|`boolean` - Perform a sniff on connection fault. Sniffing might not be the best solution for you, take a look https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how[here] to know more. +
_Default:_ `false`
|`resurrectStrategy`
|`string` - Configure the node resurrection strategy. +
_Options:_ `'ping'`, `'optimistic'`, `'none'` +
_Default:_ `'ping'`
|`suggestCompression`
|`boolean` - Adds `accept-encoding` header to every request. +
_Default:_ `false`
|`compression`
|`string, boolean` - Enables gzip request body compression. +
_Options:_ `'gzip'`, `false` +
_Default:_ `false`
|`tls`
|`http.SecureContextOptions` - tls https://nodejs.org/api/tls.html[configuraton]. +
_Default:_ `null`
|`proxy`
a|`string, URL` - If you are using an http(s) proxy, you can put its url here.
The client will automatically handle the connection to it. +
_Default:_ `null`
[source,js]
----
const client = new Client({
node: 'http://localhost:9200',
proxy: 'http://localhost:8080'
})
// Proxy with basic authentication
const client = new Client({
node: 'http://localhost:9200',
proxy: 'http://user:pwd@localhost:8080'
})
----
|`agent`
a|`http.AgentOptions, function` - http agent https://nodejs.org/api/http.html#http_new_agent_options[options],
or a function that returns an actual http agent instance. If you want to disable the http agent use entirely
(and disable the `keep-alive` feature), set the agent to `false`. +
_Default:_ `null`
[source,js]
----
const client = new Client({
node: 'http://localhost:9200',
agent: { agent: 'options' }
})
const client = new Client({
node: 'http://localhost:9200',
// the function takes as parameter the option
// object passed to the Connection constructor
agent: (opts) => new CustomAgent()
})
const client = new Client({
node: 'http://localhost:9200',
// Disable agent and keep-alive
agent: false
})
----
|`nodeFilter`
a|`function` - Filters which node not to use for a request. +
_Default:_
[source,js]
----
function defaultNodeFilter (node) {
// avoid master only nodes
if (node.roles.master === true &&
node.roles.data === false &&
node.roles.ingest === false) {
return false
}
return true
}
----
|`nodeSelector`
a|`function` - custom selection strategy. +
_Options:_ `'round-robin'`, `'random'`, custom function +
_Default:_ `'round-robin'` +
_Custom function example:_
[source,js]
----
function nodeSelector (connections) {
const index = calculateIndex()
return connections[index]
}
----
|`generateRequestId`
a|`function` - function to generate the request id for every request, it takes
two parameters, the request parameters and options. +
By default it generates an incremental integer for every request. +
_Custom function example:_
[source,js]
----
function generateRequestId (params, options) {
// your id generation logic
// must be syncronous
return 'id'
}
----
|`name`
|`string, symbol` - The name to identify the client instance in the events. +
_Default:_ `elasticsearch-js`
|`opaqueIdPrefix`
|`string` - A string that will be use to prefix any `X-Opaque-Id` header. +
See https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/observability.html#_x-opaque-id_support[`X-Opaque-Id` support] for more details. +
_Default:_ `null`
|`headers`
|`object` - A set of custom headers to send in every request. +
_Default:_ `{}`
|`context`
|`object` - A custom object that you can use for observability in your events.
It will be merged with the API level context option. +
_Default:_ `null`
|`enableMetaHeader`
|`boolean` - If true, adds an header named `'x-elastic-client-meta'`, containing some minimal telemetry data,
such as the client and platform version. +
_Default:_ `true`
|`cloud`
a|`object` - Custom configuration for connecting to
https://cloud.elastic.co[Elastic Cloud]. See https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/auth-reference.html[Authentication]
for more details. +
_Default:_ `null` +
_Cloud configuration example:_
[source,js]
----
const client = new Client({
cloud: {
id: '<cloud-id>'
},
auth: {
username: 'elastic',
password: 'changeme'
}
})
----
|`disablePrototypePoisoningProtection`
|`boolean`, `'proto'`, `'constructor'` - The client can protect you against prototype poisoning attacks. Read https://web.archive.org/web/20200319091159/https://hueniverse.com/square-brackets-are-the-enemy-ff5b9fd8a3e8?gi=184a27ee2a08[this article] to learn more about this security concern. If needed, you can enable prototype poisoning protection entirely (`false`) or one of the two checks (`'proto'` or `'constructor'`). For performance reasons, it is disabled by default. Read the `secure-json-parse` https://github.com/fastify/secure-json-parse[documentation] to learn more. +
_Default:_ `true`
|`caFingerprint`
|`string` - If configured, verify that the fingerprint of the CA certificate that has signed the certificate of the server matches the supplied fingerprint. Only accepts SHA256 digest fingerprints. +
_Default:_ `null`
|`maxResponseSize`
|`number` - When configured, it verifies that the uncompressed response size is lower than the configured number, if it's higher it will abort the request. It cannot be higher than buffer.constants.MAX_STRING_LENGTH +
_Default:_ `null`
|`maxCompressedResponseSize`
|`number` - When configured, it verifies that the compressed response size is lower than the configured number, if it's higher it will abort the request. It cannot be higher than buffer.constants.MAX_LENGTH +
_Default:_ `null`
|===

View File

@ -1,966 +0,0 @@
[[changelog-client]]
== Release notes
[discrete]
=== 9.0.0
[discrete]
==== Breaking changes
[discrete]
===== Drop support for deprecated `body` parameter
In 8.0, the top-level `body` parameter that was available on all API functions <<remove-body-key,was deprecated>>. In 9.0 this property is completely removed.
[discrete]
===== Remove the default 30-second timeout on all requests sent to Elasticsearch
Setting HTTP timeouts on Elasticsearch requests goes against Elastic's recommendations. See <<timeout-best-practices>> for more information.
[discrete]
=== 8.17.1
[discrete]
==== Fixes
[discrete]
===== Improved support for Elasticsearch `v8.17`
Updated TypeScript types based on fixes and improvements to the Elasticsearch specification.
[discrete]
===== Report correct transport connection type in telemetry
The client's telemetry reporting mechanism was incorrectly reporting all traffic as using `HttpConnection` when the default is `UndiciConnection`. https://github.com/elastic/elasticsearch-js/issues/2324[#2324]
[discrete]
=== 8.17.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.17`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.17/release-notes-8.17.0.html[here].
[discrete]
=== 8.16.4
[discrete]
==== Fixes
[discrete]
===== Improved support for Elasticsearch `v8.16`
Updated TypeScript types based on fixes and improvements to the Elasticsearch specification.
[discrete]
===== Report correct transport connection type in telemetry
The client's telemetry reporting mechanism was incorrectly reporting all traffic as using `HttpConnection` when the default is `UndiciConnection`. https://github.com/elastic/elasticsearch-js/issues/2324[#2324]
[discrete]
=== 8.16.3
[discrete]
==== Fixes
[discrete]
===== Improved support for Elasticsearch `v8.16`
Updated TypeScript types based on fixes and improvements to the Elasticsearch specification.
[discrete]
=== 8.16.2
[discrete]
==== Fixes
[discrete]
===== Improved support for Elasticsearch `v8.16`
Updated TypeScript types based on fixes and improvements to the Elasticsearch specification.
[discrete]
===== Drop testing artifacts from npm package
Tap, the unit testing tool used by this project, was recently upgraded and started writing to a `.tap` directory. Since tests are run prior to an `npm publish` in CI, this directory was being included in the published package and bloating its size.
[discrete]
=== 8.16.1
[discrete]
==== Fixes
[discrete]
===== Fix ECMAScript imports
Fixed package configuration to correctly support native ECMAScript `import` syntax.
[discrete]
=== 8.16.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.16`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.16/release-notes-8.16.0.html[here].
[discrete]
===== Support Apache Arrow in ES|QL helper
The ES|QL helper can now return results as an Apache Arrow `Table` or `RecordBatchReader`, which enables high-performance calculations on ES|QL results, even if the response data is larger than the system's available memory. See <<esql-helper>> for more information.
[discrete]
==== Fixes
[discrete]
===== Pass prototype poisoning options to serializer correctly
The client's `disablePrototypePoisoningProtection` option was set to `true` by default, but when it was set to any other value it was ignored, making it impossible to enable prototype poisoning protection without providing a custom serializer implementation.
[discrete]
=== 8.15.3
[discrete]
==== Fixes
[discrete]
===== Improved support for Elasticsearch `v8.15`
Updated TypeScript types based on fixes and improvements to the Elasticsearch specification.
[discrete]
===== Drop testing artifacts from npm package
Tap, the unit testing tool, was recently upgraded and started writing to a `.tap` directory. Since tests are run prior to an `npm publish` in CI, this directory was being included in the published package and bloating its size.
[discrete]
=== 8.15.2
[discrete]
==== Fixes
[discrete]
===== Improved support for Elasticsearch `v8.15`
Updated TypeScript types based on fixes and improvements to the Elasticsearch specification.
[discrete]
=== 8.15.1
[discrete]
==== Fixes
[discrete]
===== Improved support for Elasticsearch `v8.15`
Updated TypeScript types based on fixes and improvements to the Elasticsearch specification.
[discrete]
=== 8.15.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.15.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.15/release-notes-8.15.0.html[here].
[discrete]
===== OpenTelemetry zero-code instrumentation support
For those that use an observability service that supports OpenTelemetry spans, the client will now automatically generate traces for each Elasticsearch request it makes.
See {jsclient}/observability.html#_opentelemetry[the docs]
for more information.
[discrete]
=== 8.14.1
[discrete]
==== Features
[discrete]
===== Improved support for Elasticsearch `8.14`
Updated types based on fixes and changes to the Elasticsearch specification.
[discrete]
=== 8.14.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.14.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.14/release-notes-8.14.0.html[here].
[discrete]
===== ES|QL object API helper
A helper method has been added that parses the response of an ES|QL query and converts it into an array of objects.
A TypeScript type parameter can also be provided to improve developer experience when working with the result. https://github.com/elastic/elasticsearch-js/pull/2238[#2238]
[discrete]
===== `onSuccess` callback added to bulk helper
The bulk helper now supports an `onSuccess` callback that will be called for each successful operation. https://github.com/elastic/elasticsearch-js/pull/2199[#2199]
[discrete]
===== Request retries are more polite
https://github.com/elastic/elastic-transport-js/releases/tag/v8.6.0[`@elastic/transport` v8.6.0] was released, which refactored when and how failed requests are retried. Timed-out requests are no longer retried by default, and retries now use exponential backoff rather than running immediately.
[discrete]
=== 8.13.1
[discrete]
==== Fixes
[discrete]
===== Pin @elastic/transport to `~8.4.1`
Switching from `^8.4.1` to `~8.4.1` ensures 8.13 client users are not required to update to Node.js v18+, which is a new requirement set by `@elastic/transport` v8.5.0. See https://github.com/elastic/elastic-transport-js/issues/91[elastic/elastic-transport-js#91] for details.
v8.13.0 was also released depending on v8.4.0 of `@elastic/transport` instead of v8.4.1, which was unintentional.
[discrete]
=== 8.13.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.13.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.13/release-notes-8.13.0.html[here].
[discrete]
==== Fixes
[discrete]
===== Ensure new connections inherit client's set defaults https://github.com/elastic/elasticsearch-js/pull/2159[#2159]
When instantiating a client, any connection-related defaults (e.g. `requestTimeout`) set on that client instance would not be inherited by nodes if they were entered as strings rather than a `ConnectionOptions` object.
[discrete]
=== 8.12.3
[discrete]
==== Fixes
[discrete]
===== Bump @elastic/transport to `~8.4.1`
Switching from `^8.4.1` to `~8.4.1` ensures 8.12 client users are not required to update to Node.js v18+, which is a new requirement set by `@elastic/transport` v8.5.0. See https://github.com/elastic/elastic-transport-js/issues/91[elastic/elastic-transport-js#91] for details.
[discrete]
=== 8.12.2
[discrete]
==== Fixes
[discrete]
===== Upgrade transport to 8.4.1 https://github.com/elastic/elasticsearch-js/pull/2137[#2137]
Upgrades `@elastic/transport` to 8.4.1 to resolve https://github.com/elastic/elastic-transport-js/pull/83[a bug] where arrays in error diagnostics were unintentionally transformed into objects.
[discrete]
=== 8.12.1
[discrete]
==== Fixes
[discrete]
===== Fix hang in bulk helper semaphore https://github.com/elastic/elasticsearch-js/pull/2027[#2027]
The failing state could be reached when a server's response times are slower than flushInterval.
[discrete]
=== 8.12.0
[discrete]
=== Features
[discrete]
===== Support for Elasticsearch `v8.12.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.12/release-notes-8.12.0.html[here].
[discrete]
=== 8.11.1
[discrete]
==== Fixes
[discrete]
===== Bump @elastic/transport to `~8.4.0`
Switching from `^8.4.0` to `~8.4.0` ensures 8.11 client users are not required to update to Node.js v18+, which is a new requirement set by `@elastic/transport` v8.5.0. See https://github.com/elastic/elastic-transport-js/issues/91[elastic/elastic-transport-js#91] for details.
[discrete]
=== 8.11.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.11.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.11/release-notes-8.11.0.html[here].
[discrete]
===== Enhanced support for redacting potentially sensitive data https://github.com/elastic/elasticsearch-js/pull/2095[#2095]
`@elastic/transport` https://github.com/elastic/elastic-transport-js/releases/tag/v8.4.0[version 8.4.0] introduces enhanced measures for ensuring that request metadata attached to some `Error` objects is redacted. This functionality is primarily to address custom logging solutions that don't use common serialization methods like `JSON.stringify`, `console.log`, or `util.inspect`, which were already accounted for.
See <<redaction>> for more information.
[discrete]
=== 8.10.1
[discrete]
==== Fixes
[discrete]
===== Bump @elastic/transport to `~8.3.4`
Switching from `^8.3.4` to `~8.3.4` ensures 8.10 client users are not required to update to Node.js v18+, which is a new requirement set by `@elastic/transport` v8.5.0. See https://github.com/elastic/elastic-transport-js/issues/91[elastic/elastic-transport-js#91] for details.
[discrete]
=== 8.10.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.10.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.10/release-notes-8.10.0.html[here].
[discrete]
=== 8.9.2
[discrete]
==== Fixes
[discrete]
===== Bump @elastic/transport to `~8.3.4`
Switching from `^8.3.4` to `~8.3.4` ensures 8.9 client users are not required to update to Node.js v18+, which is a new requirement set by `@elastic/transport` v8.5.0. See https://github.com/elastic/elastic-transport-js/issues/91[elastic/elastic-transport-js#91] for details.
[discrete]
=== 8.9.1
[discrete]
==== Fixes
[discrete]
===== Upgrade Transport https://github.com/elastic/elasticsearch-js/pull/1968[#1968]
Upgrades `@elastic/transport` to the latest patch release to fix https://github.com/elastic/elastic-transport-js/pull/69[a bug] that could cause the process to exit when handling malformed `HEAD` requests.
[discrete]
=== 8.9.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.9.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.9/release-notes-8.9.0.html[here].
[discrete]
===== Allow document to be overwritten in `onDocument` iteratee of bulk helper https://github.com/elastic/elasticsearch-js/pull/1732[#1732]
In the {jsclient}/client-helpers.html#bulk-helper[bulk helper], documents could not be modified before being sent to Elasticsearch. It is now possible to {jsclient}/client-helpers.html#_modifying_a_document_before_operation[modify a document] before sending it.
[discrete]
==== Fixes
[discrete]
===== Updated `user-agent` header https://github.com/elastic/elasticsearch-js/pull/1954[#1954]
The `user-agent` header the client used to connect to Elasticsearch was using a non-standard format that has been improved.
[discrete]
=== 8.8.2
[discrete]
==== Fixes
[discrete]
===== Bump @elastic/transport to `~8.3.2`
Switching from `^8.3.2` to `~8.3.2` ensures 8.8 client users are not required to update to Node.js v18+, which is a new requirement set by `@elastic/transport` v8.5.0. See https://github.com/elastic/elastic-transport-js/issues/91[elastic/elastic-transport-js#91] for details.
[discrete]
=== 8.8.1
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.8.1`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.8/release-notes-8.8.1.html[here].
[discrete]
==== Fixes
[discrete]
===== Fix index drift bug in bulk helper https://github.com/elastic/elasticsearch-js/pull/1759[#1759]
Fixes a bug in the bulk helper that would cause `onDrop` to send back the wrong JSON document or error on a nonexistent document when an error occurred on a bulk HTTP request that contained a `delete` action.
[discrete]
===== Fix a memory leak caused by an outdated version of Undici https://github.com/elastic/elasticsearch-js/pull/1902[#1902]
Undici 5.5.1, used by https://github.com/elastic/elastic-transport-js[elastic-transport-js], could create a memory leak when a high volume of requests created too many HTTP `abort` listeners. Upgrading Undici to 5.22.1 removed the memory leak.
[discrete]
=== 8.8.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.8.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.8/release-notes-8.8.0.html[here].
[discrete]
==== Fixes
[discrete]
===== Fix type declarations for legacy types with a body key https://github.com/elastic/elasticsearch-js/pull/1784[#1784]
Prior releases contained a bug where type declarations for legacy types that include a `body` key were not actually importing the type that includes the `body` key.
[discrete]
=== 8.7.3
[discrete]
==== Fixes
[discrete]
===== Bump @elastic/transport to `~8.3.1`
Switching from `^8.3.1` to `~8.3.1` ensures 8.7 client users are not required to update to Node.js v18+, which is a new requirement set by `@elastic/transport` v8.5.0. See https://github.com/elastic/elastic-transport-js/issues/91[elastic/elastic-transport-js#91] for details.
[discrete]
=== 8.7.0
[discrete]
===== Support for Elasticsearch `v8.7.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.7/release-notes-8.7.0.html[here].
[discrete]
=== 8.6.1
[discrete]
==== Fixes
[discrete]
===== Bump @elastic/transport to `~8.3.1`
Switching from `^8.3.1` to `~8.3.1` ensures 8.6 client users are not required to update to Node.js v18+, which is a new requirement set by `@elastic/transport` v8.5.0. See https://github.com/elastic/elastic-transport-js/issues/91[elastic/elastic-transport-js#91] for details.
[discrete]
=== 8.6.0
[discrete]
===== Bump @elastic/transport to 8.3.1+ https://github.com/elastic/elasticsearch-js/pull/1802[#1802]
The `@elastic/transport` dependency has been bumped to `~8.3.1` to ensure
fixes to the `maxResponseSize` option are available in the client.
[discrete]
===== Support for Elasticsearch `v8.6.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.6/release-notes-8.6.0.html[here].
[discrete]
=== 8.5.0
[discrete]
===== Support for Elasticsearch `v8.5.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.5/release-notes-8.5.0.html[here].
[discrete]
=== 8.4.0
[discrete]
===== Support for Elasticsearch `v8.4.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.4/release-notes-8.4.0.html[here].
[discrete]
=== 8.2.1
[discrete]
==== Fixes
[discrete]
===== Support for Elasticsearch `v8.2.1`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.2/release-notes-8.2.1.html[here].
[discrete]
===== Fix ndjson APIs https://github.com/elastic/elasticsearch-js/pull/1688[#1688]
The previous release contained a bug that broken ndjson APIs.
We have released `v8.2.0-patch.1` to address this.
This fix is the same as the one we have released and we strongly recommend upgrading to this version.
[discrete]
===== Fix node shutdown apis https://github.com/elastic/elasticsearch-js/pull/1697[#1697]
The shutdown APIs wheren't complete, this fix completes them.
[discrete]
==== Types: move query keys to body https://github.com/elastic/elasticsearch-js/pull/1693[#1693]
The types definitions where wrongly representing the types of fields present in both query and body.
[discrete]
=== 8.2.0
[discrete]
==== Breaking changes
[discrete]
===== Drop Node.js v12 https://github.com/elastic/elasticsearch-js/pull/1670[#1670]
According to our https://github.com/elastic/elasticsearch-js#nodejs-support[Node.js support matrix].
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.2`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.2/release-notes-8.2.0.html[here].
[discrete]
===== More lenient parameter checks https://github.com/elastic/elasticsearch-js/pull/1662[#1662]
When creating a new client, an `undefined` `caFingerprint` no longer trigger an error for a http connection.
[discrete]
===== Update TypeScript docs and export estypes https://github.com/elastic/elasticsearch-js/pull/1675[#1675]
You can import the full TypeScript requests & responses definitions as it follows:
[source,ts]
----
import { estypes } from '@elastic/elasticsearch'
----
If you need the legacy definitions with the body, you can do the following:
[source,ts]
----
import { estypesWithBody } from '@elastic/elasticsearch'
----
[discrete]
==== Fixes
[discrete]
===== Updated hpagent to the latest version https://github.com/elastic/elastic-transport-js/pull/49[transport/#49]
You can fing the related changes https://github.com/delvedor/hpagent/releases/tag/v1.0.0[here].
[discrete]
=== 8.1.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.1`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.1/release-notes-8.1.0.html[here].
[discrete]
===== Export SniffingTransport https://github.com/elastic/elasticsearch-js/pull/1653[#1653]
Now the client exports the SniffingTransport class.
[discrete]
==== Fixes
[discrete]
===== Fix onFlushTimeout timer not being cleared when upstream errors https://github.com/elastic/elasticsearch-js/pull/1616[#1616]
Fixes a memory leak caused by an error in the upstream dataset of the bulk helper.
[discrete]
===== Cleanup abort listener https://github.com/elastic/elastic-transport-js/pull/42[transport/#42]
The legacy http client was not cleaning up the abort listener, which could cause a memory leak.
[discrete]
===== Improve undici performances https://github.com/elastic/elastic-transport-js/pull/41[transport/#41]
Improve the stream body collection and keep alive timeout.
[discrete]
=== 8.0.0
[discrete]
==== Features
[discrete]
===== Support for Elasticsearch `v8.0`
You can find all the API changes
https://www.elastic.co/guide/en/elasticsearch/reference/8.0/release-notes-8.0.0.html[here].
[discrete]
===== Drop old typescript definitions
*Breaking: Yes* | *Migration effort: Medium*
The current TypeScript definitions will be removed from the client, and the new definitions, which contain request and response definitions as well will be shipped by default.
[discrete]
===== Drop callback-style API
*Breaking: Yes* | *Migration effort: Large*
Maintaining both API styles is not a problem per se, but it makes error handling more convoluted due to async stack traces.
Moving to a full-promise API will solve this issue.
[source,js]
----
// callback-style api
client.search({ params }, { options }, (err, result) => {
console.log(err || result)
})
// promise-style api
client.search({ params }, { options })
.then(console.log)
.catch(console.log)
// async-style (sugar syntax on top of promises)
const response = await client.search({ params }, { options })
console.log(response)
----
If you are already using the promise-style API, this won't be a breaking change for you.
[discrete]
===== Remove the current abort API and use the new AbortController standard
*Breaking: Yes* | *Migration effort: Small*
The old abort API makes sense for callbacks but it's annoying to use with promises
[source,js]
----
// callback-style api
const request = client.search({ params }, { options }, (err, result) => {
console.log(err) // RequestAbortedError
})
request.abort()
// promise-style api
const promise = client.search({ params }, { options })
promise
.then(console.log)
.catch(console.log) // RequestAbortedError
promise.abort()
----
Node v12 has added the standard https://nodejs.org/api/globals.html#globals_class_abortcontroller[`AbortController`] API which is designed to work well with both callbacks and promises.
[source,js]
----
const ac = new AbortController()
client.search({ params }, { signal: ac.signal })
.then(console.log)
.catch(console.log) // RequestAbortedError
ac.abort()
----
[discrete]
[[remove-body-key]]
===== Remove the body key from the request
*Breaking: Yes* | *Migration effort: Small*
Thanks to the new types we are developing now we know exactly where a parameter should go.
The client API leaks HTTP-related notions in many places, and removing them would definitely improve the DX.
This could be a rather big breaking change, so a double solution could be used during the 8.x lifecycle. (accepting body keys without them being wrapped in the body as well as the current solution).
To convert code from 7.x, you need to remove the `body` parameter in all the endpoints request.
For instance, this is an example for the `search` endpoint:
[source,js]
----
// from
const response = await client.search({
index: 'test',
body: {
query: {
match_all: {}
}
}
})
// to
const response = await client.search({
index: 'test',
query: {
match_all: {}
}
})
----
[discrete]
===== Migrate to new separate transport
*Breaking: Yes* | *Migration effort: Small to none*
The separated transport has been rewritten in TypeScript and has already dropped the callback style API.
Given that now is separated, most of the Elasticsearch specific concepts have been removed, and the client will likely need to extend parts of it for reintroducing them.
If you weren't extending the internals of the client, this won't be a breaking change for you.
[discrete]
===== The returned value of API calls is the body and not the HTTP related keys
*Breaking: Yes* | *Migration effort: Small*
The client API leaks HTTP-related notions in many places, and removing them would definitely improve the DX.
The client will expose a new request-specific option to still get the full response details.
The new behaviour returns the `body` value directly as response.
If you want to have the 7.x response format, you need to add `meta : true` in the request.
This will return all the HTTP meta information, including the `body`.
For instance, this is an example for the `search` endpoint:
[source,js]
----
// from
const response = await client.search({
index: 'test',
body: {
query: {
match_all: {}
}
}
})
console.log(response) // { body: SearchResponse, statusCode: number, headers: object, warnings: array }
// to
const response = await client.search({
index: 'test',
query: {
match_all: {}
}
})
console.log(response) // SearchResponse
// with a bit of TypeScript and JavaScript magic...
const response = await client.search({
index: 'test',
query: {
match_all: {}
}
}, {
meta: true
})
console.log(response) // { body: SearchResponse, statusCode: number, headers: object, warnings: array }
----
[discrete]
===== Use a weighted connection pool
*Breaking: Yes* | *Migration effort: Small to none*
Move from the current cluster connection pool to a weight-based implementation.
This new implementation offers better performances and runs less code in the background, the old connection pool can still be used.
If you weren't extending the internals of the client, this won't be a breaking change for you.
[discrete]
===== Migrate to the "undici" http client
*Breaking: Yes* | *Migration effort: Small to none*
By default, the HTTP client will no longer be the default Node.js HTTP client, but https://github.com/nodejs/undici[undici] instead.
Undici is a brand new HTTP client written from scratch, it offers vastly improved performances and has better support for promises.
Furthermore, it offers comprehensive and predictable error handling. The old HTTP client can still be used.
If you weren't extending the internals of the client, this won't be a breaking change for you.
[discrete]
===== Drop support for old camelCased keys
*Breaking: Yes* | *Migration effort: Medium*
Currently, every path or query parameter could be expressed in both `snake_case` and `camelCase`. Internally the client will convert everything to `snake_case`.
This was done in an effort to reduce the friction of migrating from the legacy to the new client, but now it no longer makes sense.
If you are already using `snake_case` keys, this won't be a breaking change for you.
[discrete]
===== Rename `ssl` option to `tls`
*Breaking: Yes* | *Migration effort: Small*
People usually refers to this as `tls`, furthermore, internally we use the tls API and Node.js refers to it as tls everywhere.
[source,js]
----
// before
const client = new Client({
node: 'https://localhost:9200',
ssl: {
rejectUnauthorized: false
}
})
// after
const client = new Client({
node: 'https://localhost:9200',
tls: {
rejectUnauthorized: false
}
})
----
[discrete]
===== Remove prototype poisoning protection
*Breaking: Yes* | *Migration effort: Small*
Prototype poisoning protection is very useful, but it can cause performances issues with big payloads.
In v8 it will be removed, and the documentation will show how to add it back with a custom serializer.
[discrete]
===== Remove client extensions API
*Breaking: Yes* | *Migration effort: Large*
Nowadays the client support the entire Elasticsearch API, and the `transport.request` method can be used if necessary. The client extensions API have no reason to exist.
[source,js]
----
client.extend('utility.index', ({ makeRequest }) => {
return function _index (params, options) {
// your code
}
})
client.utility.index(...)
----
If you weren't using client extensions, this won't be a breaking change for you.
[discrete]
===== Move to TypeScript
*Breaking: No* | *Migration effort: None*
The new separated transport is already written in TypeScript, and it makes sense that the client v8 will be fully written in TypeScript as well.
[discrete]
===== Move from emitter-like interface to a diagnostic method
*Breaking: Yes* | *Migration effort: Small*
Currently, the client offers a subset of methods of the `EventEmitter` class, v8 will ship with a `diagnostic` property which will be a proper event emitter.
[source,js]
----
// from
client.on('request', console.log)
// to
client.diagnostic.on('request', console.log)
----
[discrete]
===== Remove username & password properties from Cloud configuration
*Breaking: Yes* | *Migration effort: Small*
The Cloud configuration does not support ApiKey and Bearer auth, while the `auth` options does.
There is no need to keep the legacy basic auth support in the cloud configuration.
[source,js]
----
// before
const client = new Client({
cloud: {
id: '<cloud-id>',
username: 'elastic',
password: 'changeme'
}
})
// after
const client = new Client({
cloud: {
id: '<cloud-id>'
},
auth: {
username: 'elastic',
password: 'changeme'
}
})
----
If you are already passing the basic auth options in the `auth` configuration, this won't be a breaking change for you.
[discrete]
===== Calling `client.close` will reject new requests
Once you call `client.close` every new request after that will be rejected with a `NoLivingConnectionsError`. In-flight requests will be executed normally unless an in-flight request requires a retry, in which case it will be rejected.
[discrete]
===== Parameters rename
- `ilm.delete_lifecycle`: `policy` parameter has been renamed to `name`
- `ilm.get_lifecycle`: `policy` parameter has been renamed to `name`
- `ilm.put_lifecycle`: `policy` parameter has been renamed to `name`
- `snapshot.cleanup_repository`: `repository` parameter has been renamed to `name`
- `snapshot.create_repository`: `repository` parameter has been renamed to `name`
- `snapshot.delete_repository`: `repository` parameter has been renamed to `name`
- `snapshot.get_repository`: `repository` parameter has been renamed to `name`
- `snapshot.verify_repository`: `repository` parameter has been renamed to `name`
[discrete]
===== Removal of snake_cased methods
The v7 client provided snake_cased methods, such as `client.delete_by_query`. This is no longer supported, now only camelCased method are present.
So `client.delete_by_query` can be accessed with `client.deleteByQuery`

View File

@ -1,35 +0,0 @@
[[child]]
=== Creating a child client
There are some use cases where you may need multiple instances of the client.
You can easily do that by calling `new Client()` as many times as you need, but
you will lose all the benefits of using one single client, such as the long
living connections and the connection pool handling. To avoid this problem, the
client offers a `child` API, which returns a new client instance that shares the
connection pool with the parent client.
NOTE: The event emitter is shared between the parent and the child(ren). If you
extend the parent client, the child client will have the same extensions, while
if the child client adds an extension, the parent client will not be extended.
You can pass to the `child` every client option you would pass to a normal
client, but the connection pool specific options (`ssl`, `agent`, `pingTimeout`,
`Connection`, and `resurrectStrategy`).
CAUTION: If you call `close` in any of the parent/child clients, every client
will be closed.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<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)
----

View File

@ -1,12 +0,0 @@
[[client-configuration]]
== Configuration
The client is designed to be easily configured for your needs. In the following
section, you can see the possible options that you can use to configure it.
* <<basic-config>>
* <<advanced-config>>
* <<timeout-best-practices>>
* <<child>>
* <<client-testing>>

View File

@ -1,738 +0,0 @@
[[client-connecting]]
== Connecting
This page contains the information you need to connect and use the Client with
{es}.
**On this page**
* <<authentication, Authentication options>>
* <<client-usage, Using the client>>
* <<client-faas-env, Using the Client in a Function-as-a-Service Environment>>
* <<client-connect-proxy, Connecting through a proxy>>
* <<client-error-handling, Handling errors>>
* <<keep-alive, Keep-alive connections>>
* <<close-connections, Closing a client's connections>>
* <<product-check, Automatic product check>>
[[authentication]]
[discrete]
=== Authentication
This document contains code snippets to show you how to connect to various {es}
providers.
[discrete]
[[auth-ec]]
==== Elastic Cloud
If you are using https://www.elastic.co/cloud[Elastic Cloud], the client offers
an easy way to connect to it via the `cloud` option. You must pass the Cloud ID
that you can find in the cloud console, then your username and password inside
the `auth` option.
NOTE: When connecting to Elastic Cloud, the client will automatically enable
both request and response compression by default, since it yields significant
throughput improvements. Moreover, the client will also set the tls option
`secureProtocol` to `TLSv1_2_method` unless specified otherwise. You can still
override this option by configuring them.
IMPORTANT: Do not enable sniffing when using Elastic Cloud, since the nodes are
behind a load balancer, Elastic Cloud will take care of everything for you.
Take a look https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how[here]
to know more.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: {
id: '<cloud-id>'
},
auth: {
username: 'elastic',
password: 'changeme'
}
})
----
[discrete]
[[connect-self-managed-new]]
=== Connecting to a self-managed cluster
By default {es} will start with security features like authentication and TLS
enabled. To connect to the {es} cluster you'll need to configure the Node.js {es}
client to use HTTPS with the generated CA certificate in order to make requests
successfully.
If you're just getting started with {es} we recommend reading the documentation
on https://www.elastic.co/guide/en/elasticsearch/reference/current/settings.html[configuring]
and
https://www.elastic.co/guide/en/elasticsearch/reference/current/starting-elasticsearch.html[starting {es}]
to ensure your cluster is running as expected.
When you start {es} for the first time you'll see a distinct block like the one
below in the output from {es} (you may have to scroll up if it's been a while):
[source,sh]
----
-> Elasticsearch security features have been automatically configured!
-> Authentication is enabled and cluster connections are encrypted.
-> Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
lhQpLELkjkrawaBoaz0Q
-> HTTP CA certificate SHA-256 fingerprint:
a52dd93511e8c6045e21f16654b77c9ee0f34aea26d9f40320b531c474676228
...
----
Depending on the circumstances there are two options for verifying the HTTPS
connection, either verifying with the CA certificate itself or via the HTTP CA
certificate fingerprint.
[discrete]
[[auth-tls]]
==== TLS configuration
The generated root CA certificate can be found in the `certs` directory in your
{es} config location (`$ES_CONF_PATH/certs/http_ca.crt`). If you're running {es}
in Docker there is
https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html[additional documentation for retrieving the CA certificate].
Without any additional configuration you can specify `https://` node urls, and
the certificates used to sign these requests will be verified. To turn off
certificate verification, you must specify an `tls` object in the top level
config and set `rejectUnauthorized: false`. The default `tls` values are the
same that Node.js's https://nodejs.org/api/tls.html#tls_tls_connect_options_callback[`tls.connect()`]
uses.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
username: 'elastic',
password: 'changeme'
},
tls: {
ca: fs.readFileSync('./http_ca.crt'),
rejectUnauthorized: false
}
})
----
[discrete]
[[auth-ca-fingerprint]]
==== CA fingerprint
You can configure the client to only trust certificates that are signed by a specific CA certificate
(CA certificate pinning) by providing a `caFingerprint` option.
This will verify that the fingerprint of the CA certificate that has signed
the certificate of the server matches the supplied value.
You must configure a SHA256 digest.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://example.com'
auth: { ... },
// the fingerprint (SHA256) of the CA certificate that is used to sign
// the certificate that the Elasticsearch node presents for TLS.
caFingerprint: '20:0D:CA:FA:76:...',
tls: {
// might be required if it's a self-signed certificate
rejectUnauthorized: false
}
})
----
The certificate fingerprint can be calculated using `openssl x509` with the
certificate file:
[source,sh]
----
openssl x509 -fingerprint -sha256 -noout -in /path/to/http_ca.crt
----
If you don't have access to the generated CA file from {es} you can use the
following script to output the root CA fingerprint of the {es} instance with
`openssl s_client`:
[source,sh]
----
# Replace the values of 'localhost' and '9200' to the
# corresponding host and port values for the cluster.
openssl s_client -connect localhost:9200 -servername localhost -showcerts </dev/null 2>/dev/null \
| openssl x509 -fingerprint -sha256 -noout -in /dev/stdin
----
The output of `openssl x509` will look something like this:
[source,sh]
----
SHA256 Fingerprint=A5:2D:D9:35:11:E8:C6:04:5E:21:F1:66:54:B7:7C:9E:E0:F3:4A:EA:26:D9:F4:03:20:B5:31:C4:74:67:62:28
----
[discrete]
[[connect-no-security]]
=== Connecting without security enabled
WARNING: Running {es} without security enabled is not recommended.
If your cluster is configured with
https://www.elastic.co/guide/en/elasticsearch/reference/current/security-settings.html[security explicitly disabled]
then you can connect via HTTP:
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'http://example.com'
})
----
[discrete]
[[auth-strategies]]
=== Authentication strategies
Following you can find all the supported authentication strategies.
[discrete]
[[auth-apikey]]
==== ApiKey authentication
You can use the
{ref-7x}/security-api-create-api-key.html[ApiKey]
authentication by passing the `apiKey` parameter via the `auth` option. The
`apiKey` parameter can be either a base64 encoded string or an object with the
values that you can obtain from the
{ref-7x}/security-api-create-api-key.html[create api key endpoint].
NOTE: If you provide both basic authentication credentials and the ApiKey
configuration, the ApiKey takes precedence.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
apiKey: 'base64EncodedKey'
}
})
----
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
apiKey: {
id: 'foo',
api_key: 'bar'
}
}
})
----
[discrete]
[[auth-bearer]]
==== Bearer authentication
You can provide your credentials by passing the `bearer` token
parameter via the `auth` option.
Useful for https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-service-token.html[service account tokens].
Be aware that it does not handle automatic token refresh.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
bearer: 'token'
}
})
----
[discrete]
[[auth-basic]]
==== Basic authentication
You can provide your credentials by passing the `username` and `password`
parameters via the `auth` option.
NOTE: If you provide both basic authentication credentials and the Api Key
configuration, the Api Key will take precedence.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
username: 'elastic',
password: 'changeme'
}
})
----
Otherwise, you can provide your credentials in the node(s) URL.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://username:password@localhost:9200'
})
----
[discrete]
[[client-usage]]
=== Usage
Using the client is straightforward, it supports all the public APIs of {es},
and every method exposes the same signature.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const result = await client.search({
index: 'my-index',
query: {
match: { hello: 'world' }
}
})
----
The returned value of every API call is the response body from {es}.
If you need to access additonal metadata, such as the status code or headers,
you must specify `meta: true` in the request options:
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const result = await client.search({
index: 'my-index',
query: {
match: { hello: 'world' }
}
}, { meta: true })
----
In this case, the result will be:
[source,ts]
----
{
body: object | boolean
statusCode: number
headers: object
warnings: string[],
meta: object
}
----
NOTE: The body is a boolean value when you use `HEAD` APIs.
[discrete]
==== Aborting a request
If needed, you can abort a running request by using the `AbortController` standard.
CAUTION: If you abort a request, the request will fail with a
`RequestAbortedError`.
[source,js]
----
const AbortController = require('node-abort-controller')
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const abortController = new AbortController()
setImmediate(() => abortController.abort())
const result = await client.search({
index: 'my-index',
query: {
match: { hello: 'world' }
}
}, { signal: abortController.signal })
----
[discrete]
==== Request specific options
If needed you can pass request specific options in a second object:
[source,js]
----
const result = await client.search({
index: 'my-index',
body: {
query: {
match: { hello: 'world' }
}
}
}, {
ignore: [404],
maxRetries: 3
})
----
The supported request specific options are:
[cols=2*]
|===
|`ignore`
|`number[]` - HTTP status codes which should not be considered errors for this request. +
_Default:_ `null`
|`requestTimeout`
|`number | string | null` - Max request timeout for the request in milliseconds. This overrides the client default, which is to not time out at all. See https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-network.html#_http_client_configuration[Elasticsearch best practices for HTML clients] for more info. +
_Default:_ No timeout
|`retryOnTimeout`
|`boolean` - Retry requests that have timed out.
_Default:_ `false`
|`maxRetries`
|`number` - Max number of retries for the request, it overrides the client default. +
_Default:_ `3`
|`compression`
|`string | boolean` - Enables body compression for the request. +
_Options:_ `false`, `'gzip'` +
_Default:_ `false`
|`asStream`
|`boolean` - Instead of getting the parsed body back, you get the raw Node.js stream of data. +
_Default:_ `false`
|`headers`
|`object` - Custom headers for the request. +
_Default:_ `null`
|`querystring`
|`object` - Custom querystring for the request. +
_Default:_ `null`
|`id`
|`any` - Custom request id. _(overrides the top level request id generator)_ +
_Default:_ `null`
|`context`
|`any` - Custom object per request. _(you can use it to pass data to the clients events)_ +
_Default:_ `null`
|`opaqueId`
|`string` - Set the `X-Opaque-Id` HTTP header. See {ref}/api-conventions.html#x-opaque-id
_Default:_ `null`
|`maxResponseSize`
|`number` - When configured, it verifies that the uncompressed response size is lower than the configured number, if it's higher it will abort the request. It cannot be higher than buffer.constants.MAX_STRING_LENTGH +
_Default:_ `null`
|`maxCompressedResponseSize`
|`number` - When configured, it verifies that the compressed response size is lower than the configured number, if it's higher it will abort the request. It cannot be higher than buffer.constants.MAX_LENTGH +
_Default:_ `null`
|`signal`
|`AbortSignal` - The AbortSignal instance to allow request abortion. +
_Default:_ `null`
|`meta`
|`boolean` - Rather than returning the body, return an object containing `body`, `statusCode`, `headers` and `meta` keys +
_Default_: `false`
|`redaction`
|`object` - Options for redacting potentially sensitive data from error metadata. See <<redaction>>.
|`retryBackoff`
|`(min: number, max: number, attempt: number) => number;` - A function that calculates how long to sleep, in seconds, before the next request retry +
_Default:_ A built-in function that uses exponential backoff with jitter.
|===
[discrete]
[[client-faas-env]]
=== Using the Client in a Function-as-a-Service Environment
This section illustrates the 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, the global scope.
This practice does not only improve performance but also enables background functionality as for example https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how[sniffing].
The following examples provide a skeleton for the best practices.
[discrete]
==== GCP Cloud Functions
[source,js]
----
'use strict'
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
// client initialisation
})
exports.testFunction = async function (req, res) {
// use the client
}
----
[discrete]
==== AWS Lambda
[source,js]
----
'use strict'
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
// client initialisation
})
exports.handler = async function (event, context) {
// use the client
}
----
[discrete]
==== Azure Functions
[source,js]
----
'use strict'
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
// client initialisation
})
module.exports = async function (context, req) {
// use the client
}
----
Resources used to assess these recommendations:
- https://cloud.google.com/functions/docs/bestpractices/tips#use_global_variables_to_reuse_objects_in_future_invocations[GCP Cloud Functions: Tips & Tricks]
- https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html[Best practices for working with AWS Lambda functions]
- https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=azurecli-linux%2Capplication-level#global-variables[Azure Functions Python developer guide]
- https://docs.aws.amazon.com/lambda/latest/operatorguide/global-scope.html[AWS Lambda: Comparing the effect of global scope]
[discrete]
[[client-connect-proxy]]
=== Connecting through a proxy
~Added~ ~in~ ~`v7.10.0`~
If you need to pass through an http(s) proxy for connecting to {es}, the client
out of the box offers a handy configuration for helping you with it. Under the
hood, it uses the https://github.com/delvedor/hpagent[`hpagent`] module.
IMPORTANT: In versions 8.0+ of the client, the default `Connection` type is set to `UndiciConnection`, which does not support proxy configurations.
To use a proxy, you will need to use the `HttpConnection` class from `@elastic/transport` instead.
[source,js]
----
import { HttpConnection } from '@elastic/transport'
const client = new Client({
node: 'http://localhost:9200',
proxy: 'http://localhost:8080',
Connection: HttpConnection,
})
----
Basic authentication is supported as well:
[source,js]
----
const client = new Client({
node: 'http://localhost:9200',
proxy: 'http:user:pwd@//localhost:8080',
Connection: HttpConnection,
})
----
If you are connecting through a non-http(s) proxy, such as a `socks5` or `pac`,
you can use the `agent` option to configure it.
[source,js]
----
const SocksProxyAgent = require('socks-proxy-agent')
const client = new Client({
node: 'http://localhost:9200',
agent () {
return new SocksProxyAgent('socks://127.0.0.1:1080')
},
Connection: HttpConnection,
})
----
[discrete]
[[client-error-handling]]
=== Error handling
The client exposes a variety of error objects that you can use to enhance your
error handling. You can find all the error objects inside the `errors` key in
the client.
[source,js]
----
const { errors } = require('@elastic/elasticsearch')
console.log(errors)
----
You can find the errors exported by the client in the table below.
[cols=3*]
|===
|*Error*
|*Description*
|*Properties*
|`ElasticsearchClientError`
|Every error inherits from this class, it is the basic error generated by the client.
a|* `name` - `string`
* `message` - `string`
|`TimeoutError`
|Generated when a request exceeds the `requestTimeout` option.
a|* `name` - `string`
* `message` - `string`
* `meta` - `object`, contains all the information about the request
|`ConnectionError`
|Generated when an error occurs during the request, it can be a connection error or a malformed stream of data.
a|* `name` - `string`
* `message` - `string`
* `meta` - `object`, contains all the information about the request
|`RequestAbortedError`
|Generated if the user calls the `request.abort()` method.
a|* `name` - `string`
* `message` - `string`
* `meta` - `object`, contains all the information about the request
|`NoLivingConnectionsError`
|Given the configuration, the ConnectionPool was not able to find a usable Connection for this request.
a|* `name` - `string`
* `message` - `string`
* `meta` - `object`, contains all the information about the request
|`SerializationError`
|Generated if the serialization fails.
a|* `name` - `string`
* `message` - `string`
* `data` - `object`, the object to serialize
|`DeserializationError`
|Generated if the deserialization fails.
a|* `name` - `string`
* `message` - `string`
* `data` - `string`, the string to deserialize
|`ConfigurationError`
|Generated if there is a malformed configuration or parameter.
a|* `name` - `string`
* `message` - `string`
|`ResponseError`
|Generated when in case of a `4xx` or `5xx` response.
a|* `name` - `string`
* `message` - `string`
* `meta` - `object`, contains all the information about the request
* `body` - `object`, the response body
* `statusCode` - `object`, the response headers
* `headers` - `object`, the response status code
|===
[[keep-alive]]
[discrete]
=== Keep-alive connections
By default, the client uses persistent, keep-alive connections to reduce the overhead of creating a new HTTP connection for each Elasticsearch request.
If you are using the default `UndiciConnection` connection class, it maintains a pool of 256 connections with a keep-alive of 10 minutes.
If you are using the legacy `HttpConnection` connection class, it maintains a pool of 256 connections with a keep-alive of 1 minute.
If you need to disable keep-alive connections, you can override the HTTP agent with your preferred https://nodejs.org/api/http.html#http_new_agent_options[HTTP agent options]:
[source,js]
----
const client = new Client({
node: 'http://localhost:9200',
// the function takes as parameter the option
// object passed to the Connection constructor
agent: (opts) => new CustomAgent()
})
----
Or you can disable the HTTP agent entirely:
[source,js]
----
const client = new Client({
node: 'http://localhost:9200',
// Disable agent and keep-alive
agent: false
})
----
[discrete]
[[close-connections]]
=== Closing a client's connections
If you would like to close all open connections being managed by an instance of the client, use the `close()` function:
[source,js]
----
const client = new Client({
node: 'http://localhost:9200'
});
client.close();
----
[discrete]
[[product-check]]
=== Automatic product check
Since v7.14.0, the client performs a required product check before the first call.
This pre-flight product check allows the client to establish the version of Elasticsearch
that it is communicating with. The product check requires one additional HTTP request to
be sent to the server as part of the request pipeline before the main API call is sent.
In most cases, this will succeed during the very first API call that the client sends.
Once the product check completes, no further product check HTTP requests are sent for
subsequent API calls.

12
docs/docset.yml Normal file
View File

@ -0,0 +1,12 @@
project: 'Node.js client'
exclude:
- examples/proxy/README.md
cross_links:
- docs-content
- elasticsearch
toc:
- toc: reference
- toc: release-notes
subs:
stack: "Elastic Stack"
es: "Elasticsearch"

View File

@ -1,34 +0,0 @@
[[examples]]
== Examples
Following you can find some examples on how to use the client.
* Use of the <<as_stream_examples,asStream>> parameter;
* Executing a <<bulk_examples,bulk>> request;
* Executing a <<exists_examples,exists>> request;
* Executing a <<get_examples,get>> request;
* Executing a <<sql_query_examples,sql.query>> request;
* Executing a <<update_examples,update>> request;
* Executing a <<update_by_query_examples,update by query>> request;
* Executing a <<reindex_examples,reindex>> request;
* Use of the <<ignore_examples,ignore>> parameter;
* Executing a <<msearch_examples,msearch>> request;
* How do I <<scroll_examples,scroll>>?
* Executing a <<search_examples,search>> request;
* I need <<suggest_examples,suggestions>>;
* How to use the <<transport_request_examples,transport.request>> method;
include::asStream.asciidoc[]
include::bulk.asciidoc[]
include::exists.asciidoc[]
include::get.asciidoc[]
include::ignore.asciidoc[]
include::msearch.asciidoc[]
include::scroll.asciidoc[]
include::search.asciidoc[]
include::suggest.asciidoc[]
include::transport.request.asciidoc[]
include::sql.query.asciidoc[]
include::update.asciidoc[]
include::update_by_query.asciidoc[]
include::reindex.asciidoc[]

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
// IMPORTANT: this is not a production ready code & purely for demonstration purposes,

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
// IMPORTANT: this is not a production ready code & purely for demonstration purposes,

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
// IMPORTANT: this is not a production ready code & purely for demonstration purposes,

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
// IMPORTANT: this is not a production ready code & purely for demonstration purposes,

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
// IMPORTANT: this is not a production ready code & purely for demonstration purposes,

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
'use strict'

View File

@ -1,170 +0,0 @@
[[getting-started-js]]
== Getting started
This page guides you through the installation process of the Node.js client,
shows you how to instantiate the client, and how to perform basic Elasticsearch
operations with it.
[discrete]
=== Requirements
* https://nodejs.org/[Node.js] version 14.x or newer
* https://docs.npmjs.com/downloading-and-installing-node-js-and-npm[`npm`], usually bundled with Node.js
[discrete]
=== Installation
To install the latest version of the client, run the following command:
[source,shell]
--------------------------
npm install @elastic/elasticsearch
--------------------------
Refer to the <<installation>> page to learn more.
[discrete]
=== Connecting
You can connect to the Elastic Cloud using an API key and the Elasticsearch
endpoint.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://...', // Elasticsearch endpoint
auth: {
apiKey: { // API key ID and secret
id: 'foo',
api_key: 'bar',
}
}
})
----
Your Elasticsearch endpoint can be found on the **My deployment** page of your
deployment:
image::images/es-endpoint.jpg[alt="Finding Elasticsearch endpoint",align="center"]
You can generate an API key on the **Management** page under Security.
image::images/create-api-key.png[alt="Create API key",align="center"]
For other connection options, refer to the <<client-connecting>> section.
[discrete]
=== Operations
Time to use Elasticsearch! This section walks you through the basic, and most
important, operations of Elasticsearch.
[discrete]
==== Creating an index
This is how you create the `my_index` index:
[source,js]
----
await client.indices.create({ index: 'my_index' })
----
[discrete]
==== Indexing documents
This is a simple way of indexing a document:
[source,js]
----
await client.index({
index: 'my_index',
id: 'my_document_id',
document: {
foo: 'foo',
bar: 'bar',
},
})
----
[discrete]
==== Getting documents
You can get documents by using the following code:
[source,js]
----
await client.get({
index: 'my_index',
id: 'my_document_id',
})
----
[discrete]
==== Searching documents
This is how you can create a single match query with the client:
[source,js]
----
await client.search({
query: {
match: {
foo: 'foo'
}
}
})
----
[discrete]
==== Updating documents
This is how you can update a document, for example to add a new field:
[source,js]
----
await client.update({
index: 'my_index',
id: 'my_document_id',
doc: {
foo: 'bar',
new_field: 'new value'
}
})
----
[discrete]
==== Deleting documents
[source,js]
----
await client.delete({
index: 'my_index',
id: 'my_document_id',
})
----
[discrete]
==== Deleting an index
[source,js]
----
await client.indices.delete({ index: 'my_index' })
----
[discrete]
== Further reading
* Use <<client-helpers>> for a more comfortable experience with the APIs.
* For an elaborate example of how to ingest data into Elastic Cloud,
refer to {cloud}/ec-getting-started-node-js.html[this page].

View File

@ -1,748 +0,0 @@
[[client-helpers]]
== Client helpers
The client comes with an handy collection of helpers to give you a more
comfortable experience with some APIs.
CAUTION: The client helpers are experimental, and the API may change in the next
minor releases. The helpers will not work in any Node.js version lower than 10.
[discrete]
[[bulk-helper]]
=== Bulk helper
~Added~ ~in~ ~`v7.7.0`~
Running bulk requests can be complex due to the shape of the API, this helper
aims to provide a nicer developer experience around the Bulk API.
[discrete]
==== Usage
[source,js]
----
const { createReadStream } = require('fs')
const split = require('split2')
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<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)
// {
// total: number,
// failed: number,
// retry: number,
// successful: number,
// time: number,
// bytes: number,
// aborted: boolean
// }
----
To create a new instance of the Bulk helper, access it as shown in the example
above, the configuration options are:
[cols=2*]
|===
|`datasource`
a|An array, async generator or a readable stream with the data you need to index/create/update/delete.
It can be an array of strings or objects, but also a stream of json strings or JavaScript objects. +
If it is a stream, we recommend to use the https://www.npmjs.com/package/split2[`split2`] package, that splits the stream on new lines delimiters. +
This parameter is mandatory.
[source,js]
----
const { createReadStream } = require('fs')
const split = require('split2')
const b = client.helpers.bulk({
// if you just use split(), the data will be used as array of strings
datasource: createReadStream('./dataset.ndjson').pipe(split())
// if you need to manipulate the data, you can pass JSON.parse to split
datasource: createReadStream('./dataset.ndjson').pipe(split(JSON.parse))
})
----
|`onDocument`
a|A function that is called for each document of the datasource. Inside this function you can manipulate the document and you must return the operation you want to execute with the document. Look at the link:{ref}/docs-bulk.html[Bulk API documentation] to see the supported operations. +
This parameter is mandatory.
[source,js]
----
const b = client.helpers.bulk({
onDocument (doc) {
return {
index: { _index: 'my-index' }
}
}
})
----
|`onDrop`
a|A function that is called for everytime a document can't be indexed and it has reached the maximum amount of retries.
[source,js]
----
const b = client.helpers.bulk({
onDrop (doc) {
console.log(doc)
}
})
----
|`onSuccess`
a|A function that is called for each successful operation in the bulk request, which includes the result from Elasticsearch along with the original document that was sent, or `null` for delete operations.
[source,js]
----
const b = client.helpers.bulk({
onSuccess ({ result, document }) {
console.log(`SUCCESS: Document ${result.index._id} indexed to ${result.index._index}`)
}
})
----
|`flushBytes`
a|The size of the bulk body in bytes to reach before to send it. Default of 5MB. +
_Default:_ `5000000`
[source,js]
----
const b = client.helpers.bulk({
flushBytes: 1000000
})
----
|`flushInterval`
a|How much time (in milliseconds) the helper waits before flushing the body from the last document read. +
_Default:_ `30000`
[source,js]
----
const b = client.helpers.bulk({
flushInterval: 30000
})
----
|`concurrency`
a|How many request is executed at the same time. +
_Default:_ `5`
[source,js]
----
const b = client.helpers.bulk({
concurrency: 10
})
----
|`retries`
a|How many times a document is retried before to call the `onDrop` callback. +
_Default:_ Client max retries.
[source,js]
----
const b = client.helpers.bulk({
retries: 3
})
----
|`wait`
a|How much time to wait before retries in milliseconds. +
_Default:_ 5000.
[source,js]
----
const b = client.helpers.bulk({
wait: 3000
})
----
|`refreshOnCompletion`
a|If `true`, at the end of the bulk operation it runs a refresh on all indices or on the specified indices. +
_Default:_ false.
[source,js]
----
const b = client.helpers.bulk({
refreshOnCompletion: true
// or
refreshOnCompletion: 'index-name'
})
----
|===
[discrete]
==== Supported operations
[discrete]
===== Index
[source,js]
----
client.helpers.bulk({
datasource: myDatasource,
onDocument (doc) {
return {
index: { _index: 'my-index' }
}
}
})
----
[discrete]
===== Create
[source,js]
----
client.helpers.bulk({
datasource: myDatasource,
onDocument (doc) {
return {
create: { _index: 'my-index', _id: doc.id }
}
}
})
----
[discrete]
===== Update
[source,js]
----
client.helpers.bulk({
datasource: myDatasource,
onDocument (doc) {
// Note that the update operation requires you to return
// an array, where the first element is the action, while
// the second are the document option
return [
{ update: { _index: 'my-index', _id: doc.id } },
{ doc_as_upsert: true }
]
}
})
----
[discrete]
===== Delete
[source,js]
----
client.helpers.bulk({
datasource: myDatasource,
onDocument (doc) {
return {
delete: { _index: 'my-index', _id: doc.id }
}
}
})
----
[discrete]
==== Abort a bulk operation
If needed, you can abort a bulk operation at any time. The bulk helper returns a
https://promisesaplus.com/[thenable], which has an `abort` method.
NOTE: The abort method stops the execution of the bulk operation, but if you
are using a concurrency higher than one, the operations that are already running
will not be stopped.
[source,js]
----
const { createReadStream } = require('fs')
const split = require('split2')
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const b = client.helpers.bulk({
datasource: createReadStream('./dataset.ndjson').pipe(split()),
onDocument (doc) {
return {
index: { _index: 'my-index' }
}
},
onDrop (doc) {
b.abort()
}
})
console.log(await b)
----
[discrete]
==== Passing custom options to the Bulk API
You can pass any option supported by the link:
{ref}/docs-bulk.html#docs-bulk-api-query-params[Bulk API] to the helper, and the
helper uses those options in conjunction with the Bulk API call.
[source,js]
----
const result = await client.helpers.bulk({
datasource: [...],
onDocument (doc) {
return {
index: { _index: 'my-index' }
}
},
pipeline: 'my-pipeline'
})
----
[discrete]
==== Usage with an async generator
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
async function * generator () {
const dataset = [
{ user: 'jon', age: 23 },
{ user: 'arya', age: 18 },
{ user: 'tyrion', age: 39 }
]
for (const doc of dataset) {
yield doc
}
}
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const result = await client.helpers.bulk({
datasource: generator(),
onDocument (doc) {
return {
index: { _index: 'my-index' }
}
}
})
console.log(result)
----
[discrete]
==== Modifying a document before operation
~Added~ ~in~ ~`v8.8.2`~
If you need to modify documents in your datasource before it is sent to Elasticsearch, you can return an array in the `onDocument` function rather than an operation object. The first item in the array must be the operation object, and the second item must be the document or partial document object as you'd like it to be sent to Elasticsearch.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const result = await client.helpers.bulk({
datasource: [...],
onDocument (doc) {
return [
{ index: { _index: 'my-index' } },
{ ...doc, favorite_color: 'mauve' },
]
}
})
console.log(result)
----
[discrete]
[[multi-search-helper]]
=== Multi search helper
~Added~ ~in~ ~`v7.8.0`~
If you send search request at a high rate, this helper might be useful
for you. It uses the multi search API under the hood to batch the requests
and improve the overall performances of your application. The `result` exposes a
`documents` property as well, which allows you to access directly the hits
sources.
[discrete]
==== Usage
[source,js]
----
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)) // or result.documents
.catch(err => console.error(err))
----
To create a new instance of the multi search (msearch) helper, you should access
it as shown in the example above, the configuration options are:
[cols=2*]
|===
|`operations`
a|How many search operations should be sent in a single msearch request. +
_Default:_ `5`
[source,js]
----
const m = client.helpers.msearch({
operations: 10
})
----
|`flushInterval`
a|How much time (in milliseconds) the helper waits before flushing the operations from the last operation read. +
_Default:_ `500`
[source,js]
----
const m = client.helpers.msearch({
flushInterval: 500
})
----
|`concurrency`
a|How many request is executed at the same time. +
_Default:_ `5`
[source,js]
----
const m = client.helpers.msearch({
concurrency: 10
})
----
|`retries`
a|How many times an operation is retried before to resolve the request. An operation is retried only in case of a 429 error. +
_Default:_ Client max retries.
[source,js]
----
const m = client.helpers.msearch({
retries: 3
})
----
|`wait`
a|How much time to wait before retries in milliseconds. +
_Default:_ 5000.
[source,js]
----
const m = client.helpers.msearch({
wait: 3000
})
----
|===
[discrete]
==== Stopping the msearch helper
If needed, you can stop an msearch processor at any time. The msearch helper
returns a https://promisesaplus.com/[thenable], which has an `stop` method.
If you are creating multiple msearch helpers instances and using them for a
limitied period of time, remember to always use the `stop` method once you have
finished using them, otherwise your application will start leaking memory.
The `stop` method accepts an optional error, that will be dispatched every
subsequent search request.
NOTE: The stop method stops the execution of the msearch processor, but if
you are using a concurrency higher than one, the operations that are already
running will not be stopped.
[source,js]
----
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())
----
[discrete]
[[search-helper]]
=== Search helper
~Added~ ~in~ ~`v7.7.0`~
A simple wrapper around the search API. Instead of returning the entire `result`
object it returns only the search documents source. For improving the
performances, this helper automatically adds `filter_path=hits.hits._source` to
the query string.
[source,js]
----
const documents = await client.helpers.search({
index: 'stackoverflow',
query: {
match: {
title: 'javascript'
}
}
})
for (const doc of documents) {
console.log(doc)
}
----
[discrete]
[[scroll-search-helper]]
=== Scroll search helper
~Added~ ~in~ ~`v7.7.0`~
This helpers offers a simple and intuitive way to use the scroll search API.
Once called, it returns an
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function[async iterator]
which can be used in conjuction with a for-await...of. It handles automatically
the `429` error and uses the `maxRetries` option of the client.
[source,js]
----
const scrollSearch = client.helpers.scrollSearch({
index: 'stackoverflow',
query: {
match: {
title: 'javascript'
}
}
})
for await (const result of scrollSearch) {
console.log(result)
}
----
[discrete]
==== Clear a scroll search
If needed, you can clear a scroll search by calling `result.clear()`:
[source,js]
----
for await (const result of scrollSearch) {
if (condition) {
await result.clear()
}
}
----
[discrete]
==== Quickly getting the documents
If you only need the documents from the result of a scroll search, you can
access them via `result.documents`:
[source,js]
----
for await (const result of scrollSearch) {
console.log(result.documents)
}
----
[discrete]
[[scroll-documents-helper]]
=== Scroll documents helper
~Added~ ~in~ ~`v7.7.0`~
It works in the same way as the scroll search helper, but it returns only the
documents instead. Note, every loop cycle returns a single document, and you
can't use the `clear` method. For improving the performances, this helper
automatically adds `filter_path=hits.hits._source` to the query string.
[source,js]
----
const scrollSearch = client.helpers.scrollDocuments({
index: 'stackoverflow',
query: {
match: {
title: 'javascript'
}
}
})
for await (const doc of scrollSearch) {
console.log(doc)
}
----
[discrete]
[[esql-helper]]
=== ES|QL helper
ES|QL queries can return their results in {ref}/esql-rest.html#esql-rest-format[several formats].
The default JSON format returned by ES|QL queries contains arrays of values
for each row, with column names and types returned separately:
[discrete]
==== Usage
[discrete]
===== `toRecords`
~Added~ ~in~ ~`v8.14.0`~
The default JSON format returned by ES|QL queries contains arrays of values
for each row, with column names and types returned separately:
[source,json]
----
{
"columns": [
{ "name": "@timestamp", "type": "date" },
{ "name": "client_ip", "type": "ip" },
{ "name": "event_duration", "type": "long" },
{ "name": "message", "type": "keyword" }
],
"values": [
[
"2023-10-23T12:15:03.360Z",
"172.21.2.162",
3450233,
"Connected to 10.1.0.3"
],
[
"2023-10-23T12:27:28.948Z",
"172.21.2.113",
2764889,
"Connected to 10.1.0.2"
]
]
}
----
In many cases, it's preferable to operate on an array of objects, one object per row,
rather than an array of arrays. The ES|QL `toRecords` helper converts row data into objects.
[source,js]
----
await client.helpers
.esql({ query: 'FROM sample_data | LIMIT 2' })
.toRecords()
// =>
// {
// "columns": [
// { "name": "@timestamp", "type": "date" },
// { "name": "client_ip", "type": "ip" },
// { "name": "event_duration", "type": "long" },
// { "name": "message", "type": "keyword" }
// ],
// "records": [
// {
// "@timestamp": "2023-10-23T12:15:03.360Z",
// "client_ip": "172.21.2.162",
// "event_duration": 3450233,
// "message": "Connected to 10.1.0.3"
// },
// {
// "@timestamp": "2023-10-23T12:27:28.948Z",
// "client_ip": "172.21.2.113",
// "event_duration": 2764889,
// "message": "Connected to 10.1.0.2"
// },
// ]
// }
----
In TypeScript, you can declare the type that `toRecords` returns:
[source,ts]
----
type EventLog = {
'@timestamp': string,
client_ip: string,
event_duration: number,
message: string,
}
const result = await client.helpers
.esql({ query: 'FROM sample_data | LIMIT 2' })
.toRecords<EventLog>()
----
[discrete]
===== `toArrowReader`
~Added~ ~in~ ~`v8.16.0`~
ES|QL can return results in multiple binary formats, including https://arrow.apache.org/[Apache Arrow]'s streaming format. Because it is a very efficient format to read, it can be valuable for performing high-performance in-memory analytics. And, because the response is streamed as batches of records, it can be used to produce aggregations and other calculations on larger-than-memory data sets.
`toArrowReader` returns a https://arrow.apache.org/docs/js/classes/Arrow_dom.RecordBatchReader.html[`RecordBatchStreamReader`].
[source,ts]
----
const reader = await client.helpers
.esql({ query: 'FROM sample_data' })
.toArrowReader()
// print each record as JSON
for (const recordBatch of reader) {
for (const record of recordBatch) {
console.log(record.toJSON())
}
}
----
[discrete]
===== `toArrowTable`
~Added~ ~in~ ~`v8.16.0`~
If you would like to pull the entire data set in Arrow format but without streaming, you can use the `toArrowTable` helper to get a https://arrow.apache.org/docs/js/classes/Arrow_dom.Table.html[Table] back instead.
[source,ts]
----
const table = await client.helpers
.esql({ query: 'FROM sample_data' })
.toArrowTable()
console.log(table.toArray())
----

View File

@ -1,24 +0,0 @@
= Elasticsearch JavaScript Client
include::{asciidoc-dir}/../../shared/versions/stack/{source_branch}.asciidoc[]
include::{asciidoc-dir}/../../shared/attributes.asciidoc[]
include::introduction.asciidoc[]
include::getting-started.asciidoc[]
include::changelog.asciidoc[]
include::installation.asciidoc[]
include::connecting.asciidoc[]
include::configuration.asciidoc[]
include::basic-config.asciidoc[]
include::advanced-config.asciidoc[]
include::child.asciidoc[]
include::testing.asciidoc[]
include::integrations.asciidoc[]
include::observability.asciidoc[]
include::transport.asciidoc[]
include::typescript.asciidoc[]
include::reference.asciidoc[]
include::examples/index.asciidoc[]
include::helpers.asciidoc[]
include::redirects.asciidoc[]
include::timeout-best-practices.asciidoc[]

View File

@ -1,116 +0,0 @@
[[installation]]
== Installation
This page guides you through the installation process of the client.
To install the latest version of the client, run the following command:
[source,sh]
----
npm install @elastic/elasticsearch
----
To install a specific major version of the client, run the following command:
[source,sh]
----
npm install @elastic/elasticsearch@<major>
----
To learn more about the supported major versions, please refer to the
<<js-compatibility-matrix>>.
[discrete]
[[nodejs-support]]
=== Node.js support
NOTE: The minimum supported version of Node.js is `v18`.
The client versioning follows the {stack} versioning, this means that
major, minor, and patch releases are done following a precise schedule that
often does not coincide with the https://nodejs.org/en/about/releases/[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`).
[%header,cols=3*]
|===
|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)
|===
[discrete]
[[js-compatibility-matrix]]
=== Compatibility matrix
Language clients are forward compatible; meaning that clients support
communicating with greater or equal minor versions of {es} without breaking. It
does not mean that the client automatically supports new features of newer {es}
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 {es}, the 8.13 client version is required for that.
{es} language clients are only backwards compatible with default distributions
and without guarantees made.
[%header,cols=3*]
|===
|{es} Version
|Client Version
|Supported
|`8.x`
|`8.x`
|`8.x`
|`7.x`
|`7.x`
|`7.17`
|`6.x`
|`6.x`
|
|`5.x`
|`5.x`
|
|===
[discrete]
==== Browser
WARNING: There is no official support for the browser environment. It exposes
your {es} instance to everyone, which could lead to security issues. We
recommend you to write a lightweight proxy that uses this client instead,
you can see a proxy example https://github.com/elastic/elasticsearch-js/tree/master/docs/examples/proxy[here].

View File

@ -1,8 +0,0 @@
[[integrations]]
== Integrations
The Client offers the following integration options for you:
* <<observability>>
* <<transport>>
* <<typescript>>

View File

@ -1,17 +0,0 @@
["appendix",role="exclude",id="redirects"]
= Deleted pages
The following pages have moved or been deleted.
[role="exclude",id="auth-reference"]
== Authentication
This page has moved. See <<client-connecting>>.
[role="exclude",id="breaking-changes"]
== Breaking changes
For information about migrating from the legacy elasticsearch.js client to the
new Elasticsearch JavaScript client, refer to the
https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/7.17/breaking-changes.html[7.17
JavaScript client migration guide].

View File

@ -221,7 +221,7 @@ client.count({ ... })
* *Request (object):*
** *`index` (Optional, string | string[])*: A list of data streams, indices, and aliases to search. It supports wildcards (`*`). To search all data streams and indices, omit this parameter or use `*` or `_all`.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Defines the search query using Query DSL. A request body query cannot be used with the `q` query string parameter.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Defines the search query using Query DSL. A request body query cannot be used with the `q` query string parameter.
** *`allow_no_indices` (Optional, boolean)*: If `false`, the request returns an error if any wildcard expression, index alias, or `_all` value targets only missing or closed indices. This behavior applies even if the request targets other open indices. For example, a request targeting `foo*,bar*` returns an error if an index starts with `foo` but no index starts with `bar`.
** *`analyzer` (Optional, string)*: The analyzer to use for the query string. This parameter can be used only when the `q` query string parameter is specified.
** *`analyze_wildcard` (Optional, boolean)*: If `true`, wildcard and prefix queries are analyzed. This parameter can be used only when the `q` query string parameter is specified.
@ -324,9 +324,14 @@ client.create({ id, index })
** *`id` (string)*: A unique identifier for the document. To automatically generate a document ID, use the `POST /<target>/_doc/` request format.
** *`index` (string)*: The name of the data stream or index to target. If the target doesn't exist and matches the name or wildcard (`*`) pattern of an index template with a `data_stream` definition, this request creates the data stream. If the target doesn't exist and doesnt match a data stream template, this request creates the index.
** *`document` (Optional, object)*: A document.
** *`if_primary_term` (Optional, number)*: Only perform the operation if the document has this primary term.
** *`if_seq_no` (Optional, number)*: Only perform the operation if the document has this sequence number.
** *`include_source_on_error` (Optional, boolean)*: True or false if to include the document source in the error message in case of parsing errors.
** *`op_type` (Optional, Enum("index" | "create"))*: Set to `create` to only index the document if it does not already exist (put if absent). If a document with the specified `_id` already exists, the indexing operation will fail. The behavior is the same as using the `<index>/_create` endpoint. If a document ID is specified, this paramater defaults to `index`. Otherwise, it defaults to `create`. If the request targets a data stream, an `op_type` of `create` is required.
** *`pipeline` (Optional, string)*: The ID of the pipeline to use to preprocess incoming documents. If the index has a default ingest pipeline specified, setting the value to `_none` turns off the default ingest pipeline for this request. If a final pipeline is configured, it will always run regardless of the value of this parameter.
** *`refresh` (Optional, Enum(true | false | "wait_for"))*: If `true`, Elasticsearch refreshes the affected shards to make this operation visible to search. If `wait_for`, it waits for a refresh to make this operation visible to search. If `false`, it does nothing with refreshes.
** *`require_alias` (Optional, boolean)*: If `true`, the destination must be an index alias.
** *`require_data_stream` (Optional, boolean)*: If `true`, the request's actions must target a data stream (existing or to be created).
** *`routing` (Optional, string)*: A custom value that is used to route operations to a specific shard.
** *`timeout` (Optional, string | -1 | 0)*: The period the request waits for the following operations: automatic index creation, dynamic mapping updates, waiting for active shards. Elasticsearch waits for at least the specified timeout period before failing. The actual wait time could be longer, particularly when multiple waits occur. This parameter is useful for situations where the primary shard assigned to perform the operation might not be available when the operation runs. Some reasons for this might be that the primary shard is currently recovering from a gateway or undergoing relocation. By default, the operation will wait on the primary shard to become available for at least 1 minute before failing and responding with an error. The actual wait time could be longer, particularly when multiple waits occur.
** *`version` (Optional, number)*: The explicit version number for concurrency control. It must be a non-negative long number.
@ -489,7 +494,7 @@ client.deleteByQuery({ index })
* *Request (object):*
** *`index` (string | string[])*: A list of data streams, indices, and aliases to search. It supports wildcards (`*`). To search all data streams or indices, omit this parameter or use `*` or `_all`.
** *`max_docs` (Optional, number)*: The maximum number of documents to delete.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The documents to delete specified with Query DSL.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The documents to delete specified with Query DSL.
** *`slice` (Optional, { field, id, max })*: Slice the request manually using the provided slice ID and total number of slices.
** *`allow_no_indices` (Optional, boolean)*: If `false`, the request returns an error if any wildcard expression, index alias, or `_all` value targets only missing or closed indices. This behavior applies even if the request targets other open indices. For example, a request targeting `foo*,bar*` returns an error if an index starts with `foo` but no index starts with `bar`.
** *`analyzer` (Optional, string)*: Analyzer to use for the query string. This parameter can be used only when the `q` query string parameter is specified.
@ -652,7 +657,7 @@ client.explain({ id, index })
* *Request (object):*
** *`id` (string)*: The document identifier.
** *`index` (string)*: Index names that are used to limit the request. Only a single index name can be provided to this parameter.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Defines the search definition using the Query DSL.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Defines the search definition using the Query DSL.
** *`analyzer` (Optional, string)*: The analyzer to use for the query string. This parameter can be used only when the `q` query string parameter is specified.
** *`analyze_wildcard` (Optional, boolean)*: If `true`, wildcard and prefix queries are analyzed. This parameter can be used only when the `q` query string parameter is specified.
** *`default_operator` (Optional, Enum("and" | "or"))*: The default operator for query string query: `AND` or `OR`. This parameter can be used only when the `q` query string parameter is specified.
@ -687,7 +692,7 @@ client.fieldCaps({ ... })
* *Request (object):*
** *`index` (Optional, string | string[])*: A list of data streams, indices, and aliases used to limit the request. Supports wildcards (*). To target all data streams and indices, omit this parameter or use * or _all.
** *`fields` (Optional, string | string[])*: A list of fields to retrieve capabilities for. Wildcard (`*`) expressions are supported.
** *`index_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Filter indices if the provided query rewrites to `match_none` on every shard. IMPORTANT: The filtering is done on a best-effort basis, it uses index statistics and mappings to rewrite queries to `match_none` instead of fully running the request. For instance a range query over a date field can rewrite to `match_none` if all documents within a shard (including deleted documents) are outside of the provided range. However, not all queries can rewrite to `match_none` so this API may return an index even if the provided filter matches no document.
** *`index_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Filter indices if the provided query rewrites to `match_none` on every shard. IMPORTANT: The filtering is done on a best-effort basis, it uses index statistics and mappings to rewrite queries to `match_none` instead of fully running the request. For instance a range query over a date field can rewrite to `match_none` if all documents within a shard (including deleted documents) are outside of the provided range. However, not all queries can rewrite to `match_none` so this API may return an index even if the provided filter matches no document.
** *`runtime_mappings` (Optional, Record<string, { fields, fetch_fields, format, input_field, target_field, target_index, script, type }>)*: Define ad-hoc runtime fields in the request similar to the way it is done in search requests. These fields exist only as part of the query and take precedence over fields defined with the same name in the index mappings.
** *`allow_no_indices` (Optional, boolean)*: If false, the request returns an error if any wildcard expression, index alias, or `_all` value targets only missing or closed indices. This behavior applies even if the request targets other open indices. For example, a request targeting `foo*,bar*` returns an error if an index starts with foo but no index starts with bar.
** *`expand_wildcards` (Optional, Enum("all" | "open" | "closed" | "hidden" | "none") | Enum("all" | "open" | "closed" | "hidden" | "none")[])*: The type of index that wildcard patterns can match. If the request can target data streams, this argument determines whether wildcard expressions match hidden data streams. Supports a list of values, such as `open,hidden`.
@ -1092,7 +1097,7 @@ client.knnSearch({ index, knn })
** *`docvalue_fields` (Optional, { field, format, include_unmapped }[])*: The request returns doc values for field names matching these patterns in the `hits.fields` property of the response. It accepts wildcard (`*`) patterns.
** *`stored_fields` (Optional, string | string[])*: A list of stored fields to return as part of a hit. If no fields are specified, no stored fields are included in the response. If this field is specified, the `_source` parameter defaults to `false`. You can pass `_source: true` to return both source fields and stored fields in the search response.
** *`fields` (Optional, string | string[])*: The request returns values for field names matching these patterns in the `hits.fields` property of the response. It accepts wildcard (`*`) patterns.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type } | { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type }[])*: A query to filter the documents that can match. The kNN search will return the top `k` documents that also match this filter. The value can be a single query or a list of queries. If `filter` isn't provided, all documents are allowed to match.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type } | { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type }[])*: A query to filter the documents that can match. The kNN search will return the top `k` documents that also match this filter. The value can be a single query or a list of queries. If `filter` isn't provided, all documents are allowed to match.
** *`routing` (Optional, string)*: A list of specific routing values.
[discrete]
@ -1307,7 +1312,7 @@ client.openPointInTime({ index, keep_alive })
* *Request (object):*
** *`index` (string | string[])*: A list of index names to open point in time; use `_all` or empty string to perform the operation on all indices
** *`keep_alive` (string | -1 | 0)*: Extend the length of time that the point in time persists.
** *`index_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Filter indices if the provided query rewrites to `match_none` on every shard.
** *`index_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Filter indices if the provided query rewrites to `match_none` on every shard.
** *`ignore_unavailable` (Optional, boolean)*: If `false`, the request returns an error if it targets a missing or closed index.
** *`preference` (Optional, string)*: The node or shard the operation should be performed on. By default, it is random.
** *`routing` (Optional, string)*: A custom value that is used to route operations to a specific shard.
@ -1724,9 +1729,9 @@ client.search({ ... })
** *`knn` (Optional, { field, query_vector, query_vector_builder, k, num_candidates, boost, filter, similarity, inner_hits, rescore_vector } | { field, query_vector, query_vector_builder, k, num_candidates, boost, filter, similarity, inner_hits, rescore_vector }[])*: The approximate kNN search to run.
** *`rank` (Optional, { rrf })*: The Reciprocal Rank Fusion (RRF) to use.
** *`min_score` (Optional, number)*: The minimum `_score` for matching documents. Documents with a lower `_score` are not included in the search results.
** *`post_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Use the `post_filter` parameter to filter search results. The search hits are filtered after the aggregations are calculated. A post filter has no impact on the aggregation results.
** *`post_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Use the `post_filter` parameter to filter search results. The search hits are filtered after the aggregations are calculated. A post filter has no impact on the aggregation results.
** *`profile` (Optional, boolean)*: Set to `true` to return detailed timing information about the execution of individual components in a search request. NOTE: This is a debugging tool and adds significant overhead to search execution.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The search definition using the Query DSL.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The search definition using the Query DSL.
** *`rescore` (Optional, { window_size, query, learning_to_rank } | { window_size, query, learning_to_rank }[])*: Can be used to improve precision by reordering just the top (for example 100 - 500) documents returned by the `query` and `post_filter` phases.
** *`retriever` (Optional, { standard, knn, rrf, text_similarity_reranker, rule })*: A retriever is a specification to describe top documents returned from a search. A retriever replaces other elements of the search API that also return top documents such as `query` and `knn`.
** *`script_fields` (Optional, Record<string, { script, ignore_failure }>)*: Retrieve a script evaluation (based on different fields) for each hit.
@ -1937,7 +1942,7 @@ client.searchMvt({ index, field, zoom, x, y })
** *`grid_agg` (Optional, Enum("geotile" | "geohex"))*: The aggregation used to create a grid for the `field`.
** *`grid_precision` (Optional, number)*: Additional zoom levels available through the aggs layer. For example, if `<zoom>` is `7` and `grid_precision` is `8`, you can zoom in up to level 15. Accepts 0-8. If 0, results don't include the aggs layer.
** *`grid_type` (Optional, Enum("grid" | "point" | "centroid"))*: Determines the geometry type for features in the aggs layer. In the aggs layer, each feature represents a `geotile_grid` cell. If `grid, each feature is a polygon of the cells bounding box. If `point`, each feature is a Point that is the centroid of the cell.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The query DSL used to filter documents for the search.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The query DSL used to filter documents for the search.
** *`runtime_mappings` (Optional, Record<string, { fields, fetch_fields, format, input_field, target_field, target_index, script, type }>)*: Defines one or more runtime fields in the search request. These fields take precedence over mapped fields with the same name.
** *`size` (Optional, number)*: The maximum number of features to return in the hits layer. Accepts 0-10000. If 0, results don't include the hits layer.
** *`sort` (Optional, string | { _score, _doc, _geo_distance, _script } | string | { _score, _doc, _geo_distance, _script }[])*: Sort the features in the hits layer. By default, the API calculates a bounding box for each feature. It sorts features based on this box's diagonal length, from longest to shortest.
@ -2027,7 +2032,7 @@ client.termsEnum({ index, field })
** *`size` (Optional, number)*: The number of matching terms to return.
** *`timeout` (Optional, string | -1 | 0)*: The maximum length of time to spend collecting results. If the timeout is exceeded the `complete` flag set to `false` in the response and the results may be partial or empty.
** *`case_insensitive` (Optional, boolean)*: When `true`, the provided search string is matched against index terms without case sensitivity.
** *`index_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Filter an index shard if the provided query rewrites to `match_none`.
** *`index_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Filter an index shard if the provided query rewrites to `match_none`.
** *`string` (Optional, string)*: The string to match at the start of indexed terms. If it is not provided, all terms in the field are considered. > info > The prefix string cannot be larger than the largest possible keyword value, which is Lucene's term byte-length limit of 32766.
** *`search_after` (Optional, string)*: The string after which terms in the index should be returned. It allows for a form of pagination if the last result from one request is passed as the `search_after` parameter for a subsequent request.
@ -2089,17 +2094,17 @@ client.termvectors({ index })
** *`doc` (Optional, object)*: An artificial document (a document not present in the index) for which you want to retrieve term vectors.
** *`filter` (Optional, { max_doc_freq, max_num_terms, max_term_freq, max_word_length, min_doc_freq, min_term_freq, min_word_length })*: Filter terms based on their tf-idf scores. This could be useful in order find out a good characteristic vector of a document. This feature works in a similar manner to the second phase of the More Like This Query.
** *`per_field_analyzer` (Optional, Record<string, string>)*: Override the default per-field analyzer. This is useful in order to generate term vectors in any fashion, especially when using artificial documents. When providing an analyzer for a field that already stores term vectors, the term vectors will be regenerated.
** *`fields` (Optional, string | string[])*: A list or wildcard expressions of fields to include in the statistics. It is used as the default list unless a specific field list is provided in the `completion_fields` or `fielddata_fields` parameters.
** *`fields` (Optional, string | string[])*: A list of fields to include in the statistics. It is used as the default list unless a specific field list is provided in the `completion_fields` or `fielddata_fields` parameters.
** *`field_statistics` (Optional, boolean)*: If `true`, the response includes: * The document count (how many documents contain this field). * The sum of document frequencies (the sum of document frequencies for all terms in this field). * The sum of total term frequencies (the sum of total term frequencies of each term in this field).
** *`offsets` (Optional, boolean)*: If `true`, the response includes term offsets.
** *`payloads` (Optional, boolean)*: If `true`, the response includes term payloads.
** *`positions` (Optional, boolean)*: If `true`, the response includes term positions.
** *`preference` (Optional, string)*: The node or shard the operation should be performed on. It is random by default.
** *`realtime` (Optional, boolean)*: If true, the request is real-time as opposed to near-real-time.
** *`routing` (Optional, string)*: A custom value that is used to route operations to a specific shard.
** *`term_statistics` (Optional, boolean)*: If `true`, the response includes: * The total term frequency (how often a term occurs in all documents). * The document frequency (the number of documents containing the current term). By default these values are not returned since term statistics can have a serious performance impact.
** *`routing` (Optional, string)*: A custom value that is used to route operations to a specific shard.
** *`version` (Optional, number)*: If `true`, returns the document version as part of a hit.
** *`version_type` (Optional, Enum("internal" | "external" | "external_gte" | "force"))*: The version type.
** *`preference` (Optional, string)*: The node or shard the operation should be performed on. It is random by default.
** *`realtime` (Optional, boolean)*: If true, the request is real-time as opposed to near-real-time.
[discrete]
=== update
@ -2252,7 +2257,7 @@ client.updateByQuery({ index })
* *Request (object):*
** *`index` (string | string[])*: A list of data streams, indices, and aliases to search. It supports wildcards (`*`). To search all data streams or indices, omit this parameter or use `*` or `_all`.
** *`max_docs` (Optional, number)*: The maximum number of documents to update.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The documents to update using the Query DSL.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The documents to update using the Query DSL.
** *`script` (Optional, { source, id, params, lang, options })*: The script to run to update the document source or metadata when updating.
** *`slice` (Optional, { field, id, max })*: Slice the request manually using the provided slice ID and total number of slices.
** *`conflicts` (Optional, Enum("abort" | "proceed"))*: The preferred behavior when update by query hits version conflicts: `abort` or `proceed`.
@ -2419,9 +2424,9 @@ names matching these patterns in the hits.fields property of the response.
** *`knn` (Optional, { field, query_vector, query_vector_builder, k, num_candidates, boost, filter, similarity, inner_hits, rescore_vector } | { field, query_vector, query_vector_builder, k, num_candidates, boost, filter, similarity, inner_hits, rescore_vector }[])*: Defines the approximate kNN search to run.
** *`min_score` (Optional, number)*: Minimum _score for matching documents. Documents with a lower _score are
not included in the search results.
** *`post_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*
** *`post_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*
** *`profile` (Optional, boolean)*
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Defines the search definition using the Query DSL.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Defines the search definition using the Query DSL.
** *`rescore` (Optional, { window_size, query, learning_to_rank } | { window_size, query, learning_to_rank }[])*
** *`script_fields` (Optional, Record<string, { script, ignore_failure }>)*: Retrieve a script evaluation (based on different fields) for each hit.
** *`search_after` (Optional, number | number | string | boolean | null[])*
@ -5026,7 +5031,7 @@ client.eql.search({ index, query })
** *`tiebreaker_field` (Optional, string)*: Field used to sort hits with the same timestamp in ascending order
** *`timestamp_field` (Optional, string)*: Field containing event timestamp. Default "@timestamp"
** *`fetch_size` (Optional, number)*: Maximum number of events to search at a time for sequence queries.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type } | { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type }[])*: Query, written in Query DSL, used to filter the events on which the EQL query runs.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type } | { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type }[])*: Query, written in Query DSL, used to filter the events on which the EQL query runs.
** *`keep_alive` (Optional, string | -1 | 0)*
** *`keep_on_completion` (Optional, boolean)*
** *`wait_for_completion_timeout` (Optional, string | -1 | 0)*
@ -5068,7 +5073,7 @@ client.esql.asyncQuery({ query })
* *Request (object):*
** *`query` (string)*: The ES|QL query API accepts an ES|QL query string in the query parameter, runs it, and returns the results.
** *`columnar` (Optional, boolean)*: By default, ES|QL returns results as rows. For example, FROM returns each individual document as one row. For the JSON, YAML, CBOR and smile formats, ES|QL can return the results in a columnar fashion where one row represents all the values of a certain column in the results.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Specify a Query DSL query in the filter parameter to filter the set of documents that an ES|QL query runs on.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Specify a Query DSL query in the filter parameter to filter the set of documents that an ES|QL query runs on.
** *`locale` (Optional, string)*
** *`params` (Optional, number | number | string | boolean | null[])*: To avoid any attempts of hacking or code injection, extract the values in a separate list of parameters. Use question mark placeholders (?) in the query string for each of the parameters.
** *`profile` (Optional, boolean)*: If provided and `true` the response will include an extra `profile` object
@ -5080,6 +5085,10 @@ name and the next level key is the column name.
** *`include_ccs_metadata` (Optional, boolean)*: When set to `true` and performing a cross-cluster query, the response will include an extra `_clusters`
object with information about the clusters that participated in the search along with info such as shards
count.
** *`wait_for_completion_timeout` (Optional, string | -1 | 0)*: The period to wait for the request to finish.
By default, the request waits for 1 second for the query results.
If the query completes during this period, results are returned
Otherwise, a query ID is returned that can later be used to retrieve the results.
** *`delimiter` (Optional, string)*: The character to use between values within a CSV row.
It is valid only for the CSV format.
** *`drop_null_columns` (Optional, boolean)*: Indicates whether columns that are entirely `null` will be removed from the `columns` and `values` portion of the results.
@ -5091,10 +5100,6 @@ When this period expires, the query and its results are deleted, even if the que
If the `keep_on_completion` parameter is false, Elasticsearch only stores async queries that do not complete within the period set by the `wait_for_completion_timeout` parameter, regardless of this value.
** *`keep_on_completion` (Optional, boolean)*: Indicates whether the query and its results are stored in the cluster.
If false, the query and its results are stored in the cluster only if the request does not complete during the period set by the `wait_for_completion_timeout` parameter.
** *`wait_for_completion_timeout` (Optional, string | -1 | 0)*: The period to wait for the request to finish.
By default, the request waits for 1 second for the query results.
If the query completes during this period, results are returned
Otherwise, a query ID is returned that can later be used to retrieve the results.
[discrete]
==== async_query_delete
@ -5189,7 +5194,7 @@ client.esql.query({ query })
* *Request (object):*
** *`query` (string)*: The ES|QL query API accepts an ES|QL query string in the query parameter, runs it, and returns the results.
** *`columnar` (Optional, boolean)*: By default, ES|QL returns results as rows. For example, FROM returns each individual document as one row. For the JSON, YAML, CBOR and smile formats, ES|QL can return the results in a columnar fashion where one row represents all the values of a certain column in the results.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Specify a Query DSL query in the filter parameter to filter the set of documents that an ES|QL query runs on.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Specify a Query DSL query in the filter parameter to filter the set of documents that an ES|QL query runs on.
** *`locale` (Optional, string)*
** *`params` (Optional, number | number | string | boolean | null[])*: To avoid any attempts of hacking or code injection, extract the values in a separate list of parameters. Use question mark placeholders (?) in the query string for each of the parameters.
** *`profile` (Optional, boolean)*: If provided and `true` the response will include an extra `profile` object
@ -5365,9 +5370,9 @@ Defaults to 10,000 hits.
names matching these patterns in the hits.fields property of the response.
** *`min_score` (Optional, number)*: Minimum _score for matching documents. Documents with a lower _score are
not included in the search results.
** *`post_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*
** *`post_filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*
** *`profile` (Optional, boolean)*
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Defines the search definition using the Query DSL.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Defines the search definition using the Query DSL.
** *`rescore` (Optional, { window_size, query, learning_to_rank } | { window_size, query, learning_to_rank }[])*
** *`script_fields` (Optional, Record<string, { script, ignore_failure }>)*: Retrieve a script evaluation (based on different fields) for each hit.
** *`search_after` (Optional, number | number | string | boolean | null[])*
@ -5460,7 +5465,7 @@ client.graph.explore({ index })
** *`index` (string | string[])*: Name of the index.
** *`connections` (Optional, { connections, query, vertices })*: Specifies or more fields from which you want to extract terms that are associated with the specified vertices.
** *`controls` (Optional, { sample_diversity, sample_size, timeout, use_significance })*: Direct the Graph API how to build the graph.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: A seed query that identifies the documents of interest. Can be any valid Elasticsearch query.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: A seed query that identifies the documents of interest. Can be any valid Elasticsearch query.
** *`vertices` (Optional, { exclude, field, include, min_doc_count, shard_min_doc_count, size }[])*: Specifies one or more fields that contain the terms you want to include in the graph as vertices.
** *`routing` (Optional, string)*: Custom value used to route operations to a specific shard.
** *`timeout` (Optional, string | -1 | 0)*: Specifies the period of time to wait for a response from each shard.
@ -6337,6 +6342,8 @@ client.indices.existsIndexTemplate({ name })
* *Request (object):*
** *`name` (string)*: List of index template names used to limit the request. Wildcard (*) expressions are supported.
** *`local` (Optional, boolean)*: If true, the request retrieves information from the local node only. Defaults to false, which means information is retrieved from the master node.
** *`flat_settings` (Optional, boolean)*: If true, returns settings in flat format.
** *`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.
[discrete]
@ -6413,8 +6420,6 @@ If the request can target data streams, this argument determines whether wildcar
Supports a list of values, such as `open,hidden`.
** *`ignore_unavailable` (Optional, boolean)*: If `true`, missing or closed indices are not included in the response.
** *`fields` (Optional, string | string[])*: List or wildcard expressions of fields to include in the statistics.
** *`wait_for_active_shards` (Optional, number | Enum("all" | "index-setting"))*: The number of shard copies that must be active before proceeding with the operation.
Set to all or any positive integer up to the total number of shards in the index (`number_of_replicas+1`).
[discrete]
==== flush
@ -6683,6 +6688,7 @@ Supports a list of values, such as `open,hidden`.
Valid values are: `all`, `open`, `closed`, `hidden`, `none`.
** *`ignore_unavailable` (Optional, boolean)*: If `false`, the request returns an error if it targets a missing or closed index.
** *`include_defaults` (Optional, boolean)*: If `true`, return all default settings in the response.
** *`local` (Optional, boolean)*: If `true`, the request retrieves information from the local node only.
[discrete]
==== get_index_template
@ -6844,7 +6850,7 @@ If successful, the request removes the alias and creates a data stream with the
The indices for the alias become hidden backing indices for the stream.
The write index for the alias becomes the write index for the stream.
{ref}/data-streams.html[Endpoint documentation]
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-migrate-to-data-stream[Endpoint documentation]
[source,ts]
----
client.indices.migrateToDataStream({ name })
@ -6863,7 +6869,7 @@ client.indices.migrateToDataStream({ name })
Update data streams.
Performs one or more data stream modification actions in a single atomic operation.
{ref}/data-streams.html[Endpoint documentation]
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-modify-data-stream[Endpoint documentation]
[source,ts]
----
client.indices.modifyDataStream({ actions })
@ -6944,7 +6950,7 @@ NOTE: When promoting a data stream, ensure the local cluster has a data stream e
If this is missing, the data stream will not be able to roll over until a matching index template is created.
This will affect the lifecycle management of the data stream and interfere with the data stream size and retention.
{ref}/data-streams.html[Endpoint documentation]
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-promote-data-stream[Endpoint documentation]
[source,ts]
----
client.indices.promoteDataStream({ name })
@ -6962,7 +6968,7 @@ client.indices.promoteDataStream({ name })
Create or update an alias.
Adds a data stream or index to an alias.
{ref}/indices-aliases.html[Endpoint documentation]
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-put-alias[Endpoint documentation]
[source,ts]
----
client.indices.putAlias({ index, name })
@ -6978,7 +6984,7 @@ Wildcard patterns that match both data streams and indices return an error.
** *`name` (string)*: Alias to update.
If the alias doesnt exist, the request creates it.
Index alias names support date math.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Query used to limit documents the alias can access.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Query used to limit documents the alias can access.
** *`index_routing` (Optional, string)*: Value used to route indexing operations to a specific shard.
If specified, this overwrites the `routing` value for indexing operations.
Data stream aliases dont support this parameter.
@ -7001,7 +7007,7 @@ If no response is received before the timeout expires, the request fails and ret
Update data stream lifecycles.
Update the data stream lifecycle of the specified data streams.
{ref}/data-streams-put-lifecycle.html[Endpoint documentation]
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-put-data-lifecycle[Endpoint documentation]
[source,ts]
----
client.indices.putDataLifecycle({ name })
@ -7060,7 +7066,7 @@ This recursive merging strategy applies not only to field mappings, but also roo
If an earlier component contains a `dynamic_templates` block, then by default new `dynamic_templates` entries are appended onto the end.
If an entry already exists with the same key, then it is overwritten by the new definition.
{ref}/indices-put-template.html[Endpoint documentation]
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-put-index-template[Endpoint documentation]
[source,ts]
----
client.indices.putIndexTemplate({ name })
@ -7158,7 +7164,7 @@ a new date field is added instead of string.
not used at all by Elasticsearch, but can be used to store
application-specific metadata.
** *`numeric_detection` (Optional, boolean)*: Automatically map strings into numeric data types for all fields.
** *`properties` (Optional, Record<string, { type } | { boost, fielddata, index, null_value, type } | { type, enabled, null_value, boost, coerce, script, on_script_error, ignore_malformed, time_series_metric, analyzer, eager_global_ordinals, index, index_options, index_phrases, index_prefixes, norms, position_increment_gap, search_analyzer, search_quote_analyzer, term_vector, format, precision_step, locale } | { relations, eager_global_ordinals, type } | { boost, eager_global_ordinals, index, index_options, script, on_script_error, normalizer, norms, null_value, similarity, split_queries_on_whitespace, time_series_dimension, type } | { type, fields, meta, copy_to } | { type } | { positive_score_impact, type } | { positive_score_impact, type } | { analyzer, index, index_options, max_shingle_size, norms, search_analyzer, search_quote_analyzer, similarity, term_vector, type } | { analyzer, boost, eager_global_ordinals, fielddata, fielddata_frequency_filter, index, index_options, index_phrases, index_prefixes, norms, position_increment_gap, search_analyzer, search_quote_analyzer, similarity, term_vector, type } | { type } | { type, null_value } | { boost, format, ignore_malformed, index, null_value, precision_step, type } | { boost, fielddata, format, ignore_malformed, index, null_value, precision_step, locale, type } | { type, default_metric, metrics, time_series_metric } | { type, dims, element_type, index, index_options, similarity } | { boost, depth_limit, doc_values, eager_global_ordinals, index, index_options, null_value, similarity, split_queries_on_whitespace, type } | { enabled, include_in_parent, include_in_root, type } | { enabled, subobjects, type } | { type, enabled, priority, time_series_dimension } | { type, meta, inference_id } | { type } | { analyzer, contexts, max_input_length, preserve_position_increments, preserve_separators, search_analyzer, type } | { value, type } | { type, index } | { path, type } | { ignore_malformed, type } | { boost, index, ignore_malformed, null_value, on_script_error, script, time_series_dimension, type } | { type } | { analyzer, boost, index, null_value, enable_position_increments, type } | { ignore_malformed, ignore_z_value, null_value, index, on_script_error, script, type } | { coerce, ignore_malformed, ignore_z_value, orientation, strategy, type } | { ignore_malformed, ignore_z_value, null_value, type } | { coerce, ignore_malformed, ignore_z_value, orientation, type } | { type, null_value } | { type, null_value } | { type, null_value } | { type, null_value } | { type, null_value } | { type, null_value } | { type, null_value, scaling_factor } | { type, null_value } | { type, null_value } | { format, type } | { type } | { type } | { type } | { type } | { type } | { type, norms, index_options, index, null_value, rules, language, country, variant, strength, decomposition, alternate, case_level, case_first, numeric, variable_top, hiragana_quaternary_mode }>)*: Mapping for a field. For new fields, this mapping can include:
** *`properties` (Optional, Record<string, { type } | { boost, fielddata, index, null_value, type } | { type, enabled, null_value, boost, coerce, script, on_script_error, ignore_malformed, time_series_metric, analyzer, eager_global_ordinals, index, index_options, index_phrases, index_prefixes, norms, position_increment_gap, search_analyzer, search_quote_analyzer, term_vector, format, precision_step, locale } | { relations, eager_global_ordinals, type } | { boost, eager_global_ordinals, index, index_options, script, on_script_error, normalizer, norms, null_value, similarity, split_queries_on_whitespace, time_series_dimension, type } | { type, fields, meta, copy_to } | { type } | { positive_score_impact, type } | { positive_score_impact, type } | { analyzer, index, index_options, max_shingle_size, norms, search_analyzer, search_quote_analyzer, similarity, term_vector, type } | { analyzer, boost, eager_global_ordinals, fielddata, fielddata_frequency_filter, index, index_options, index_phrases, index_prefixes, norms, position_increment_gap, search_analyzer, search_quote_analyzer, similarity, term_vector, type } | { type } | { type, null_value } | { boost, format, ignore_malformed, index, script, on_script_error, null_value, precision_step, type } | { boost, fielddata, format, ignore_malformed, index, script, on_script_error, null_value, precision_step, locale, type } | { type, default_metric, metrics, time_series_metric } | { type, dims, element_type, index, index_options, similarity } | { boost, depth_limit, doc_values, eager_global_ordinals, index, index_options, null_value, similarity, split_queries_on_whitespace, type } | { enabled, include_in_parent, include_in_root, type } | { enabled, subobjects, type } | { type, enabled, priority, time_series_dimension } | { type, meta, inference_id, search_inference_id } | { type } | { analyzer, contexts, max_input_length, preserve_position_increments, preserve_separators, search_analyzer, type } | { value, type } | { type, index } | { path, type } | { ignore_malformed, type } | { boost, index, ignore_malformed, null_value, on_script_error, script, time_series_dimension, type } | { type } | { analyzer, boost, index, null_value, enable_position_increments, type } | { ignore_malformed, ignore_z_value, null_value, index, on_script_error, script, type } | { coerce, ignore_malformed, ignore_z_value, index, orientation, strategy, type } | { ignore_malformed, ignore_z_value, null_value, type } | { coerce, ignore_malformed, ignore_z_value, orientation, type } | { type, null_value } | { type, null_value } | { type, null_value } | { type, null_value } | { type, null_value } | { type, null_value } | { type, null_value, scaling_factor } | { type, null_value } | { type, null_value } | { format, type } | { type } | { type } | { type } | { type } | { type } | { type, norms, index_options, index, null_value, rules, language, country, variant, strength, decomposition, alternate, case_level, case_first, numeric, variable_top, hiragana_quaternary_mode }>)*: Mapping for a field. For new fields, this mapping can include:
- Field name
- Field data type
@ -7227,6 +7233,9 @@ hidden data streams. Supports a list of values, such as
received before the timeout expires, the request fails and returns an
error.
** *`preserve_existing` (Optional, boolean)*: If `true`, existing index settings remain unchanged.
** *`reopen` (Optional, boolean)*: Whether to close and reopen the index to apply non-dynamic settings.
If set to `true` the indices to which the settings are being applied
will be closed temporarily and then reopened in order to apply the changes.
** *`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.
@ -7394,6 +7403,7 @@ client.indices.reloadSearchAnalyzers({ index })
** *`allow_no_indices` (Optional, boolean)*: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
** *`expand_wildcards` (Optional, Enum("all" | "open" | "closed" | "hidden" | "none") | Enum("all" | "open" | "closed" | "hidden" | "none")[])*: Whether to expand wildcard expression to concrete indices that are open, closed or both.
** *`ignore_unavailable` (Optional, boolean)*: Whether specified concrete indices should be ignored when unavailable (missing or closed)
** *`resource` (Optional, string)*: Changed resource to reload analyzers from if applicable
[discrete]
==== resolve_cluster
@ -7585,6 +7595,8 @@ If no response is received before the timeout expires, the request fails and ret
If no response is received before the timeout expires, the request fails and returns an error.
** *`wait_for_active_shards` (Optional, number | Enum("all" | "index-setting"))*: The number of shard copies that must be active before proceeding with the operation.
Set to all or any positive integer up to the total number of shards in the index (`number_of_replicas+1`).
** *`lazy` (Optional, boolean)*: If set to true, the rollover action will only mark a data stream to signal that it needs to be rolled over at the next write.
Only allowed on data streams.
[discrete]
==== segments
@ -7720,6 +7732,8 @@ client.indices.simulateIndexTemplate({ name })
* *Request (object):*
** *`name` (string)*: Name of the index to simulate
** *`create` (Optional, boolean)*: Whether the index template we optionally defined in the body should only be dry-run added if new or can also replace an existing one
** *`cause` (Optional, string)*: User defined reason for dry-run creating the new template for simulation purposes
** *`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.
** *`include_defaults` (Optional, boolean)*: If true, returns all relevant default configurations for the index template.
@ -7765,6 +7779,7 @@ references a component template that might not exist
** *`deprecated` (Optional, boolean)*: Marks this index template as deprecated. When creating or updating a non-deprecated index template
that uses deprecated components, Elasticsearch will emit a deprecation warning.
** *`create` (Optional, boolean)*: If true, the template passed in the body is only used if no existing templates match the same index patterns. If false, the simulation uses the template with the highest priority. Note that the template is not permanently added or updated in either case; it is only used for the simulation.
** *`cause` (Optional, string)*: User defined reason for dry-run creating the new template for simulation purposes
** *`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.
** *`include_defaults` (Optional, boolean)*: If true, returns all relevant default configurations for the index template.
@ -7868,7 +7883,7 @@ such as `open,hidden`.
Create or update an alias.
Adds a data stream or index to an alias.
{ref}/indices-aliases.html[Endpoint documentation]
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-update-aliases[Endpoint documentation]
[source,ts]
----
client.indices.updateAliases({ ... })
@ -7889,7 +7904,7 @@ If no response is received before the timeout expires, the request fails and ret
Validate a query.
Validates a query without running it.
{ref}/search-validate.html[Endpoint documentation]
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-validate-query[Endpoint documentation]
[source,ts]
----
client.indices.validateQuery({ ... })
@ -7902,7 +7917,7 @@ client.indices.validateQuery({ ... })
** *`index` (Optional, string | string[])*: List of data streams, indices, and aliases to search.
Supports wildcards (`*`).
To search all data streams or indices, omit this parameter or use `*` or `_all`.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Query in the Lucene query string syntax.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Query in the Lucene query string syntax.
** *`allow_no_indices` (Optional, boolean)*: If `false`, the request returns an error if any wildcard expression, index alias, or `_all` value targets only missing or closed indices.
This behavior applies even if the request targets other open indices.
** *`all_shards` (Optional, boolean)*: If `true`, the validation is executed on all shards instead of one random shard per index.
@ -7924,6 +7939,51 @@ Valid values are: `all`, `open`, `closed`, `hidden`, `none`.
[discrete]
=== inference
[discrete]
==== chat_completion_unified
Perform chat completion inference
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-inference-unified-inference[Endpoint documentation]
[source,ts]
----
client.inference.chatCompletionUnified({ inference_id, messages })
----
[discrete]
==== Arguments
* *Request (object):*
** *`inference_id` (string)*: The inference Id
** *`messages` ({ content, role, tool_call_id, tool_calls }[])*: A list of objects representing the conversation.
** *`model` (Optional, string)*: The ID of the model to use.
** *`max_completion_tokens` (Optional, number)*: The upper bound limit for the number of tokens that can be generated for a completion request.
** *`stop` (Optional, string[])*: A sequence of strings to control when the model should stop generating additional tokens.
** *`temperature` (Optional, float)*: The sampling temperature to use.
** *`tool_choice` (Optional, string | { type, function })*: Controls which tool is called by the model.
** *`tools` (Optional, { type, function }[])*: A list of tools that the model can call.
** *`top_p` (Optional, float)*: Nucleus sampling, an alternative to sampling with temperature.
** *`timeout` (Optional, string | -1 | 0)*: Specifies the amount of time to wait for the inference request to complete.
[discrete]
==== completion
Perform completion inference on the service
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-inference-inference[Endpoint documentation]
[source,ts]
----
client.inference.completion({ inference_id, input })
----
[discrete]
==== Arguments
* *Request (object):*
** *`inference_id` (string)*: The inference Id
** *`input` (string | string[])*: Inference input.
Either a string or an array of strings.
** *`task_settings` (Optional, User-defined value)*: Optional task settings
** *`timeout` (Optional, string | -1 | 0)*: Specifies the amount of time to wait for the inference request to complete.
[discrete]
==== delete
Delete an inference endpoint
@ -7939,7 +7999,7 @@ client.inference.delete({ inference_id })
* *Request (object):*
** *`inference_id` (string)*: The inference identifier.
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion"))*: The task type
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion" | "chat_completion"))*: The task type
** *`dry_run` (Optional, boolean)*: When true, the endpoint is not deleted and a list of ingest processors which reference this endpoint is returned.
** *`force` (Optional, boolean)*: When true, the inference endpoint is forcefully deleted even if it is still being used by ingest processors or semantic text fields.
@ -7957,43 +8017,9 @@ client.inference.get({ ... })
==== Arguments
* *Request (object):*
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion"))*: The task type
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion" | "chat_completion"))*: The task type
** *`inference_id` (Optional, string)*: The inference Id
[discrete]
==== inference
Perform inference on the service.
This API enables you to use machine learning models to perform specific tasks on data that you provide as an input.
It returns a response with the results of the tasks.
The inference endpoint you use can perform one specific task that has been defined when the endpoint was created with the create inference API.
> info
> The inference APIs enable you to use certain services, such as built-in machine learning models (ELSER, E5), models uploaded through Eland, Cohere, OpenAI, Azure, Google AI Studio, Google Vertex AI, Anthropic, Watsonx.ai, or Hugging Face. For built-in models and models uploaded through Eland, the inference APIs offer an alternative way to use and manage trained models. However, if you do not plan to use the inference APIs to use these models or if you want to use non-NLP models, use the machine learning trained model APIs.
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-inference-inference[Endpoint documentation]
[source,ts]
----
client.inference.inference({ inference_id, input })
----
[discrete]
==== Arguments
* *Request (object):*
** *`inference_id` (string)*: The unique identifier for the inference endpoint.
** *`input` (string | string[])*: The text on which you want to perform the inference task.
It can be a single string or an array.
> info
> Inference endpoints for the `completion` task type currently only support a single string as input.
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion"))*: The type of inference task that the model performs.
** *`query` (Optional, string)*: The query input, which is required only for the `rerank` task.
It is not required for other tasks.
** *`task_settings` (Optional, User-defined value)*: Task settings for the individual inference request.
These settings are specific to the task type you specified and override the task settings specified when initializing the service.
** *`timeout` (Optional, string | -1 | 0)*: The amount of time to wait for the inference request to complete.
[discrete]
==== put
Create an inference endpoint.
@ -8018,11 +8044,117 @@ client.inference.put({ inference_id })
* *Request (object):*
** *`inference_id` (string)*: The inference Id
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion"))*: The task type
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion" | "chat_completion"))*: The task type
** *`inference_config` (Optional, { chunking_settings, service, service_settings, task_settings })*
[discrete]
==== stream_inference
==== put_openai
Create an OpenAI inference endpoint.
Create an inference endpoint to perform an inference task with the `openai` service.
When you create an inference endpoint, the associated machine learning model is automatically deployed if it is not already running.
After creating the endpoint, wait for the model deployment to complete before using it.
To verify the deployment status, use the get trained model statistics API.
Look for `"state": "fully_allocated"` in the response and ensure that the `"allocation_count"` matches the `"target_allocation_count"`.
Avoid creating multiple endpoints for the same model unless required, as each endpoint consumes significant resources.
{ref}/infer-service-openai.html[Endpoint documentation]
[source,ts]
----
client.inference.putOpenai({ task_type, openai_inference_id, service, service_settings })
----
[discrete]
==== Arguments
* *Request (object):*
** *`task_type` (Enum("chat_completion" | "completion" | "text_embedding"))*: The type of the inference task that the model will perform.
NOTE: The `chat_completion` task type only supports streaming and only through the _stream API.
** *`openai_inference_id` (string)*: The unique identifier of the inference endpoint.
** *`service` (Enum("openai"))*: The type of service supported for the specified task type. In this case, `openai`.
** *`service_settings` ({ api_key, dimensions, model_id, organization_id, rate_limit, url })*: Settings used to install the inference model. These settings are specific to the `openai` service.
** *`chunking_settings` (Optional, { max_chunk_size, overlap, sentence_overlap, strategy })*: The chunking configuration object.
** *`task_settings` (Optional, { user })*: Settings to configure the inference task.
These settings are specific to the task type you specified.
[discrete]
==== put_watsonx
Create a Watsonx inference endpoint.
Create an inference endpoint to perform an inference task with the `watsonxai` service.
You need an IBM Cloud Databases for Elasticsearch deployment to use the `watsonxai` inference service.
You can provision one through the IBM catalog, the Cloud Databases CLI plug-in, the Cloud Databases API, or Terraform.
When you create an inference endpoint, the associated machine learning model is automatically deployed if it is not already running.
After creating the endpoint, wait for the model deployment to complete before using it.
To verify the deployment status, use the get trained model statistics API.
Look for `"state": "fully_allocated"` in the response and ensure that the `"allocation_count"` matches the `"target_allocation_count"`.
Avoid creating multiple endpoints for the same model unless required, as each endpoint consumes significant resources.
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-inference-put-watsonx[Endpoint documentation]
[source,ts]
----
client.inference.putWatsonx({ task_type, watsonx_inference_id, service, service_settings })
----
[discrete]
==== Arguments
* *Request (object):*
** *`task_type` (Enum("text_embedding"))*: The task type.
The only valid task type for the model to perform is `text_embedding`.
** *`watsonx_inference_id` (string)*: The unique identifier of the inference endpoint.
** *`service` (Enum("openai"))*: The type of service supported for the specified task type. In this case, `watsonxai`.
** *`service_settings` ({ api_key, api_version, model_id, project_id, rate_limit, url })*: Settings used to install the inference model. These settings are specific to the `watsonxai` service.
[discrete]
==== rerank
Perform rereanking inference on the service
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-inference-inference[Endpoint documentation]
[source,ts]
----
client.inference.rerank({ inference_id, query, input })
----
[discrete]
==== Arguments
* *Request (object):*
** *`inference_id` (string)*: The unique identifier for the inference endpoint.
** *`query` (string)*: Query input.
** *`input` (string | string[])*: The text on which you want to perform the inference task.
It can be a single string or an array.
> info
> Inference endpoints for the `completion` task type currently only support a single string as input.
** *`task_settings` (Optional, User-defined value)*: Task settings for the individual inference request.
These settings are specific to the task type you specified and override the task settings specified when initializing the service.
** *`timeout` (Optional, string | -1 | 0)*: The amount of time to wait for the inference request to complete.
[discrete]
==== sparse_embedding
Perform sparse embedding inference on the service
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-inference-inference[Endpoint documentation]
[source,ts]
----
client.inference.sparseEmbedding({ inference_id, input })
----
[discrete]
==== Arguments
* *Request (object):*
** *`inference_id` (string)*: The inference Id
** *`input` (string | string[])*: Inference input.
Either a string or an array of strings.
** *`task_settings` (Optional, User-defined value)*: Optional task settings
** *`timeout` (Optional, string | -1 | 0)*: Specifies the amount of time to wait for the inference request to complete.
[discrete]
==== stream_completion
Perform streaming inference.
Get real-time responses for completion tasks by delivering answers incrementally, reducing response times during computation.
This API works only with the completion task type.
@ -8034,7 +8166,7 @@ This API requires the `monitor_inference` cluster privilege (the built-in `infer
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-inference-stream-inference[Endpoint documentation]
[source,ts]
----
client.inference.streamInference({ inference_id, input })
client.inference.streamCompletion({ inference_id, input })
----
[discrete]
@ -8046,14 +8178,16 @@ client.inference.streamInference({ inference_id, input })
It can be a single string or an array.
NOTE: Inference endpoints for the completion task type currently only support a single string as input.
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion"))*: The type of task that the model performs.
** *`task_settings` (Optional, User-defined value)*: Optional task settings
[discrete]
==== unified_inference
Perform inference on the service using the Unified Schema
==== text_embedding
Perform text embedding inference on the service
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-inference-inference[Endpoint documentation]
[source,ts]
----
client.inference.unifiedInference({ inference_id, messages })
client.inference.textEmbedding({ inference_id, input })
----
[discrete]
@ -8061,15 +8195,9 @@ client.inference.unifiedInference({ inference_id, messages })
* *Request (object):*
** *`inference_id` (string)*: The inference Id
** *`messages` ({ content, role, tool_call_id, tool_calls }[])*: A list of objects representing the conversation.
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion"))*: The task type
** *`model` (Optional, string)*: The ID of the model to use.
** *`max_completion_tokens` (Optional, number)*: The upper bound limit for the number of tokens that can be generated for a completion request.
** *`stop` (Optional, string[])*: A sequence of strings to control when the model should stop generating additional tokens.
** *`temperature` (Optional, float)*: The sampling temperature to use.
** *`tool_choice` (Optional, string | { type, function })*: Controls which tool is called by the model.
** *`tools` (Optional, { type, function }[])*: A list of tools that the model can call.
** *`top_p` (Optional, float)*: Nucleus sampling, an alternative to sampling with temperature.
** *`input` (string | string[])*: Inference input.
Either a string or an array of strings.
** *`task_settings` (Optional, User-defined value)*: Optional task settings
** *`timeout` (Optional, string | -1 | 0)*: Specifies the amount of time to wait for the inference request to complete.
[discrete]
@ -8093,7 +8221,7 @@ client.inference.update({ inference_id })
* *Request (object):*
** *`inference_id` (string)*: The unique identifier of the inference endpoint.
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion"))*: The type of inference task that the model performs.
** *`task_type` (Optional, Enum("sparse_embedding" | "text_embedding" | "rerank" | "completion" | "chat_completion"))*: The type of inference task that the model performs.
** *`inference_config` (Optional, { chunking_settings, service, service_settings, task_settings })*
[discrete]
@ -8978,7 +9106,7 @@ client.ml.evaluateDataFrame({ evaluation, index })
* *Request (object):*
** *`evaluation` ({ classification, outlier_detection, regression })*: Defines the type of evaluation you want to perform.
** *`index` (string)*: Defines the `index` in which the evaluation will be performed.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: A query clause that retrieves a subset of data from the source index.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: A query clause that retrieves a subset of data from the source index.
[discrete]
==== explain_data_frame_analytics
@ -9628,7 +9756,6 @@ be retrieved and then added to another cluster.
** *`from` (Optional, number)*: Skips the specified number of models.
** *`include` (Optional, Enum("definition" | "feature_importance_baseline" | "hyperparameters" | "total_feature_importance" | "definition_status"))*: A comma delimited string of optional fields to include in the response
body.
** *`include_model_definition` (Optional, boolean)*: parameter is deprecated! Use [include=definition] instead
** *`size` (Optional, number)*: Specifies the maximum number of models to obtain.
** *`tags` (Optional, string | string[])*: A comma delimited string of tags. A trained model can have many tags, or
none. When supplied, only trained models that contain all the supplied
@ -9977,15 +10104,15 @@ The default value is either the bucket span for short bucket spans, or, for long
fraction of the bucket span. When `frequency` is shorter than the bucket span, interim results for the last
(partial) bucket are written then eventually overwritten by the full bucket results. If the datafeed uses
aggregations, this value must be divisible by the interval of the date histogram aggregation.
** *`indices` (Optional, string | string[])*: An array of index names. Wildcards are supported. If any of the indices are in remote clusters, the machine
learning nodes must have the `remote_cluster_client` role.
** *`indices` (Optional, string | string[])*: An array of index names. Wildcards are supported. If any of the indices are in remote clusters, the master
nodes and the machine learning nodes must have the `remote_cluster_client` role.
** *`indices_options` (Optional, { allow_no_indices, expand_wildcards, ignore_unavailable, ignore_throttled })*: Specifies index expansion options that are used during search
** *`job_id` (Optional, string)*: Identifier for the anomaly detection job.
** *`max_empty_searches` (Optional, number)*: If a real-time datafeed has never seen any data (including during any initial training period), it automatically
stops and closes the associated job after this many real-time searches return no documents. In other words,
it stops after `frequency` times `max_empty_searches` of real-time operation. If not set, a datafeed with no
end time that sees no data remains started until it is explicitly stopped. By default, it is not set.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The Elasticsearch query domain-specific language (DSL). This value corresponds to the query object in an
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The Elasticsearch query domain-specific language (DSL). This value corresponds to the query object in an
Elasticsearch search POST body. All the options that are supported by Elasticsearch can be used, as this
object is passed verbatim to Elasticsearch.
** *`query_delay` (Optional, string | -1 | 0)*: The number of seconds behind real time that data is queried. For example, if data from 10:04 a.m. might
@ -10538,7 +10665,7 @@ learning nodes must have the `remote_cluster_client` role.
stops and closes the associated job after this many real-time searches return no documents. In other words,
it stops after `frequency` times `max_empty_searches` of real-time operation. If not set, a datafeed with no
end time that sees no data remains started until it is explicitly stopped. By default, it is not set.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The Elasticsearch query domain-specific language (DSL). This value corresponds to the query object in an
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The Elasticsearch query domain-specific language (DSL). This value corresponds to the query object in an
Elasticsearch search POST body. All the options that are supported by Elasticsearch can be used, as this
object is passed verbatim to Elasticsearch. Note that if you change the query, the analyzed data is also
changed. Therefore, the time required to learn might be long and the understandability of the results is
@ -11274,7 +11401,7 @@ This parameter has the following rules:
* Only one rollup index may be specified. If more than one are supplied, an exception occurs.
* Wildcard expressions (`*`) may be used. If they match more than one rollup index, an exception occurs. However, you can use an expression to match multiple non-rollup indices or data streams.
** *`aggregations` (Optional, Record<string, { aggregations, meta, adjacency_matrix, auto_date_histogram, avg, avg_bucket, boxplot, bucket_script, bucket_selector, bucket_sort, bucket_count_ks_test, bucket_correlation, cardinality, categorize_text, children, composite, cumulative_cardinality, cumulative_sum, date_histogram, date_range, derivative, diversified_sampler, extended_stats, extended_stats_bucket, frequent_item_sets, filter, filters, geo_bounds, geo_centroid, geo_distance, geohash_grid, geo_line, geotile_grid, geohex_grid, global, histogram, ip_range, ip_prefix, inference, line, matrix_stats, max, max_bucket, median_absolute_deviation, min, min_bucket, missing, moving_avg, moving_percentiles, moving_fn, multi_terms, nested, normalize, parent, percentile_ranks, percentiles, percentiles_bucket, range, rare_terms, rate, reverse_nested, random_sampler, sampler, scripted_metric, serial_diff, significant_terms, significant_text, stats, stats_bucket, string_stats, sum, sum_bucket, terms, time_series, top_hits, t_test, top_metrics, value_count, weighted_avg, variable_width_histogram }>)*: Specifies aggregations.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Specifies a DSL query that is subject to some limitations.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: Specifies a DSL query that is subject to some limitations.
** *`size` (Optional, number)*: Must be zero if set, as rollups work on pre-aggregated data.
** *`rest_total_hits_as_int` (Optional, boolean)*: Indicates whether hits.total should be rendered as an integer or an object in the rest search response
** *`typed_keys` (Optional, boolean)*: Specify whether aggregation and suggester names should be prefixed by their respective types in the response
@ -12777,14 +12904,14 @@ These APIs are used internally by Kibana in order to provide OpenID Connect base
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-oidc-logout[Endpoint documentation]
[source,ts]
----
client.security.oidcLogout({ access_token })
client.security.oidcLogout({ token })
----
[discrete]
==== Arguments
* *Request (object):*
** *`access_token` (string)*: The access token to be invalidated.
** *`token` (string)*: The access token to be invalidated.
** *`refresh_token` (Optional, string)*: The refresh token to be invalidated.
[discrete]
@ -13638,7 +13765,7 @@ client.simulate.ingest({ docs })
This value can be overridden by specifying an index on each document.
If you specify this parameter in the request path, it is used for any documents that do not explicitly specify an index argument.
** *`component_template_substitutions` (Optional, Record<string, { template, version, _meta, deprecated }>)*: A map of component template names to substitute component template definition objects.
** *`index_template_subtitutions` (Optional, Record<string, { index_patterns, composed_of, template, version, priority, _meta, allow_auto_create, data_stream, deprecated, ignore_missing_component_templates }>)*: A map of index template names to substitute index template definition objects.
** *`index_template_substitutions` (Optional, Record<string, { index_patterns, composed_of, template, version, priority, _meta, allow_auto_create, data_stream, deprecated, ignore_missing_component_templates }>)*: A map of index template names to substitute index template definition objects.
** *`mapping_addition` (Optional, { all_field, date_detection, dynamic, dynamic_date_formats, dynamic_templates, _field_names, index_field, _meta, numeric_detection, properties, _routing, _size, _source, runtime, enabled, subobjects, _data_stream_timestamp })*
** *`pipeline_substitutions` (Optional, Record<string, { description, on_failure, processors, version, deprecated, _meta }>)*: Pipelines to test.
If you dont specify the `pipeline` request path parameter, this parameter is required.
@ -14513,7 +14640,7 @@ It ignores other request body parameters.
** *`fetch_size` (Optional, number)*: The maximum number of rows (or entries) to return in one response.
** *`field_multi_value_leniency` (Optional, boolean)*: If `false`, the API returns an exception when encountering multiple values for a field.
If `true`, the API is lenient and returns the first value from the array with no guarantee of consistent results.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The Elasticsearch query DSL for additional filtering.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The Elasticsearch query DSL for additional filtering.
** *`index_using_frozen` (Optional, boolean)*: If `true`, the search can run on frozen indices.
** *`keep_alive` (Optional, string | -1 | 0)*: The retention period for an async or saved synchronous search.
** *`keep_on_completion` (Optional, boolean)*: If `true`, Elasticsearch stores synchronous searches if you also specify the `wait_for_completion_timeout` parameter.
@ -14554,7 +14681,7 @@ client.sql.translate({ query })
* *Request (object):*
** *`query` (string)*: The SQL query to run.
** *`fetch_size` (Optional, number)*: The maximum number of rows (or entries) to return in one response.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The Elasticsearch query DSL for additional filtering.
** *`filter` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: The Elasticsearch query DSL for additional filtering.
** *`time_zone` (Optional, string)*: The ISO-8601 time zone ID for the search.
[discrete]
@ -15856,7 +15983,7 @@ client.watcher.queryWatches({ ... })
It must be non-negative.
** *`size` (Optional, number)*: The number of hits to return.
It must be non-negative.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: A query that filters the watches to be returned.
** *`query` (Optional, { bool, boosting, common, combined_fields, constant_score, dis_max, distance_feature, exists, function_score, fuzzy, geo_bounding_box, geo_distance, geo_grid, geo_polygon, geo_shape, has_child, has_parent, ids, intervals, knn, match, match_all, match_bool_prefix, match_none, match_phrase, match_phrase_prefix, more_like_this, multi_match, nested, parent_id, percolate, pinned, prefix, query_string, range, rank_feature, regexp, rule, script, script_score, semantic, shape, simple_query_string, span_containing, span_field_masking, span_first, span_multi, span_near, span_not, span_or, span_term, span_within, sparse_vector, term, terms, terms_set, text_expansion, weighted_tokens, wildcard, wrapper, type })*: A query that filters the watches to be returned.
** *`sort` (Optional, string | { _score, _doc, _geo_distance, _script } | string | { _score, _doc, _geo_distance, _script }[])*: One or more fields used to sort the search results.
** *`search_after` (Optional, number | number | string | boolean | null[])*: Retrieve the next page of hits using a set of sort values from the previous page.

View File

@ -1,25 +1,27 @@
[[advanced-config]]
=== Advanced configuration
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/advanced-config.html
---
If you need to customize the client behavior heavily, you are in the right
place! The client enables you to customize the following internals:
# 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>>.
::::{note}
For information about the `Transport` class, refer to [Transport](/reference/transport.md).
::::
[discrete]
==== `ConnectionPool`
This class is responsible for keeping in memory all the {es} Connection 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.
## `ConnectionPool` [_connectionpool]
[source,js]
----
This class is responsible for keeping in memory all the {{es}} Connection 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 {
@ -34,19 +36,14 @@ const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
----
```
[discrete]
==== `Connection`
## `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
(Node.js core), you should override the `request` method of this class.
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 (Node.js core), you should override the `request` method of this class.
[source,js]
----
```js
const { Client, BaseConnection } = require('@elastic/elasticsearch')
class MyConnection extends BaseConnection {
@ -60,22 +57,19 @@ const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
----
```
[discrete]
==== `Serializer`
## `Serializer` [_serializer]
This class is responsible for the serialization of every request, it offers the
following methods:
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.
[source,js]
----
```js
const { Client, Serializer } = require('@elastic/elasticsearch')
class MySerializer extends Serializer {
@ -89,11 +83,10 @@ const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
----
```
[discrete]
[[redaction]]
==== Redaction of potentially sensitive data
## 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.
@ -101,8 +94,7 @@ If your configuration requires extra headers or other configurations that may in
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]`.
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
@ -115,12 +107,11 @@ try {
} 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:
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
@ -138,12 +129,11 @@ try {
} 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.
Alternatively, if you know youre 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.
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
@ -157,14 +147,16 @@ try {
} 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.
::::{warning}
Setting `redaction.type` to `off` is not recommended in production environments.
::::
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
@ -178,18 +170,10 @@ try {
} catch (err) {
console.log(err.meta.meta.request.options.headers.authorization) // the actual header value will be logged
}
----
```
[discrete]
==== 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 Elasticsearch 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 Elasticsearch without upgrading
everything at once. Elasticsearch 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`.
## 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 Elasticsearch 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 Elasticsearch without upgrading everything at once. Elasticsearch 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`.

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,13 @@
[[as_stream_examples]]
=== asStream
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/as_stream_examples.html
---
Instead of getting the parsed body back, you will get the raw Node.js stream of
data.
# asStream [as_stream_examples]
[source,js]
----
Instead of getting the parsed body back, you will get the raw Node.js stream of data.
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -66,13 +68,14 @@ async function run () {
}
run().catch(console.log)
----
```
TIP: This can be useful if you need to pipe the {es}'s response to a proxy, or
send it directly to another source.
::::{tip}
This can be useful if you need to pipe the {{es}}'s response to a proxy, or send it directly to another source.
::::
[source,js]
----
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -96,4 +99,5 @@ fastify.post('/search/:index', async (req, reply) => {
})
fastify.listen(3000)
----
```

View File

@ -0,0 +1,421 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/basic-config.html
---
# Basic configuration [basic-config]
This page explains the basic configuration options for the JavaScript client.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' },
maxRetries: 5,
sniffOnStart: true
})
```
### `node` or `nodes`
The {{es}} endpoint to use. It can be a single string or an array of strings:
```js
node: 'http://localhost:9200'
```
```js
nodes: ['http://localhost:9200', 'http://localhost:9201']
```
Or it can be an object (or an array of objects) that represents the node:
```js
node: {
url: new URL('http://localhost:9200'),
tls: 'tls options',
agent: 'http agent options',
id: 'custom node id',
headers: { 'custom': 'headers' },
roles: {
master: true,
data: true,
ingest: true,
ml: false
}
}
```
---
### `auth`
Default: `null`
Your authentication data. You can use both basic authentication and [ApiKey](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-create-api-key).
See [Authentication](/reference/connecting.md#authentication) for more details.
Basic authentication:
```js
auth: {
username: 'elastic',
password: 'changeme'
}
```
[ApiKey](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-create-api-key) authentication:
```js
auth: {
apiKey: 'base64EncodedKey'
}
```
Bearer authentication, useful for [service account tokens](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-create-service-token). Be aware that it does not handle automatic token refresh:
```js
auth: {
bearer: 'token'
}
```
---
### `maxRetries`
Type: `number`<br>
Default: `3`
Max number of retries for each request.
---
### `requestTimeout`
Type: `number`<br>
Default: `No value`
Max request timeout in milliseconds for each request.
---
### `pingTimeout`
Type: `number`<br>
Default: `3000`
Max ping request timeout in milliseconds for each request.
---
### `sniffInterval`
Type: `number, boolean`<br>
Default: `false`
Perform a sniff operation every `n` milliseconds.
:::{tip}
Sniffing might not be the best solution. Before using the various `sniff` options, review this [blog post](https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how).
:::
---
### `sniffOnStart`
Type: `boolean`<br>
Default: `false`
Perform a sniff once the client is started. Be sure to review the sniffing best practices [blog post](https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how).
---
### `sniffEndpoint`
Type: `string`<br>
Default: `'_nodes/_all/http'`
Endpoint to ping during a sniff. Be sure to review the sniffing best practices [blog post](https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how).
---
### `sniffOnConnectionFault`
Type: `boolean`<br>
Default: `false`
Perform a sniff on connection fault. Be sure to review the sniffing best practices [blog post](https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how).
---
### `resurrectStrategy`
Type: `string`<br>
Default: `'ping'`
Configure the node resurrection strategy.<br>
Options: `'ping'`, `'optimistic'`, `'none'`
---
### `suggestCompression`
Type: `boolean`<br>
Default: `false`
Adds an `accept-encoding` header to every request.
---
### `compression`
Type: `string, boolean`<br>
Default: `false`
Enables gzip request body compression.<br>
Options: `'gzip'`, `false`
---
### `tls`
Type: `http.SecureContextOptions`<br>
Default: `null`
The [tls configuraton](https://nodejs.org/api/tls.html).
---
### `proxy`
Type: `string, URL`<br>
Default: `null`
If you are using an http(s) proxy, you can put its url here. The client will automatically handle the connection to it.
```js
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'
})
```
---
### `agent`
Type: `http.AgentOptions, function`<br>
Default: `null`
http agent [options](https://nodejs.org/api/http.html#http_new_agent_options), or a function that returns an actual http agent instance. If you want to disable the http agent use entirely (and disable the `keep-alive` feature), set the agent to `false`.
```js
const client = new Client({
node: 'http://localhost:9200',
agent: { agent: 'options' }
})
const client = new Client({
node: 'http://localhost:9200',
// the function takes as parameter the option
// object passed to the Connection constructor
agent: (opts) => new CustomAgent()
})
const client = new Client({
node: 'http://localhost:9200',
// Disable agent and keep-alive
agent: false
})
```
---
### `nodeFilter`
Type: `function`
Filter that indicates whether a node should be used for a request. Default function definition:
```js
function defaultNodeFilter (node) {
// avoid master only nodes
if (node.roles.master === true &&
node.roles.data === false &&
node.roles.ingest === false) {
return false
}
return true
}
```
---
### `nodeSelector`
Type: `function`<br>
Default: `'round-robin'`
Custom selection strategy.<br>
Options: `'round-robin'`, `'random'`, custom function
Custom function example:
```js
function nodeSelector (connections) {
const index = calculateIndex()
return connections[index]
}
```
---
### `generateRequestId`
Type: `function`<br>
function to generate the request id for every request, it takes two parameters, the request parameters and options. By default, it generates an incremental integer for every request.
Custom function example:
```js
function generateRequestId (params, options) {
// your id generation logic
// must be syncronous
return 'id'
}
```
---
### `name`
Type: `string, symbol`<br>
Default: `elasticsearch-js`
The name to identify the client instance in the events.
---
### `opaqueIdPrefix`
Type: `string`<br>
Default: `null`
A string that will be use to prefix any `X-Opaque-Id` header.
See [`X-Opaque-Id` support](/reference/observability.md#_x_opaque_id_support) for more details.
---
### `headers`
Type: `object`<br>
Default: `{}`
A set of custom headers to send in every request.
---
### `context`
Type: `object`<br>
Default: `null`
A custom object that you can use for observability in your events. It will be merged with the API level context option.
---
### `enableMetaHeader`
Type: `boolean`<br>
Default: `true`
If true, adds an header named `'x-elastic-client-meta'`, containing some minimal telemetry data, such as the client and platform version.
---
### `cloud`
Type: `object`<br>
Default: `null`
Custom configuration for connecting to [Elastic Cloud](https://cloud.elastic.co). See [Authentication](/reference/connecting.md) for more details.
Cloud configuration example:
```js
const client = new Client({
cloud: {
id: '<cloud-id>'
},
auth: {
username: 'elastic',
password: 'changeme'
}
})
```
---
### `disablePrototypePoisoningProtection`
Default: `true`
`boolean`, `'proto'`, `'constructor'` - The client can protect you against prototype poisoning attacks. For more information, refer to [Square Brackets are the Enemy](https://web.archive.org/web/20200319091159/https://hueniverse.com/square-brackets-are-the-enemy-ff5b9fd8a3e8?gi=184a27ee2a08). If needed, you can enable prototype poisoning protection entirely (`false`) or one of the two checks (`'proto'` or `'constructor'`). For performance reasons, it is disabled by default. To learn more, refer to the [`secure-json-parse` documentation](https://github.com/fastify/secure-json-parse).
---
### `caFingerprint`
Type: `string`<br>
Default: `null`
If configured, verify that the fingerprint of the CA certificate that has signed the certificate of the server matches the supplied fingerprint. Only accepts SHA256 digest fingerprints.
---
### `maxResponseSize`
Type: `number`<br>
Default: `null`
When configured, `maxResponseSize` verifies that the uncompressed response size is lower than the configured number. If its higher, the request will be canceled. The `maxResponseSize` cannot be higher than the value of `buffer.constants.MAX_STRING_LENGTH`.
---
### `maxCompressedResponseSize`
Type: `number`<br>
Default: `null`
When configured, `maxCompressedResponseSize` verifies that the compressed response size is lower than the configured number. If its higher, the request will be canceled. The `maxCompressedResponseSize` cannot be higher than the value of `buffer.constants.MAX_STRING_LENGTH`.
---
### `redaction`
Type: `object`<br>
Default: A configuration that will replace known sources of sensitive data in `Error` metadata
Options for how to redact potentially sensitive data from metadata attached to `Error` objects
::::{note}
[Read about redaction](/reference/advanced-config.md#redaction) for more details
::::
---
### `serverMode`
Type: `string`<br>
Default: `"stack"`
Setting to `"stack"` sets defaults assuming a traditional (non-serverless) {{es}} instance. Setting to `"serverless"` sets defaults to work more seamlessly with [Elastic Cloud Serverless](https://www.elastic.co/guide/en/serverless/current/intro.html), like enabling compression and disabling features that assume the possibility of multiple {{es}} nodes.

View File

@ -1,13 +1,18 @@
[[bulk_examples]]
=== Bulk
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/bulk_examples.html
---
With the {jsclient}/api-reference.html#_bulk[`bulk` API], you can perform multiple index/delete operations in a
single API call. The `bulk` API significantly increases indexing speed.
# Bulk [bulk_examples]
NOTE: You can also use the <<bulk-helper,bulk helper>>.
With the [`bulk` API](/reference/api-reference.md#_bulk), you can perform multiple index/delete operations in a single API call. The `bulk` API significantly increases indexing speed.
[source,js]
----
::::{note}
You can also use the [bulk helper](/reference/client-helpers.md#bulk-helper).
::::
```js
'use strict'
require('array.prototype.flatmap').shim()
@ -90,4 +95,5 @@ async function run () {
}
run().catch(console.log)
----
```

34
docs/reference/child.md Normal file
View File

@ -0,0 +1,34 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/child.html
---
# Creating a child client [child]
There are some use cases where you may need multiple instances of the client. You can easily do that by calling `new Client()` as many times as you need, but you will lose all the benefits of using one single client, such as the long living connections and the connection pool handling. To avoid this problem, the client offers a `child` API, which returns a new client instance that shares the connection pool with the parent client.
::::{note}
The event emitter is shared between the parent and the child(ren). If you extend the parent client, the child client will have the same extensions, while if the child client adds an extension, the parent client will not be extended.
::::
You can pass to the `child` every client option you would pass to a normal client, but the connection pool specific options (`ssl`, `agent`, `pingTimeout`, `Connection`, and `resurrectStrategy`).
::::{warning}
If you call `close` in any of the parent/child clients, every client will be closed.
::::
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<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)
```

View File

@ -0,0 +1,505 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/client-helpers.html
---
# Client helpers [client-helpers]
The client comes with an handy collection of helpers to give you a more comfortable experience with some APIs.
::::{warning}
The client helpers are experimental, and the API may change in the next minor releases. The helpers will not work in any Node.js version lower than 10.
::::
## Bulk helper [bulk-helper]
Added in `v7.7.0`
Running bulk requests can be complex due to the shape of the API, this helper aims to provide a nicer developer experience around the Bulk API.
### Usage [_usage_3]
```js
const { createReadStream } = require('fs')
const split = require('split2')
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<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)
// {
// total: number,
// failed: number,
// retry: number,
// successful: number,
// time: number,
// bytes: number,
// aborted: boolean
// }
```
To create a new instance of the Bulk helper, access it as shown in the example above, the configuration options are:
| | |
| --- | --- |
| `datasource` | An array, async generator or a readable stream with the data you need to index/create/update/delete. It can be an array of strings or objects, but also a stream of json strings or JavaScript objects.<br> If it is a stream, we recommend to use the [`split2`](https://www.npmjs.com/package/split2) package, that splits the stream on new lines delimiters.<br> This parameter is mandatory.<br><br>```js<br>const { createReadStream } = require('fs')<br>const split = require('split2')<br>const b = client.helpers.bulk({<br> // if you just use split(), the data will be used as array of strings<br> datasource: createReadStream('./dataset.ndjson').pipe(split())<br> // if you need to manipulate the data, you can pass JSON.parse to split<br> datasource: createReadStream('./dataset.ndjson').pipe(split(JSON.parse))<br>})<br>```<br> |
| `onDocument` | A function that is called for each document of the datasource. Inside this function you can manipulate the document and you must return the operation you want to execute with the document. Look at the [Bulk API documentation](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-bulk) to see the supported operations.<br> This parameter is mandatory.<br><br>```js<br>const b = client.helpers.bulk({<br> onDocument (doc) {<br> return {<br> index: { _index: 'my-index' }<br> }<br> }<br>})<br>```<br> |
| `onDrop` | A function that is called for everytime a document cant be indexed and it has reached the maximum amount of retries.<br><br>```js<br>const b = client.helpers.bulk({<br> onDrop (doc) {<br> console.log(doc)<br> }<br>})<br>```<br> |
| `onSuccess` | A function that is called for each successful operation in the bulk request, which includes the result from Elasticsearch along with the original document that was sent, or `null` for delete operations.<br><br>```js<br>const b = client.helpers.bulk({<br> onSuccess ({ result, document }) {<br> console.log(`SUCCESS: Document ${result.index._id} indexed to ${result.index._index}`)<br> }<br>})<br>```<br> |
| `flushBytes` | The size of the bulk body in bytes to reach before to send it. Default of 5MB.<br> *Default:* `5000000`<br><br>```js<br>const b = client.helpers.bulk({<br> flushBytes: 1000000<br>})<br>```<br> |
| `flushInterval` | How much time (in milliseconds) the helper waits before flushing the body from the last document read.<br> *Default:* `30000`<br><br>```js<br>const b = client.helpers.bulk({<br> flushInterval: 30000<br>})<br>```<br> |
| `concurrency` | How many request is executed at the same time.<br> *Default:* `5`<br><br>```js<br>const b = client.helpers.bulk({<br> concurrency: 10<br>})<br>```<br> |
| `retries` | How many times a document is retried before to call the `onDrop` callback.<br> *Default:* Client max retries.<br><br>```js<br>const b = client.helpers.bulk({<br> retries: 3<br>})<br>```<br> |
| `wait` | How much time to wait before retries in milliseconds.<br> *Default:* 5000.<br><br>```js<br>const b = client.helpers.bulk({<br> wait: 3000<br>})<br>```<br> |
| `refreshOnCompletion` | If `true`, at the end of the bulk operation it runs a refresh on all indices or on the specified indices.<br> *Default:* false.<br><br>```js<br>const b = client.helpers.bulk({<br> refreshOnCompletion: true<br> // or<br> refreshOnCompletion: 'index-name'<br>})<br>```<br> |
### Supported operations [_supported_operations]
#### Index [_index_2]
```js
client.helpers.bulk({
datasource: myDatasource,
onDocument (doc) {
return {
index: { _index: 'my-index' }
}
}
})
```
#### Create [_create_4]
```js
client.helpers.bulk({
datasource: myDatasource,
onDocument (doc) {
return {
create: { _index: 'my-index', _id: doc.id }
}
}
})
```
#### Update [_update_3]
```js
client.helpers.bulk({
datasource: myDatasource,
onDocument (doc) {
// Note that the update operation requires you to return
// an array, where the first element is the action, while
// the second are the document option
return [
{ update: { _index: 'my-index', _id: doc.id } },
{ doc_as_upsert: true }
]
}
})
```
#### Delete [_delete_10]
```js
client.helpers.bulk({
datasource: myDatasource,
onDocument (doc) {
return {
delete: { _index: 'my-index', _id: doc.id }
}
}
})
```
### Abort a bulk operation [_abort_a_bulk_operation]
If needed, you can abort a bulk operation at any time. The bulk helper returns a [thenable](https://promisesaplus.com/), which has an `abort` method.
::::{note}
The abort method stops the execution of the bulk operation, but if you are using a concurrency higher than one, the operations that are already running will not be stopped.
::::
```js
const { createReadStream } = require('fs')
const split = require('split2')
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const b = client.helpers.bulk({
datasource: createReadStream('./dataset.ndjson').pipe(split()),
onDocument (doc) {
return {
index: { _index: 'my-index' }
}
},
onDrop (doc) {
b.abort()
}
})
console.log(await b)
```
### Passing custom options to the Bulk API [_passing_custom_options_to_the_bulk_api]
You can pass any option supported by the link: [Bulk API](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-bulk) to the helper, and the helper uses those options in conjunction with the Bulk API call.
```js
const result = await client.helpers.bulk({
datasource: [...],
onDocument (doc) {
return {
index: { _index: 'my-index' }
}
},
pipeline: 'my-pipeline'
})
```
### Usage with an async generator [_usage_with_an_async_generator]
```js
const { Client } = require('@elastic/elasticsearch')
async function * generator () {
const dataset = [
{ user: 'jon', age: 23 },
{ user: 'arya', age: 18 },
{ user: 'tyrion', age: 39 }
]
for (const doc of dataset) {
yield doc
}
}
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const result = await client.helpers.bulk({
datasource: generator(),
onDocument (doc) {
return {
index: { _index: 'my-index' }
}
}
})
console.log(result)
```
### Modifying a document before operation [_modifying_a_document_before_operation]
Added in `v8.8.2`
If you need to modify documents in your datasource before it is sent to Elasticsearch, you can return an array in the `onDocument` function rather than an operation object. The first item in the array must be the operation object, and the second item must be the document or partial document object as youd like it to be sent to Elasticsearch.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const result = await client.helpers.bulk({
datasource: [...],
onDocument (doc) {
return [
{ index: { _index: 'my-index' } },
{ ...doc, favorite_color: 'mauve' },
]
}
})
console.log(result)
```
## Multi search helper [multi-search-helper]
Added in `v7.8.0`
If you send search request at a high rate, this helper might be useful for you. It uses the multi search API under the hood to batch the requests and improve the overall performances of your application. The `result` exposes a `documents` property as well, which allows you to access directly the hits sources.
### Usage [_usage_4]
```js
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)) // or result.documents
.catch(err => console.error(err))
```
To create a new instance of the multi search (msearch) helper, you should access it as shown in the example above, the configuration options are:
| | |
| --- | --- |
| `operations` | How many search operations should be sent in a single msearch request.<br> *Default:* `5`<br><br>```js<br>const m = client.helpers.msearch({<br> operations: 10<br>})<br>```<br> |
| `flushInterval` | How much time (in milliseconds) the helper waits before flushing the operations from the last operation read.<br> *Default:* `500`<br><br>```js<br>const m = client.helpers.msearch({<br> flushInterval: 500<br>})<br>```<br> |
| `concurrency` | How many request is executed at the same time.<br> *Default:* `5`<br><br>```js<br>const m = client.helpers.msearch({<br> concurrency: 10<br>})<br>```<br> |
| `retries` | How many times an operation is retried before to resolve the request. An operation is retried only in case of a 429 error.<br> *Default:* Client max retries.<br><br>```js<br>const m = client.helpers.msearch({<br> retries: 3<br>})<br>```<br> |
| `wait` | How much time to wait before retries in milliseconds.<br> *Default:* 5000.<br><br>```js<br>const m = client.helpers.msearch({<br> wait: 3000<br>})<br>```<br> |
### Stopping the msearch helper [_stopping_the_msearch_helper]
If needed, you can stop an msearch processor at any time. The msearch helper returns a [thenable](https://promisesaplus.com/), which has an `stop` method.
If you are creating multiple msearch helpers instances and using them for a limitied period of time, remember to always use the `stop` method once you have finished using them, otherwise your application will start leaking memory.
The `stop` method accepts an optional error, that will be dispatched every subsequent search request.
::::{note}
The stop method stops the execution of the msearch processor, but if you are using a concurrency higher than one, the operations that are already running will not be stopped.
::::
```js
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())
```
## Search helper [search-helper]
Added in `v7.7.0`
A simple wrapper around the search API. Instead of returning the entire `result` object it returns only the search documents source. For improving the performances, this helper automatically adds `filter_path=hits.hits._source` to the query string.
```js
const documents = await client.helpers.search({
index: 'stackoverflow',
query: {
match: {
title: 'javascript'
}
}
})
for (const doc of documents) {
console.log(doc)
}
```
## Scroll search helper [scroll-search-helper]
Added in `v7.7.0`
This helpers offers a simple and intuitive way to use the scroll search API. Once called, it returns an [async iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) which can be used in conjuction with a for-await…of. It handles automatically the `429` error and uses the `maxRetries` option of the client.
```js
const scrollSearch = client.helpers.scrollSearch({
index: 'stackoverflow',
query: {
match: {
title: 'javascript'
}
}
})
for await (const result of scrollSearch) {
console.log(result)
}
```
### Clear a scroll search [_clear_a_scroll_search]
If needed, you can clear a scroll search by calling `result.clear()`:
```js
for await (const result of scrollSearch) {
if (condition) {
await result.clear()
}
}
```
### Quickly getting the documents [_quickly_getting_the_documents]
If you only need the documents from the result of a scroll search, you can access them via `result.documents`:
```js
for await (const result of scrollSearch) {
console.log(result.documents)
}
```
## Scroll documents helper [scroll-documents-helper]
Added in `v7.7.0`
It works in the same way as the scroll search helper, but it returns only the documents instead. Note, every loop cycle returns a single document, and you cant use the `clear` method. For improving the performances, this helper automatically adds `filter_path=hits.hits._source` to the query string.
```js
const scrollSearch = client.helpers.scrollDocuments({
index: 'stackoverflow',
query: {
match: {
title: 'javascript'
}
}
})
for await (const doc of scrollSearch) {
console.log(doc)
}
```
## ES|QL helper [esql-helper]
ES|QL queries can return their results in [several formats](docs-content://explore-analyze/query-filter/languages/esql-rest.md#esql-rest-format). The default JSON format returned by ES|QL queries contains arrays of values for each row, with column names and types returned separately:
### Usage [_usage_5]
#### `toRecords` [_torecords]
Added in `v8.14.0`
The default JSON format returned by ES|QL queries contains arrays of values for each row, with column names and types returned separately:
```json
{
"columns": [
{ "name": "@timestamp", "type": "date" },
{ "name": "client_ip", "type": "ip" },
{ "name": "event_duration", "type": "long" },
{ "name": "message", "type": "keyword" }
],
"values": [
[
"2023-10-23T12:15:03.360Z",
"172.21.2.162",
3450233,
"Connected to 10.1.0.3"
],
[
"2023-10-23T12:27:28.948Z",
"172.21.2.113",
2764889,
"Connected to 10.1.0.2"
]
]
}
```
In many cases, its preferable to operate on an array of objects, one object per row, rather than an array of arrays. The ES|QL `toRecords` helper converts row data into objects.
```js
await client.helpers
.esql({ query: 'FROM sample_data | LIMIT 2' })
.toRecords()
// =>
// {
// "columns": [
// { "name": "@timestamp", "type": "date" },
// { "name": "client_ip", "type": "ip" },
// { "name": "event_duration", "type": "long" },
// { "name": "message", "type": "keyword" }
// ],
// "records": [
// {
// "@timestamp": "2023-10-23T12:15:03.360Z",
// "client_ip": "172.21.2.162",
// "event_duration": 3450233,
// "message": "Connected to 10.1.0.3"
// },
// {
// "@timestamp": "2023-10-23T12:27:28.948Z",
// "client_ip": "172.21.2.113",
// "event_duration": 2764889,
// "message": "Connected to 10.1.0.2"
// },
// ]
// }
```
In TypeScript, you can declare the type that `toRecords` returns:
```ts
type EventLog = {
'@timestamp': string,
client_ip: string,
event_duration: number,
message: string,
}
const result = await client.helpers
.esql({ query: 'FROM sample_data | LIMIT 2' })
.toRecords<EventLog>()
```
#### `toArrowReader` [_toarrowreader]
Added in `v8.16.0`
ES|QL can return results in multiple binary formats, including [Apache Arrow](https://arrow.apache.org/)'s streaming format. Because it is a very efficient format to read, it can be valuable for performing high-performance in-memory analytics. And, because the response is streamed as batches of records, it can be used to produce aggregations and other calculations on larger-than-memory data sets.
`toArrowReader` returns a [`RecordBatchStreamReader`](https://arrow.apache.org/docs/js/classes/Arrow_dom.RecordBatchReader.md).
```ts
const reader = await client.helpers
.esql({ query: 'FROM sample_data' })
.toArrowReader()
// print each record as JSON
for (const recordBatch of reader) {
for (const record of recordBatch) {
console.log(record.toJSON())
}
}
```
#### `toArrowTable` [_toarrowtable]
Added in `v8.16.0`
If you would like to pull the entire data set in Arrow format but without streaming, you can use the `toArrowTable` helper to get a [Table](https://arrow.apache.org/docs/js/classes/Arrow_dom.Table.md) back instead.
```ts
const table = await client.helpers
.esql({ query: 'FROM sample_data' })
.toArrowTable()
console.log(table.toArray())
```

View File

@ -0,0 +1,121 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/client-testing.html
---
# Testing [client-testing]
Testing is one of the most important parts of developing an application. The client is very flexible when it comes to testing and is compatible with most testing frameworks (such as [`ava`](https://www.npmjs.com/package/ava), which is used in the examples below).
If you are using this client, you are most likely working with {{es}}, and one of the first issues you face is how to test your application. A perfectly valid solution is to use the real {{es}} instance for testing your application, but you would be doing an integration test, while you want a unit test. There are many ways to solve this problem, you could create the database with Docker, or use an in-memory compatible one, but if you are writing unit tests that can be easily parallelized this becomes quite uncomfortable. A different way of improving your testing experience while doing unit tests is to use a mock.
The client is designed to be easy to extend and adapt to your needs. Thanks to its internal architecture it allows you to change some specific components while keeping the rest of it working as usual. Each {{es}} official client is composed of the following components:
* `API layer`: every {{es}} API that you can call.
* `Transport`: a component that takes care of preparing a request before sending it and handling all the retry and sniffing strategies.
* `ConnectionPool`: {{es}} is a cluster and might have multiple nodes, the `ConnectionPool` takes care of them.
* `Serializer`: A class with all the serialization strategies, from the basic JSON to the new line delimited JSON.
* `Connection`: The actual HTTP library.
The best way to mock {{es}} with the official clients is to replace the `Connection` component since it has very few responsibilities and it does not interact with other internal components other than getting requests and returning responses.
## `@elastic/elasticsearch-mock` [_elasticelasticsearch_mock]
Writing each time a mock for your test can be annoying and error-prone, so we have built a simple yet powerful mocking library specifically designed for this client, and you can install it with the following command:
```sh
npm install @elastic/elasticsearch-mock --save-dev
```
With this library you can create custom mocks for any request you can send to {{es}}. It offers a simple and intuitive API and it mocks only the HTTP layer, leaving the rest of the client working as usual.
Before showing all of its features, and what you can do with it, lets see an example:
```js
const { Client } = require('@elastic/elasticsearch')
const Mock = require('@elastic/elasticsearch-mock')
const mock = new Mock()
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' },
Connection: mock.getConnection()
})
mock.add({
method: 'GET',
path: '/'
}, () => {
return { status: 'ok' }
})
client.info().then(console.log, console.log)
```
As you can see it works closely with the client itself, once you have created a new instance of the mock library you just need to call the mock.getConnection() method and pass its result to the Connection option of the client. From now on, every request is handled by the mock library, and the HTTP layer will never be touched. As a result, your test is significantly faster and you are able to easily parallelize them!
The library allows you to write both “strict” and “loose” mocks, which means that you can write a mock that handles a very specific request or be looser and handle a group of request, lets see this in action:
```js
mock.add({
method: 'POST',
path: '/indexName/_search'
}, () => {
return {
hits: {
total: { value: 1, relation: 'eq' },
hits: [{ _source: { baz: 'faz' } }]
}
}
})
mock.add({
method: 'POST',
path: '/indexName/_search',
body: { query: { match: { foo: 'bar' } } }
}, () => {
return {
hits: {
total: { value: 0, relation: 'eq' },
hits: []
}
}
})
```
In the example above, every search request gets the first response, while every search request that uses the query described in the second mock gets the second response.
You can also specify dynamic paths:
```js
mock.add({
method: 'GET',
path: '/:index/_count'
}, () => {
return { count: 42 }
})
client.count({ index: 'foo' }).then(console.log, console.log) // => { count: 42 }
client.count({ index: 'bar' }).then(console.log, console.log) // => { count: 42 }
```
And wildcards are supported as well.
Another very interesting use case is the ability to create a test that randomly fails to see how your code reacts to failures:
```js
mock.add({
method: 'GET',
path: '/:index/_count'
}, () => {
if (Math.random() > 0.8) {
return ResponseError({ body: {}, statusCode: 500 })
} else {
return { count: 42 }
}
})
```
We have seen how simple is mocking {{es}} and testing your application, you can find many more features and examples in the [module documentation](https://github.com/elastic/elasticsearch-js-mock).

View File

@ -0,0 +1,14 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/client-configuration.html
---
# Configuration [client-configuration]
The client is designed to be easily configured for your needs. In the following section, you can see the possible options that you can use to configure it.
- [Basic configuration](/reference/basic-config.md)
- [Advanced configuration](/reference/advanced-config.md)
- [Timeout best practices](/reference/timeout-best-practices.md)
- [Creating a child client](/reference/child.md)
- [Testing](/reference/client-testing.md)

View File

@ -0,0 +1,516 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/client-connecting.html
---
# Connecting [client-connecting]
This page contains the information you need to connect and use the Client with {{es}}.
## Authentication [authentication]
This document contains code snippets to show you how to connect to various {{es}} providers.
### Elastic Cloud [auth-ec]
If you are using [Elastic Cloud](https://www.elastic.co/cloud), the client offers an easy way to connect to it via the `cloud` option. You must pass the Cloud ID that you can find in the cloud console, then your username and password inside the `auth` option.
::::{note}
When connecting to Elastic Cloud, the client will automatically enable both request and response compression by default, since it yields significant throughput improvements. Moreover, the client will also set the tls option `secureProtocol` to `TLSv1_2_method` unless specified otherwise. You can still override this option by configuring them.
::::
::::{important}
Do not enable sniffing when using Elastic Cloud, since the nodes are behind a load balancer, Elastic Cloud will take care of everything for you. Take a look [here](https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how) to know more.
::::
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: {
id: '<cloud-id>'
},
auth: {
username: 'elastic',
password: 'changeme'
}
})
```
## Connecting to an Elastic Cloud Serverless instance [connect-serverless]
The Node.js client is built to support connecting to [Elastic Cloud Serverless](https://www.elastic.co/guide/en/serverless/current/intro.html). By setting the `serverMode` option to `"serverless"`, several default options will be modified to better suit the serverless environment.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: {
id: '<cloud-id>'
},
auth: {
username: 'elastic',
password: 'changeme'
},
serverMode: 'serverless'
})
```
## Connecting to a self-managed cluster [connect-self-managed-new]
By default {{es}} will start with security features like authentication and TLS enabled. To connect to the {{es}} cluster youll need to configure the Node.js {{es}} client to use HTTPS with the generated CA certificate in order to make requests successfully.
If youre just getting started with {{es}} we recommend reading the documentation on [configuring](docs-content://deploy-manage/deploy/self-managed/configure-elasticsearch.md) and [starting {{es}}](docs-content://deploy-manage/maintenance/start-stop-services/start-stop-elasticsearch.md) to ensure your cluster is running as expected.
When you start {{es}} for the first time youll see a distinct block like the one below in the output from {{es}} (you may have to scroll up if its been a while):
```sh
-> Elasticsearch security features have been automatically configured!
-> Authentication is enabled and cluster connections are encrypted.
-> Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
lhQpLELkjkrawaBoaz0Q
-> HTTP CA certificate SHA-256 fingerprint:
a52dd93511e8c6045e21f16654b77c9ee0f34aea26d9f40320b531c474676228
...
```
Depending on the circumstances there are two options for verifying the HTTPS connection, either verifying with the CA certificate itself or via the HTTP CA certificate fingerprint.
### TLS configuration [auth-tls]
The generated root CA certificate can be found in the `certs` directory in your {{es}} config location (`$ES_CONF_PATH/certs/http_ca.crt`). If youre running {{es}} in Docker there is [additional documentation for retrieving the CA certificate](docs-content://deploy-manage/deploy/self-managed/install-elasticsearch-with-docker.md).
Without any additional configuration you can specify `https://` node urls, and the certificates used to sign these requests will be verified. To turn off certificate verification, you must specify an `tls` object in the top level config and set `rejectUnauthorized: false`. The default `tls` values are the same that Node.jss [`tls.connect()`](https://nodejs.org/api/tls.md#tls_tls_connect_options_callback) uses.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
username: 'elastic',
password: 'changeme'
},
tls: {
ca: fs.readFileSync('./http_ca.crt'),
rejectUnauthorized: false
}
})
```
### CA fingerprint [auth-ca-fingerprint]
You can configure the client to only trust certificates that are signed by a specific CA certificate (CA certificate pinning) by providing a `caFingerprint` option. This will verify that the fingerprint of the CA certificate that has signed the certificate of the server matches the supplied value. You must configure a SHA256 digest.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://example.com'
auth: { ... },
// the fingerprint (SHA256) of the CA certificate that is used to sign
// the certificate that the Elasticsearch node presents for TLS.
caFingerprint: '20:0D:CA:FA:76:...',
tls: {
// might be required if it's a self-signed certificate
rejectUnauthorized: false
}
})
```
The certificate fingerprint can be calculated using `openssl x509` with the certificate file:
```sh
openssl x509 -fingerprint -sha256 -noout -in /path/to/http_ca.crt
```
If you dont have access to the generated CA file from {{es}} you can use the following script to output the root CA fingerprint of the {{es}} instance with `openssl s_client`:
```sh
# Replace the values of 'localhost' and '9200' to the
# corresponding host and port values for the cluster.
openssl s_client -connect localhost:9200 -servername localhost -showcerts </dev/null 2>/dev/null \
| openssl x509 -fingerprint -sha256 -noout -in /dev/stdin
```
The output of `openssl x509` will look something like this:
```sh
SHA256 Fingerprint=A5:2D:D9:35:11:E8:C6:04:5E:21:F1:66:54:B7:7C:9E:E0:F3:4A:EA:26:D9:F4:03:20:B5:31:C4:74:67:62:28
```
## Connecting without security enabled [connect-no-security]
::::{warning}
Running {{es}} without security enabled is not recommended.
::::
If your cluster is configured with [security explicitly disabled](elasticsearch://reference/elasticsearch/configuration-reference/security-settings.md) then you can connect via HTTP:
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'http://example.com'
})
```
## Authentication strategies [auth-strategies]
Following you can find all the supported authentication strategies.
### ApiKey authentication [auth-apikey]
You can use the [ApiKey](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-create-api-key) authentication by passing the `apiKey` parameter via the `auth` option. The `apiKey` parameter can be either a base64 encoded string or an object with the values that you can obtain from the [create api key endpoint](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-create-api-key).
::::{note}
If you provide both basic authentication credentials and the ApiKey configuration, the ApiKey takes precedence.
::::
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
apiKey: 'base64EncodedKey'
}
})
```
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
apiKey: {
id: 'foo',
api_key: 'bar'
}
}
})
```
### Bearer authentication [auth-bearer]
You can provide your credentials by passing the `bearer` token parameter via the `auth` option. Useful for [service account tokens](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-security-create-service-token). Be aware that it does not handle automatic token refresh.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
bearer: 'token'
}
})
```
### Basic authentication [auth-basic]
You can provide your credentials by passing the `username` and `password` parameters via the `auth` option.
::::{note}
If you provide both basic authentication credentials and the Api Key configuration, the Api Key will take precedence.
::::
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://localhost:9200',
auth: {
username: 'elastic',
password: 'changeme'
}
})
```
Otherwise, you can provide your credentials in the node(s) URL.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://username:password@localhost:9200'
})
```
## Usage [client-usage]
Using the client is straightforward, it supports all the public APIs of {{es}}, and every method exposes the same signature.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const result = await client.search({
index: 'my-index',
query: {
match: { hello: 'world' }
}
})
```
The returned value of every API call is the response body from {{es}}. If you need to access additonal metadata, such as the status code or headers, you must specify `meta: true` in the request options:
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const result = await client.search({
index: 'my-index',
query: {
match: { hello: 'world' }
}
}, { meta: true })
```
In this case, the result will be:
```ts
{
body: object | boolean
statusCode: number
headers: object
warnings: string[],
meta: object
}
```
::::{note}
The body is a boolean value when you use `HEAD` APIs.
::::
### Aborting a request [_aborting_a_request]
If needed, you can abort a running request by using the `AbortController` standard.
::::{warning}
If you abort a request, the request will fail with a `RequestAbortedError`.
::::
```js
const AbortController = require('node-abort-controller')
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' }
})
const abortController = new AbortController()
setImmediate(() => abortController.abort())
const result = await client.search({
index: 'my-index',
query: {
match: { hello: 'world' }
}
}, { signal: abortController.signal })
```
### Request specific options [_request_specific_options]
If needed you can pass request specific options in a second object:
```js
const result = await client.search({
index: 'my-index',
body: {
query: {
match: { hello: 'world' }
}
}
}, {
ignore: [404],
maxRetries: 3
})
```
The supported request specific options are:
| Option | Description |
| --- | ----------- |
| `ignore` | `number[]` - HTTP status codes which should not be considered errors for this request.<br>*Default:* `null` |
| `requestTimeout` | `number` or `string` - Max request timeout for the request in milliseconds. This overrides the client default, which is to not time out at all. See [Elasticsearch best practices for HTML clients](elasticsearch://reference/elasticsearch/configuration-reference/networking-settings.md#_http_client_configuration) for more info.<br>_Default:* No timeout |
| `retryOnTimeout` | `boolean` - Retry requests that have timed out.*Default:* `false` |
| `maxRetries` | `number` - Max number of retries for the request, it overrides the client default.<br>*Default:* `3` |
| `compression` | `string` or `boolean` - Enables body compression for the request.<br>*Options:* `false`, `'gzip'`<br>*Default:* `false` |
| `asStream` | `boolean` - Instead of getting the parsed body back, you get the raw Node.js stream of data.<br>*Default:* `false` |
| `headers` | `object` - Custom headers for the request.<br>*Default:* `null` |
|`querystring` | `object` - Custom querystring for the request.<br>*Default:* `null` |
| `id` | `any` - Custom request ID. *(overrides the top level request id generator)*<br>*Default:* `null` |
| `context` | `any` - Custom object per request. *(you can use it to pass data to the clients events)*<br>*Default:* `null` |
| `opaqueId` | `string` - Set the `X-Opaque-Id` HTTP header. See [X-Opaque-Id HTTP header](elasticsearch://reference/elasticsearch/rest-apis/api-conventions.md#x-opaque-id) *Default:* `null` |
| `maxResponseSize` | `number` - When configured, it verifies that the uncompressed response size is lower than the configured number, if its higher it will abort the request. It cannot be higher than buffer.constants.MAX_STRING_LENTGH<br>*Default:* `null` |
| `maxCompressedResponseSize` | `number` - When configured, it verifies that the compressed response size is lower than the configured number, if its higher it will abort the request. It cannot be higher than buffer.constants.MAX_LENTGH<br>*Default:* `null` |
| `signal` | `AbortSignal` - The AbortSignal instance to allow request abortion.<br>*Default:* `null` |
| `meta` | `boolean` - Rather than returning the body, return an object containing `body`, `statusCode`, `headers` and `meta` keys<br>*Default*: `false` |
| `redaction` | `object` - Options for redacting potentially sensitive data from error metadata. See [Redaction of potentially sensitive data](/reference/advanced-config.md#redaction). | `retryBackoff` |
## Using the Client in a Function-as-a-Service Environment [client-faas-env]
This section illustrates the 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, the global scope. This practice does not only improve performance but also enables background functionality as for example [sniffing](https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how). The following examples provide a skeleton for the best practices.
### GCP Cloud Functions [_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 [_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
}
```
### Azure Functions [_azure_functions]
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
// client initialisation
})
module.exports = async function (context, req) {
// use the client
}
```
Resources used to assess these recommendations:
* [GCP Cloud Functions: Tips & Tricks](https://cloud.google.com/functions/docs/bestpractices/tips#use_global_variables_to_reuse_objects_in_future_invocations)
* [Best practices for working with AWS Lambda functions](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.md)
* [Azure Functions Python developer guide](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=azurecli-linux%2Capplication-level#global-variables)
* [AWS Lambda: Comparing the effect of global scope](https://docs.aws.amazon.com/lambda/latest/operatorguide/global-scope.md)
## Connecting through a proxy [client-connect-proxy]
Added in `v7.10.0`
If you need to pass through an http(s) proxy for connecting to {{es}}, the client out of the box offers a handy configuration for helping you with it. Under the hood, it uses the [`hpagent`](https://github.com/delvedor/hpagent) module.
::::{important}
In versions 8.0+ of the client, the default `Connection` type is set to `UndiciConnection`, which does not support proxy configurations. To use a proxy, you will need to use the `HttpConnection` class from `@elastic/transport` instead.
::::
```js
import { HttpConnection } from '@elastic/transport'
const client = new Client({
node: 'http://localhost:9200',
proxy: 'http://localhost:8080',
Connection: HttpConnection,
})
```
Basic authentication is supported as well:
```js
const client = new Client({
node: 'http://localhost:9200',
proxy: 'http:user:pwd@//localhost:8080',
Connection: HttpConnection,
})
```
If you are connecting through a non-http(s) proxy, such as a `socks5` or `pac`, you can use the `agent` option to configure it.
```js
const SocksProxyAgent = require('socks-proxy-agent')
const client = new Client({
node: 'http://localhost:9200',
agent () {
return new SocksProxyAgent('socks://127.0.0.1:1080')
},
Connection: HttpConnection,
})
```
## Error handling [client-error-handling]
The client exposes a variety of error objects that you can use to enhance your error handling. You can find all the error objects inside the `errors` key in the client.
```js
const { errors } = require('@elastic/elasticsearch')
console.log(errors)
```
You can find the errors exported by the client in the table below.
| | | |
| --- | --- | --- |
| **Error** | **Description** | **Properties** |
| `ElasticsearchClientError` | Every error inherits from this class, it is the basic error generated by the client. | * `name` - `string`<br>* `message` - `string`<br> |
| `TimeoutError` | Generated when a request exceeds the `requestTimeout` option. | * `name` - `string`<br>* `message` - `string`<br>* `meta` - `object`, contains all the information about the request<br> |
| `ConnectionError` | Generated when an error occurs during the request, it can be a connection error or a malformed stream of data. | * `name` - `string`<br>* `message` - `string`<br>* `meta` - `object`, contains all the information about the request<br> |
| `RequestAbortedError` | Generated if the user calls the `request.abort()` method. | * `name` - `string`<br>* `message` - `string`<br>* `meta` - `object`, contains all the information about the request<br> |
| `NoLivingConnectionsError` | Given the configuration, the ConnectionPool was not able to find a usable Connection for this request. | * `name` - `string`<br>* `message` - `string`<br>* `meta` - `object`, contains all the information about the request<br> |
| `SerializationError` | Generated if the serialization fails. | * `name` - `string`<br>* `message` - `string`<br>* `data` - `object`, the object to serialize<br> |
| `DeserializationError` | Generated if the deserialization fails. | * `name` - `string`<br>* `message` - `string`<br>* `data` - `string`, the string to deserialize<br> |
| `ConfigurationError` | Generated if there is a malformed configuration or parameter. | * `name` - `string`<br>* `message` - `string`<br> |
| `ResponseError` | Generated when in case of a `4xx` or `5xx` response. | * `name` - `string`<br>* `message` - `string`<br>* `meta` - `object`, contains all the information about the request<br>* `body` - `object`, the response body<br>* `statusCode` - `object`, the response headers<br>* `headers` - `object`, the response status code<br> |
## Keep-alive connections [keep-alive]
By default, the client uses persistent, keep-alive connections to reduce the overhead of creating a new HTTP connection for each Elasticsearch request. If you are using the default `UndiciConnection` connection class, it maintains a pool of 256 connections with a keep-alive of 10 minutes. If you are using the legacy `HttpConnection` connection class, it maintains a pool of 256 connections with a keep-alive of 1 minute.
If you need to disable keep-alive connections, you can override the HTTP agent with your preferred [HTTP agent options](https://nodejs.org/api/http.md#http_new_agent_options):
```js
const client = new Client({
node: 'http://localhost:9200',
// the function takes as parameter the option
// object passed to the Connection constructor
agent: (opts) => new CustomAgent()
})
```
Or you can disable the HTTP agent entirely:
```js
const client = new Client({
node: 'http://localhost:9200',
// Disable agent and keep-alive
agent: false
})
```
## Closing a clients connections [close-connections]
If you would like to close all open connections being managed by an instance of the client, use the `close()` function:
```js
const client = new Client({
node: 'http://localhost:9200'
});
client.close();
```
## Automatic product check [product-check]
Since v7.14.0, the client performs a required product check before the first call. This pre-flight product check allows the client to establish the version of Elasticsearch that it is communicating with. The product check requires one additional HTTP request to be sent to the server as part of the request pipeline before the main API call is sent. In most cases, this will succeed during the very first API call that the client sends. Once the product check completes, no further product check HTTP requests are sent for subsequent API calls.

View File

@ -0,0 +1,38 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/examples.html
---
# Examples [examples]
Following you can find some examples on how to use the client.
* Use of the [asStream](/reference/as_stream_examples.md) parameter;
* Executing a [bulk](/reference/bulk_examples.md) request;
* Executing a [exists](/reference/exists_examples.md) request;
* Executing a [get](/reference/get_examples.md) request;
* Executing a [sql.query](/reference/sql_query_examples.md) request;
* Executing a [update](/reference/update_examples.md) request;
* Executing a [update by query](/reference/update_by_query_examples.md) request;
* Executing a [reindex](/reference/reindex_examples.md) request;
* Use of the [ignore](/reference/ignore_examples.md) parameter;
* Executing a [msearch](/reference/msearch_examples.md) request;
* How do I [scroll](/reference/scroll_examples.md)?
* Executing a [search](/reference/search_examples.md) request;
* I need [suggestions](/reference/suggest_examples.md);
* How to use the [transport.request](/reference/transport_request_examples.md) method;

View File

@ -1,12 +1,18 @@
[[exists_examples]]
=== Exists
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/exists_examples.html
---
# Exists [exists_examples]
Check that the document `/game-of-thrones/1` exists.
NOTE: Since this API uses the `HEAD` method, the body value will be boolean.
::::{note}
Since this API uses the `HEAD` method, the body value will be boolean.
::::
[source,js]
----
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -34,4 +40,5 @@ async function run () {
}
run().catch(console.log)
----
```

View File

@ -1,12 +1,13 @@
[[get_examples]]
=== Get
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/get_examples.html
---
The get API allows to get a typed JSON document from the index based on its id.
The following example gets a JSON document from an index called
`game-of-thrones`, under a type called `_doc`, with id valued `'1'`.
# Get [get_examples]
[source,js]
----
The get API allows to get a typed JSON document from the index based on its id. The following example gets a JSON document from an index called `game-of-thrones`, under a type called `_doc`, with id valued `'1'`.
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -34,4 +35,5 @@ async function run () {
}
run().catch(console.log)
----
```

View File

@ -0,0 +1,154 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/getting-started-js.html
- https://www.elastic.co/guide/en/serverless/current/elasticsearch-nodejs-client-getting-started.html
---
# Getting started [getting-started-js]
This page guides you through the installation process of the Node.js client, shows you how to instantiate the client, and how to perform basic Elasticsearch operations with it.
### Requirements [_requirements]
* [Node.js](https://nodejs.org/) version 14.x or newer
* [`npm`](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm), usually bundled with Node.js
### Installation [_installation]
To install the latest version of the client, run the following command:
```shell
npm install @elastic/elasticsearch
```
Refer to the [*Installation*](/reference/installation.md) page to learn more.
### Connecting [_connecting]
You can connect to the Elastic Cloud using an API key and the Elasticsearch endpoint.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://...', // Elasticsearch endpoint
auth: {
apiKey: { // API key ID and secret
id: 'foo',
api_key: 'bar',
}
}
})
```
Your Elasticsearch endpoint can be found on the **My deployment** page of your deployment:
:::{image} images/es-endpoint.jpg
:alt: Finding Elasticsearch endpoint
:::
You can generate an API key on the **Management** page under Security.
:::{image} images/create-api-key.png
:alt: Create API key
:::
For other connection options, refer to the [*Connecting*](/reference/connecting.md) section.
### Operations [_operations]
Time to use Elasticsearch! This section walks you through the basic, and most important, operations of Elasticsearch.
#### Creating an index [_creating_an_index]
This is how you create the `my_index` index:
```js
await client.indices.create({ index: 'my_index' })
```
#### Indexing documents [_indexing_documents]
This is a simple way of indexing a document:
```js
await client.index({
index: 'my_index',
id: 'my_document_id',
document: {
foo: 'foo',
bar: 'bar',
},
})
```
#### Getting documents [_getting_documents]
You can get documents by using the following code:
```js
await client.get({
index: 'my_index',
id: 'my_document_id',
})
```
#### Searching documents [_searching_documents]
This is how you can create a single match query with the client:
```js
await client.search({
query: {
match: {
foo: 'foo'
}
}
})
```
#### Updating documents [_updating_documents]
This is how you can update a document, for example to add a new field:
```js
await client.update({
index: 'my_index',
id: 'my_document_id',
doc: {
foo: 'bar',
new_field: 'new value'
}
})
```
#### Deleting documents [_deleting_documents]
```js
await client.delete({
index: 'my_index',
id: 'my_document_id',
})
```
#### Deleting an index [_deleting_an_index]
```js
await client.indices.delete({ index: 'my_index' })
```
## Further reading [_further_reading]
* Use [*Client helpers*](/reference/client-helpers.md) for a more comfortable experience with the APIs.
* For an elaborate example of how to ingest data into Elastic Cloud, refer to [this page](docs-content://manage-data/ingest/ingesting-data-from-applications/ingest-data-with-nodejs-on-elasticsearch-service.md).

View File

@ -1,10 +1,13 @@
[[ignore_examples]]
=== Ignore
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/ignore_examples.html
---
# Ignore [ignore_examples]
HTTP status codes which should not be considered errors for this request.
[source,js]
----
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -62,4 +65,5 @@ async function run () {
}
run().catch(console.log)
----
```

View File

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 79 KiB

View File

Before

Width:  |  Height:  |  Size: 361 KiB

After

Width:  |  Height:  |  Size: 361 KiB

View File

@ -1,12 +1,15 @@
[[introduction]]
== Introduction
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/introduction.html
---
This is the official Node.js client for {es}. This page gives a quick overview
about the features of the client.
# JavaScript [introduction]
This is the official Node.js client for {{es}}. This page gives a quick overview about the features of the client.
[discrete]
=== Features
## Features [_features]
* One-to-one mapping with REST API.
* Generalized, pluggable architecture.
@ -17,45 +20,35 @@ about the features of the client.
* TypeScript support out of the box.
[discrete]
==== Install multiple versions
### Install multiple versions [_install_multiple_versions]
If you are using multiple versions of {es}, you need to use multiple versions of
the client as well. In the past, installing multiple versions of the same
package was not possible, but with `npm v6.9`, you can do it via aliasing.
If you are using multiple versions of {{es}}, you need to use multiple versions of the client as well. In the past, installing multiple versions of the same package was not possible, but with `npm v6.9`, you can do it via aliasing.
To install different version of the client, run the following command:
[source,sh]
----
```sh
npm install <alias>@npm:@elastic/elasticsearch@<version>
----
```
For example, if you need to install `7.x` and `6.x`, run the following commands:
[source,sh]
----
```sh
npm install es6@npm:@elastic/elasticsearch@6
npm install es7@npm:@elastic/elasticsearch@7
----
```
Your `package.json` will look similar to the following example:
[source,json]
----
```json
"dependencies": {
"es6": "npm:@elastic/elasticsearch@^6.7.0",
"es7": "npm:@elastic/elasticsearch@^7.0.0"
}
----
```
Require the packages from your code by using the alias you have defined.
[source,js]
----
```js
const { Client: Client6 } = require('es6')
const { Client: Client7 } = require('es7')
@ -70,15 +63,16 @@ const client7 = new Client7({
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 {{es}} (the one that lives in the {{es}} main branch), use the following command:
Finally, if you want to install the client for the next version of {es} (the one
that lives in the {es} main branch), use the following command:
[source,sh]
----
```sh
npm install esmain@github:elastic/elasticsearch-js
----
WARNING: This command installs the main branch of the client which is not
considered stable.
```
::::{warning}
This command installs the main branch of the client which is not considered stable.
::::

View File

@ -0,0 +1,65 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/installation.html
---
# Installation [installation]
This page guides you through the installation process of the client.
To install the latest version of the client, run the following command:
```sh
npm install @elastic/elasticsearch
```
To install a specific major version of the client, run the following command:
```sh
npm install @elastic/elasticsearch@<major>
```
To learn more about the supported major versions, please refer to the [Compatibility matrix](#js-compatibility-matrix).
## Node.js support [nodejs-support]
::::{note}
The minimum supported version of Node.js is `v18`.
::::
The client versioning follows the {{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](https://nodejs.org/en/about/releases/) 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) |
## Compatibility matrix [js-compatibility-matrix]
Language clients are forward compatible; meaning that clients support communicating with greater or equal minor versions of {{es}} without breaking. It does not mean that the client automatically supports new features of newer {{es}} versions; it is only possible after a release of a new client version. For example, a 8.12 client version wont automatically support the new features of the 8.13 version of {{es}}, the 8.13 client version is required for that. {{es}} language clients are only backwards compatible with default distributions and without guarantees made.
| {{es}} Version | Client Version | Supported |
| --- | --- | --- |
| `8.x` | `8.x` | `8.x` |
| `7.x` | `7.x` | `7.17` |
| `6.x` | `6.x` | |
| `5.x` | `5.x` | |
### Browser [_browser]
::::{warning}
There is no official support for the browser environment. It exposes your {{es}} instance to everyone, which could lead to security issues. We recommend you to write a lightweight proxy that uses this client instead, you can see a proxy example [here](https://github.com/elastic/elasticsearch-js/tree/master/docs/examples/proxy).
::::

View File

@ -0,0 +1,16 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/integrations.html
---
# Integrations [integrations]
The Client offers the following integration options for you:
* [Observability](/reference/observability.md)
* [Transport](/reference/transport.md)
* [TypeScript support](/reference/typescript.md)

View File

@ -1,11 +1,13 @@
[[msearch_examples]]
=== MSearch
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/msearch_examples.html
---
The multi search API allows to execute several search requests within the same
API.
# MSearch [msearch_examples]
[source,js]
----
The multi search API allows to execute several search requests within the same API.
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -57,4 +59,5 @@ async function run () {
}
run().catch(console.log)
----
```

View File

@ -1,64 +1,54 @@
[[observability]]
=== Observability
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/observability.html
---
# Observability [observability]
To observe and measure Elasticsearch client usage, several client features are provided.
First, as of 8.15.0, the client provides native support for OpenTelemetry, which allows you to send client usage data to any endpoint that supports OpenTelemetry without having to make any changes to your JavaScript codebase.
Also, rather than providing a default logger, the client offers an event
emitter interface to hook into internal events, such as `request` and
`response`, allowing you to log the events you care about, or otherwise react
to client usage however you might need.
Also, rather than providing a default logger, the client offers an event emitter interface to hook into internal events, such as `request` and `response`, allowing you to log the events you care about, or otherwise react to client usage however you might need.
Correlating events can be hard, especially if your applications have a large codebase with many events happening at the same time. To help you with this, the client provides a correlation ID system, and other
features.
Correlating events can be hard, especially if your applications have a large codebase with many events happening at the same time. To help you with this, the client provides a correlation ID system, and other features.
All of these observability features are documented below.
[discrete]
==== OpenTelemetry
The client supports OpenTelemetry's https://opentelemetry.io/docs/zero-code/js/[zero-code
instrumentation] to enable tracking each client request as an
https://opentelemetry.io/docs/concepts/signals/traces/#spans[OpenTelemetry span]. These spans
follow all of the https://opentelemetry.io/docs/specs/semconv/database/elasticsearch/[semantic
OpenTelemetry conventions for Elasticsearch] except for `db.query.text`.
## OpenTelemetry [_opentelemetry]
To start sending Elasticsearch trace data to your OpenTelemetry endpoint, follow
https://opentelemetry.io/docs/zero-code/js/[OpenTelemetry's zero-code instrumentation guide],
or the following steps:
The client supports OpenTelemetrys [zero-code instrumentation](https://opentelemetry.io/docs/zero-code/js/) to enable tracking each client request as an [OpenTelemetry span](https://opentelemetry.io/docs/concepts/signals/traces/#spans). These spans follow all of the [semantic OpenTelemetry conventions for Elasticsearch](https://opentelemetry.io/docs/specs/semconv/database/elasticsearch/) except for `db.query.text`.
To start sending Elasticsearch trace data to your OpenTelemetry endpoint, follow [OpenTelemetrys zero-code instrumentation guide](https://opentelemetry.io/docs/zero-code/js/), or the following steps:
1. Install `@opentelemetry/api` and `@opentelemetry/auto-instrumentations-node` as Node.js dependencies
2. Export the following environment variables with the appropriate values:
- `OTEL_EXPORTER_OTLP_ENDPOINT`
- `OTEL_EXPORTER_OTLP_HEADERS`
- `OTEL_RESOURCE_ATTRIBUTES`
- `OTEL_SERVICE_NAME`
* `OTEL_EXPORTER_OTLP_ENDPOINT`
* `OTEL_EXPORTER_OTLP_HEADERS`
* `OTEL_RESOURCE_ATTRIBUTES`
* `OTEL_SERVICE_NAME`
3. `require` the Node.js auto-instrumentation library at startup:
[source,bash]
----
```
node --require '@opentelemetry/auto-instrumentations-node/register' index.js
----
```
[discrete]
==== Events
The client is an event emitter. This means that you can listen for its events to
add additional logic to your code, without needing to change the client's internals
or how you use the client. You can find the events' names by accessing the `events` key
of the client:
## Events [_events]
[source,js]
----
The client is an event emitter. This means that you can listen for its events to add additional logic to your code, without needing to change the clients internals or how you use the client. You can find the events' names by accessing the `events` key of the client:
```js
const { events } = require('@elastic/elasticsearch')
console.log(events)
----
```
The event emitter functionality can be useful if you want to log every request,
response or error that is created by the client:
The event emitter functionality can be useful if you want to log every request, response or error that is created by the client:
[source,js]
----
```js
const logger = require('my-logger')()
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
@ -73,72 +63,22 @@ client.diagnostic.on('response', (err, result) => {
logger.info(result)
}
})
----
```
The client emits the following events:
[cols=2*]
|===
|`serialization`
a|Emitted before starting serialization and compression. If you want to measure this phase duration, you should measure the time elapsed between this event and `request`.
[source,js]
----
client.diagnostic.on('serialization', (err, result) => {
console.log(err, result)
})
----
|`request`
a|Emitted before sending the actual request to {es} _(emitted multiple times in case of retries)_.
[source,js]
----
client.diagnostic.on('request', (err, result) => {
console.log(err, result)
})
----
| | |
| --- | --- |
| `serialization` | Emitted before starting serialization and compression. If you want to measure this phase duration, you should measure the time elapsed between this event and `request`.<br><br>```js<br>client.diagnostic.on('serialization', (err, result) => {<br> console.log(err, result)<br>})<br>```<br> |
| `request` | Emitted before sending the actual request to {{es}} *(emitted multiple times in case of retries)*.<br><br>```js<br>client.diagnostic.on('request', (err, result) => {<br> console.log(err, result)<br>})<br>```<br> |
| `deserialization` | Emitted before starting deserialization and decompression. If you want to measure this phase duration, you should measure the time elapsed between this event and `response`. *(This event might not be emitted in certain situations)*.<br><br>```js<br>client.diagnostic.on('deserialization', (err, result) => {<br> console.log(err, result)<br>})<br>```<br> |
| `response` | Emitted once {{es}} response has been received and parsed.<br><br>```js<br>client.diagnostic.on('response', (err, result) => {<br> console.log(err, result)<br>})<br>```<br> |
| `sniff` | Emitted when the client ends a sniffing request.<br><br>```js<br>client.diagnostic.on('sniff', (err, result) => {<br> console.log(err, result)<br>})<br>```<br> |
| `resurrect` | Emitted if the client is able to resurrect a dead node.<br><br>```js<br>client.diagnostic.on('resurrect', (err, result) => {<br> console.log(err, result)<br>})<br>```<br> |
|`deserialization`
a|Emitted before starting deserialization and decompression. If you want to measure this phase duration, you should measure the time elapsed between this event and `response`. _(This event might not be emitted in certain situations)_.
[source,js]
----
client.diagnostic.on('deserialization', (err, result) => {
console.log(err, result)
})
----
The values of `result` in `serialization`, `request`, `deserialization`, `response` and `sniff` are:
|`response`
a|Emitted once {es} response has been received and parsed.
[source,js]
----
client.diagnostic.on('response', (err, result) => {
console.log(err, result)
})
----
|`sniff`
a|Emitted when the client ends a sniffing request.
[source,js]
----
client.diagnostic.on('sniff', (err, result) => {
console.log(err, result)
})
----
|`resurrect`
a|Emitted if the client is able to resurrect a dead node.
[source,js]
----
client.diagnostic.on('resurrect', (err, result) => {
console.log(err, result)
})
----
|===
The values of `result` in `serialization`, `request`, `deserialization`,
`response` and `sniff` are:
[source,ts]
----
```ts
body: any;
statusCode: number | null;
headers: anyObject | null;
@ -159,12 +99,11 @@ meta: {
reason: string;
};
};
----
```
While the `result` value in `resurrect` is:
[source,ts]
----
```ts
strategy: string;
isAlive: boolean;
connection: Connection;
@ -172,19 +111,14 @@ name: string;
request: {
id: any;
};
----
```
[discrete]
===== Events order
The event order is described in the following graph, in some edge cases, the
order is not guaranteed.
You can find in
https://github.com/elastic/elasticsearch-js/blob/main/test/acceptance/events-order.test.js[`test/acceptance/events-order.test.js`]
how the order changes based on the situation.
### Events order [_events_order]
[source]
----
The event order is described in the following graph, in some edge cases, the order is not guaranteed. You can find in [`test/acceptance/events-order.test.js`](https://github.com/elastic/elasticsearch-js/blob/main/test/acceptance/events-order.test.js) how the order changes based on the situation.
```
serialization
│ (serialization and compression happens between those two events)
@ -198,17 +132,14 @@ serialization
│ (deserialization and decompression happens between those two events)
└─▶ response
----
```
[discrete]
==== Correlation ID
Correlating events can be hard, especially if there are many events at the same
time. The client offers you an automatic (and configurable) system to help you
handle this problem.
## Correlation ID [_correlation_id]
[source,js]
----
Correlating events can be hard, especially if there are many events at the same time. The client offers you an automatic (and configurable) system to help you handle this problem.
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
@ -233,13 +164,11 @@ client.search({
index: 'my-index',
query: { match_all: {} }
}).then(console.log, console.log)
----
```
By default the ID is an incremental integer, but you can configure it with the
`generateRequestId` option:
By default the ID is an incremental integer, but you can configure it with the `generateRequestId` option:
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
@ -251,30 +180,25 @@ const client = new Client({
return 'id'
}
})
----
```
You can also specify a custom ID per request:
[source,js]
----
```js
client.search({
index: 'my-index',
query: { match_all: {} }
}, {
id: 'custom-id'
}).then(console.log, console.log)
----
```
[discrete]
==== Context object
## Context object [_context_object]
Sometimes, you might need to make some custom data available in your events, you
can do that via the `context` option of a request:
Sometimes, you might need to make some custom data available in your events, you can do that via the `context` option of a request:
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
@ -303,14 +227,11 @@ client.search({
}, {
context: { winter: 'is coming' }
}).then(console.log, console.log)
----
```
The context object can also be configured as a global option in the client
configuration. If you provide both, the two context objects will be shallow
merged, and the API level object will take precedence.
The context object can also be configured as a global option in the client configuration. If you provide both, the two context objects will be shallow merged, and the API level object will take precedence.
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
@ -340,19 +261,14 @@ client.search({
}, {
context: { winter: 'has come' }
}).then(console.log, console.log)
----
```
[discrete]
==== Client name
## Client name [_client_name]
If you are using multiple instances of the client or if you are using multiple
child clients _(which is the recommended way to have multiple instances of the
client)_, you might need to recognize which client you are using. The `name`
options help you in this regard.
If you are using multiple instances of the client or if you are using multiple child clients *(which is the recommended way to have multiple instances of the client)*, you might need to recognize which client you are using. The `name` options help you in this regard.
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
@ -391,25 +307,16 @@ child.search({
index: 'my-index',
query: { match_all: {} }
}).then(console.log, console.log)
----
```
[discrete]
==== X-Opaque-Id support
## X-Opaque-Id support [_x_opaque_id_support]
To improve observability, the client offers an easy way to configure the
`X-Opaque-Id` header. If you set the `X-Opaque-Id` in a specific request, this
allows you to discover this identifier in the
https://www.elastic.co/guide/en/elasticsearch/reference/current/logging.html#deprecation-logging[deprecation logs],
helps you with https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules-slowlog.html#_identifying_search_slow_log_origin[identifying search slow log origin]
as well as https://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html#_identifying_running_tasks[identifying running tasks].
To improve observability, the client offers an easy way to configure the `X-Opaque-Id` header. If you set the `X-Opaque-Id` in a specific request, this allows you to discover this identifier in the [deprecation logs](docs-content://deploy-manage/monitor/logging-configuration/update-elasticsearch-logging-levels.md#deprecation-logging), helps you with [identifying search slow log origin](elasticsearch://reference/elasticsearch/index-settings/slow-log.md) as well as [identifying running tasks](https://www.elastic.co/docs/api/doc/elasticsearch/group/endpoint-tasks).
The `X-Opaque-Id` should be configured in each request, for doing that you can
use the `opaqueId` option, as you can see in the following example. The
resulting header will be `{ 'X-Opaque-Id': 'my-search' }`.
The `X-Opaque-Id` should be configured in each request, for doing that you can use the `opaqueId` option, as you can see in the following example. The resulting header will be `{ 'X-Opaque-Id': 'my-search' }`.
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
@ -422,16 +329,11 @@ client.search({
}, {
opaqueId: 'my-search'
}).then(console.log, console.log)
----
```
Sometimes it may be useful to prefix all the `X-Opaque-Id` headers with a
specific string, in case you need to identify a specific client or server. For
doing this, the client offers a top-level configuration option:
`opaqueIdPrefix`. In the following example, the resulting header will be
`{ 'X-Opaque-Id': 'proxy-client::my-search' }`.
Sometimes it may be useful to prefix all the `X-Opaque-Id` headers with a specific string, in case you need to identify a specific client or server. For doing this, the client offers a top-level configuration option: `opaqueIdPrefix`. In the following example, the resulting header will be `{ 'X-Opaque-Id': 'proxy-client::my-search' }`.
[source,js]
----
```js
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
cloud: { id: '<cloud-id>' },
@ -445,5 +347,5 @@ client.search({
}, {
opaqueId: 'my-search'
}).then(console.log, console.log)
----
```

View File

@ -1,17 +1,15 @@
[[reindex_examples]]
=== Reindex
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/reindex_examples.html
---
The `reindex` API extracts the document source from the source index and indexes
the documents into the destination index. You can copy all documents to the
destination index, reindex a subset of the documents or update the source before
to reindex it.
# Reindex [reindex_examples]
In the following example we have a `game-of-thrones` index which contains
different quotes of various characters, we want to create a new index only for
the house Stark and remove the `house` field from the document source.
The `reindex` API extracts the document source from the source index and indexes the documents into the destination index. You can copy all documents to the destination index, reindex a subset of the documents or update the source before to reindex it.
[source,js]
----
In the following example we have a `game-of-thrones` index which contains different quotes of various characters, we want to create a new index only for the house Stark and remove the `house` field from the document source.
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -76,4 +74,5 @@ async function run () {
}
run().catch(console.log)
----
```

View File

@ -1,28 +1,27 @@
[[scroll_examples]]
=== Scroll
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/scroll_examples.html
---
While a search request returns a single “page” of results, the scroll API can be
used to retrieve large numbers of results (or even all results) from a single
search request, in much the same way as you would use a cursor on a traditional
database.
# Scroll [scroll_examples]
Scrolling is not intended for real time user requests, but rather for processing
large amounts of data, for example in order to reindex the contents of one index
into a new index with a different configuration.
While a search request returns a single “page” of results, the scroll API can be used to retrieve large numbers of results (or even all results) from a single search request, in much the same way as you would use a cursor on a traditional database.
NOTE: The results that are returned from a scroll request reflect the state of
the index at the time that the initial search request was made, like a snapshot
in time. Subsequent changes to documents (index, update or delete) will only
affect later search requests.
Scrolling is not intended for real time user requests, but rather for processing large amounts of data, for example in order to reindex the contents of one index into a new index with a different configuration.
In order to use scrolling, the initial search request should specify the scroll
parameter in the query string, which tells {es} how long it should keep the
“search context” alive.
::::{note}
The results that are returned from a scroll request reflect the state of the index at the time that the initial search request was made, like a snapshot in time. Subsequent changes to documents (index, update or delete) will only affect later search requests.
::::
NOTE: Did you know that we provide an helper for sending scroll requests? You can find it <<scroll-search-helper,here>>.
[source,js]
----
In order to use scrolling, the initial search request should specify the scroll parameter in the query string, which tells {{es}} how long it should keep the “search context” alive.
::::{note}
Did you know that we provide an helper for sending scroll requests? You can find it [here](/reference/client-helpers.md#scroll-search-helper).
::::
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -111,13 +110,11 @@ async function run () {
}
run().catch(console.log)
----
```
Another cool usage of the `scroll` API can be done with Node.js ≥ 10, by using
async iteration!
Another cool usage of the `scroll` API can be done with Node.js ≥ 10, by using async iteration!
[source,js]
----
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -192,4 +189,5 @@ async function run () {
}
run().catch(console.log)
----
```

View File

@ -1,14 +1,13 @@
[[search_examples]]
=== Search
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/search_examples.html
---
The `search` API allows you to execute a search query and get back search hits
that match the query. The query can either be provided using a simple
https://www.elastic.co/guide/en/elasticsearch/reference/6.6/search-uri-request.html[query string as a parameter],
or using a
https://www.elastic.co/guide/en/elasticsearch/reference/6.6/search-request-body.html[request body].
# Search [search_examples]
[source,js]
----
The `search` API allows you to execute a search query and get back search hits that match the query. The query can either be provided using a simple [query string as a parameter](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-search), or using a [request body](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html).
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -61,4 +60,5 @@ async function run () {
}
run().catch(console.log)
----
```

View File

@ -1,19 +1,15 @@
[[sql_query_examples]]
=== SQL
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/sql_query_examples.html
---
{es} SQL is an X-Pack component that allows SQL-like queries to be executed in
real-time against {es}. Whether using the REST interface, command-line or JDBC,
any client can use SQL to search and aggregate data natively inside {es}. One
can think of {es} SQL as a translator, one that understands both SQL and {es}
and makes it easy to read and process data in real-time, at scale by leveraging
{es} capabilities.
# SQL [sql_query_examples]
In the following example we will search all the documents that has the field
`house` equals to `stark`, log the result with the tabular view and then
manipulate the result to obtain an object easy to navigate.
{{es}} SQL is an X-Pack component that allows SQL-like queries to be executed in real-time against {{es}}. Whether using the REST interface, command-line or JDBC, any client can use SQL to search and aggregate data natively inside {{es}}. One can think of {{es}} SQL as a translator, one that understands both SQL and {{es}} and makes it easy to read and process data in real-time, at scale by leveraging {{es}} capabilities.
[source,js]
----
In the following example we will search all the documents that has the field `house` equals to `stark`, log the result with the tabular view and then manipulate the result to obtain an object easy to navigate.
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -69,4 +65,5 @@ async function run () {
}
run().catch(console.log)
----
```

View File

@ -1,14 +1,15 @@
[[suggest_examples]]
=== Suggest
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/suggest_examples.html
---
The suggest feature suggests similar looking terms based on a provided text by
using a suggester. _Parts of the suggest feature are still under development._
# Suggest [suggest_examples]
The suggest request part is defined alongside the query part in a `search`
request. If the query part is left out, only suggestions are returned.
The suggest feature suggests similar looking terms based on a provided text by using a suggester. *Parts of the suggest feature are still under development.*
[source,js]
----
The suggest request part is defined alongside the query part in a `search` request. If the query part is left out, only suggestions are returned.
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -63,5 +64,5 @@ async function run () {
}
run().catch(console.log)
```
----

View File

@ -0,0 +1,13 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/timeout-best-practices.html
---
# Timeout best practices [timeout-best-practices]
Starting in 9.0.0, this client is configured to not time out any HTTP request by default. {{es}} will always eventually respond to any request, even if it takes several minutes. Reissuing a request that it has not responded to yet can cause performance side effects. See the [official {{es}} recommendations for HTTP clients](elasticsearch://reference/elasticsearch/configuration-reference/networking-settings.md#_http_client_configuration) for more information.
Prior to 9.0, this client was configured by default to operate like many HTTP client libraries do, by using a relatively short (30 second) timeout on all requests sent to {{es}}, raising a `TimeoutError` when that time period elapsed without receiving a response.
If you need to set timeouts on Elasticsearch requests, setting the `requestTimeout` value to a millisecond value will cause this client to operate as it did prior to 9.0.

35
docs/reference/toc.yml Normal file
View File

@ -0,0 +1,35 @@
toc:
- file: index.md
- file: getting-started.md
- file: installation.md
- file: connecting.md
- file: configuration.md
children:
- file: basic-config.md
- file: advanced-config.md
- file: child.md
- file: client-testing.md
- file: integrations.md
children:
- file: observability.md
- file: transport.md
- file: typescript.md
- file: api-reference.md
- file: examples.md
children:
- file: as_stream_examples.md
- file: bulk_examples.md
- file: exists_examples.md
- file: get_examples.md
- file: ignore_examples.md
- file: msearch_examples.md
- file: scroll_examples.md
- file: search_examples.md
- file: suggest_examples.md
- file: transport_request_examples.md
- file: sql_query_examples.md
- file: update_examples.md
- file: update_by_query_examples.md
- file: reindex_examples.md
- file: client-helpers.md
- file: timeout-best-practices.md

View File

@ -0,0 +1,53 @@
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/transport.html
---
# Transport [transport]
This class is responsible for performing the request to {{es}} and handling errors, it also handles sniffing.
```js
const { Client } = require('@elastic/elasticsearch')
const { Transport } = require('@elastic/transport')
class MyTransport extends Transport {
request (params, options, callback) {
// your code
}
}
const client = new Client({
Transport: MyTransport
})
```
Sometimes you need to inject a small snippet of your code and then continue to use the usual client code. In such cases, call `super.method`:
```js
class MyTransport extends Transport {
request (params, options, callback) {
// your code
return super.request(params, options, callback)
}
}
```
## Supported content types [_supported_content_types]
Depending on the `content-type` of the response, the transport will return the body as different types:
| Content-Type | JavaScript type |
| --- | --- |
| `application/json` | `object` |
| `text/plain` | `string` |
| `application/vnd.elasticsearch+json` | `object` |
| `application/vnd.mapbox-vector-tile` | `Buffer` |
| `application/vnd.apache.arrow.stream` | `Buffer` |
| `application/vnd.elasticsearch+arrow+stream` | `Buffer` |
| `application/smile` | `Buffer` |
| `application/vnd.elasticsearch+smile` | `Buffer` |
| `application/cbor` | `Buffer` |
| `application/vnd.elasticsearch+cbor` | `Buffer` |

View File

@ -1,22 +1,23 @@
[[transport_request_examples]]
=== transport.request
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/transport_request_examples.html
---
It can happen that you need to communicate with {es} by using an API that is not
supported by the client, to mitigate this issue you can directly call
`client.transport.request`, which is the internal utility that the client uses
to communicate with {es} when you use an API method.
# transport.request [transport_request_examples]
NOTE: When using the `transport.request` method you must provide all the
parameters needed to perform an HTTP call, such as `method`, `path`,
`querystring`, and `body`.
It can happen that you need to communicate with {{es}} by using an API that is not supported by the client, to mitigate this issue you can directly call `client.transport.request`, which is the internal utility that the client uses to communicate with {{es}} when you use an API method.
::::{note}
When using the `transport.request` method you must provide all the parameters needed to perform an HTTP call, such as `method`, `path`, `querystring`, and `body`.
::::
TIP: If you find yourself use this method too often, take in consideration the
use of `client.extend`, which will make your code look cleaner and easier to
maintain.
::::{tip}
If you find yourself use this method too often, take in consideration the use of `client.extend`, which will make your code look cleaner and easier to maintain.
::::
[source,js]
----
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -71,4 +72,5 @@ async function run () {
}
run().catch(console.log)
----
```

View File

@ -1,22 +1,23 @@
[[typescript]]
=== TypeScript support
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/typescript.html
---
The client offers a first-class support for TypeScript, shipping a complete set
of type definitions of Elasticsearch's API surface.
# TypeScript support [typescript]
The types are not 100% complete yet. Some APIs are missing (the newest ones, e.g. EQL),
and others may contain some errors, but we are continuously pushing fixes & improvements.
Contribute type fixes and improvements to https://github.com/elastic/elasticsearch-specification[elasticsearch-specification github repository].
The client offers a first-class support for TypeScript, shipping a complete set of type definitions of Elasticsearchs API surface.
NOTE: The client is developed against the https://www.npmjs.com/package/typescript?activeTab=versions[latest]
version of TypeScript. Furthermore, unless you have set `skipLibCheck` to `true`,
you should configure `esModuleInterop` to `true`.
The types are not 100% complete yet. Some APIs are missing (the newest ones, e.g. EQL), and others may contain some errors, but we are continuously pushing fixes & improvements. Contribute type fixes and improvements to [elasticsearch-specification github repository](https://github.com/elastic/elasticsearch-specification).
[discrete]
==== Example
::::{note}
The client is developed against the [latest](https://www.npmjs.com/package/typescript?activeTab=versions) version of TypeScript. Furthermore, unless you have set `skipLibCheck` to `true`, you should configure `esModuleInterop` to `true`.
::::
[source,ts]
----
## Example [_example]
```ts
import { Client } from '@elastic/elasticsearch'
const client = new Client({
@ -71,21 +72,20 @@ async function run () {
}
run().catch(console.log)
----
```
[discrete]
==== Request & Response types
## Request & Response types [_request_response_types]
You can import the full TypeScript requests & responses definitions as it follows:
[source,ts]
----
```ts
import { estypes } from '@elastic/elasticsearch'
----
```
If you need the legacy definitions with the body, you can do the following:
[source,ts]
----
```ts
import { estypesWithBody } from '@elastic/elasticsearch'
----
```

View File

@ -1,12 +1,13 @@
[[update_by_query_examples]]
=== Update By Query
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/update_by_query_examples.html
---
The simplest usage of _update_by_query just performs an update on every document
in the index without changing the source. This is useful to pick up a new
property or some other online mapping change.
# Update By Query [update_by_query_examples]
[source,js]
----
The simplest usage of _update_by_query just performs an update on every document in the index without changing the source. This is useful to pick up a new property or some other online mapping change.
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -56,5 +57,5 @@ async function run () {
}
run().catch(console.log)
```
----

View File

@ -1,12 +1,13 @@
[[update_examples]]
=== Update
---
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/update_examples.html
---
The update API allows updates of a specific document using the given script. In
the following example, we will index a document that also tracks how many times
a character has said the given quote, and then we will update the `times` field.
# Update [update_examples]
[source,js]
----
The update API allows updates of a specific document using the given script. In the following example, we will index a document that also tracks how many times a character has said the given quote, and then we will update the `times` field.
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -47,13 +48,11 @@ async function run () {
}
run().catch(console.log)
----
```
With the update API, you can also run a partial update of a document.
[source,js]
----
```js
'use strict'
const { Client } = require('@elastic/elasticsearch')
@ -90,6 +89,5 @@ async function run () {
}
run().catch(console.log)
```
----

View File

@ -0,0 +1,55 @@
---
navigation_title: "Breaking changes"
---
# Elasticsearch JavaScript Client breaking changes [elasticsearch-javascript-client-breaking-changes]
Breaking changes can impact your Elastic applications, potentially disrupting normal operations. Before you upgrade, carefully review the Elasticsearch JavaScript Client breaking changes and take the necessary steps to mitigate any issues. To learn how to upgrade, check [Upgrade](docs-content://deploy-manage/upgrade.md).
% ## Next version [elasticsearch-javascript-client-versionnext-breaking-changes]
% ::::{dropdown} Title of breaking change
% Description of the breaking change.
% For more information, check [PR #](PR link).
% **Impact**<br> Impact of the breaking change.
% **Action**<br> Steps for mitigating deprecation impact.
% ::::
## 9.0.0 [elasticsearch-javascript-client-900-breaking-changes]
::::{dropdown} Changes to the optional body property
In 8.x, every API function had a `body` property that would provide a place to put arbitrary values that should go in the HTTP request body, even if they were not noted in the specification or documentation. In 9.0, each API function still includes an optional `body` property, but TypeScript's type checker will disallow properties that should go in the root of the object. A `querystring` parameter has also been added that behaves the same as `body`, but inserts its values into the request querystring.
**Impact**<br> Some adjustments to API calls may be necessary for code that used a `body` property 8.x, especially to appease the TypeScript type checker, but it should not have any impact on any code that was not using a `body` property.
**Action**<br> Check existing code for use of the `body` property, and move any properties that should be in the root object according to the API function's request type definition. If using TypeScript, the TypeScript type checker will surface most of these issues for you.
::::
::::{dropdown} Changes to API parameter collation into an HTTP request
The logic for where each parameter in an API function call should be added to its HTTP request has been updated:
1. If recognized as a `body` parameter according to the Elasticsearch specification, put it in the JSON body
2. If recognized as a `path` parameter, put it in the URL path
3. If recognized as a `query` parameter or a "common" query parameter (e.g. `pretty`, `error_trace`), put it in the querystring
4. If not recognized, and this API accepts a JSON body, put it in the JSON body
5. If not recognized and this API does not accept a JSON body, put it in the querystring
The first two steps are identical in 8.x. The final three steps replace the logic from 8.x that put all unrecognized parameters in the querystring.
**Impact**<br> Some parameters that were sent via querystring to Elasticsearch may be sent in the JSON request body, and vice versa.
**Action**<br> If Elasticsearch sends back an error response due to a request not being valid, verify with the client's TypeScript type definitions, or via the docs, that the parameters your code passes are correct.
::::
::::{dropdown} Removal of the default 30-second timeout on all API calls
The default 30-second timeout on all HTTP requests sent to Elasticsearch has been dropped in favor of having no timeout set at all. The previous behavior still works as it did when setting the `requestTimeout` value.
See pull request [#2573](https://github.com/elastic/elasticsearch-js/pull/2573) for more information.
**Impact**<br> Requests to Elasticsearch that used to time out after 30 seconds will now wait for as long as it takes for Elasticsearch to respond.
**Action**<br> In environments where it is not ideal to wait for an API response indefinitely, manually setting the `requestTimeout` option when instantiating the client still works as it did in 8.x.
::::

View File

@ -0,0 +1,21 @@
---
navigation_title: "Deprecations"
---
# Elasticsearch JavaScript Client deprecations [elasticsearch-javascript-client-deprecations]
Over time, certain Elastic functionality becomes outdated and is replaced or removed. To help with the transition, Elastic deprecates functionality for a period before removal, giving you time to update your applications.
Review the deprecated functionality for the Elasticsearch JavaScript Client. While deprecations have no immediate impact, we strongly encourage you update your implementation after you upgrade. To learn how to upgrade, check out [Upgrade](docs-content://deploy-manage/upgrade.md).
## 9.0.0 [elasticsearch-javascript-client-900-deprecations]
_No deprecations_
% ## Next version
% ::::{dropdown} Deprecation title
% Description of the deprecation.
% For more information, check [PR #](PR link).
% **Impact**<br> Impact of deprecation.
% **Action**<br> Steps for mitigating deprecation impact.
% ::::

View File

@ -0,0 +1,43 @@
---
navigation_title: "Elasticsearch JavaScript Client"
mapped_pages:
- https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/changelog-client.html
---
# Elasticsearch JavaScript Client release notes [elasticsearch-javascript-client-release-notes]
Review the changes, fixes, and more in each version of Elasticsearch JavaScript Client.
To check for security updates, go to [Security announcements for the Elastic stack](https://discuss.elastic.co/c/announcements/security-announcements/31).
% Release notes include only features, enhancements, and fixes. Add breaking changes, deprecations, and known issues to the applicable release notes sections.
% ## version.next [elasticsearch-javascript-client-next-release-notes]
% **Release date:** Month day, year
% ### Features and enhancements [elasticsearch-javascript-client-next-features-enhancements]
% ### Fixes [elasticsearch-javascript-client-next-fixes]
## 9.0.0 [elasticsearch-javascript-client-900-release-notes]
**Release date:** April 8, 2025
### Features and enhancements [elasticsearch-javascript-client-900-features-enhancements]
- **Compatibility with Elasticsearch 9.0:** All changes and additions to Elasticsearch APIs for its 9.0 release are reflected in this release.
- **Serverless client merged in:** the `@elastic/elasticsearch-serverless` client is being deprecated, and its functionality has been merged back into this client. This should have zero impact on the way the client works by default, except that a new `serverMode` option has been added. When it's explicitly set to `"serverless"` by a user, a few default settings and behaviors are changed:
- turns off sniffing and ignores any sniffing-related options
- ignores all nodes passed in config except the first one, and ignores any node filtering and selecting options
- enables compression and `TLSv1_2_method` (same as when configured for Elastic Cloud)
- adds an `elastic-api-version` HTTP header to all requests
- uses `CloudConnectionPool` by default instead of `WeightedConnectionPool`
- turns off vendored `content-type` and `accept` headers in favor or standard MIME types
Docstrings for types that differ between stack and serverless have also been updated to indicate when that is the case.
- **Improved Cloud ID parsing:** when using a Cloud ID as the `cloud` parameter to instantiate the client, that ID was assumed to be in the correct format. New assertions have been added to verify that format and throw a `ConfigurationError` if it is invalid. See [#2694](https://github.com/elastic/elasticsearch-js/issues/2694).
% ### Fixes [elasticsearch-javascript-client-900-fixes]

View File

@ -0,0 +1,24 @@
---
navigation_title: "Known issues"
---
# Elasticsearch JavaScript Client known issues [elasticsearch-javascript-client-known-issues]
## 9.0.0
_No known issues_
% Use the following template to add entries to this page.
% :::{dropdown} Title of known issue
% **Details**
% On [Month/Day/Year], a known issue was discovered that [description of known issue].
% **Workaround**
% Workaround description.
% **Resolved**
% On [Month/Day/Year], this issue was resolved.
% :::

View File

@ -0,0 +1,5 @@
toc:
- file: index.md
- file: known-issues.md
- file: breaking-changes.md
- file: deprecations.md

View File

@ -1,158 +0,0 @@
[[client-testing]]
=== Testing
Testing is one of the most important parts of developing an application.
The client is very flexible when it comes to testing and is compatible with
most testing frameworks (such as https://www.npmjs.com/package/ava[`ava`],
which is used in the examples below).
If you are using this client, you are most likely working with {es}, and one of
the first issues you face is how to test your application. A perfectly valid
solution is to use the real {es} instance for testing your application, but you
would be doing an integration test, while you want a unit test. There are many
ways to solve this problem, you could create the database with Docker, or use an
in-memory compatible one, but if you are writing unit tests that can be easily
parallelized this becomes quite uncomfortable. A different way of improving your
testing experience while doing unit tests is to use a mock.
The client is designed to be easy to extend and adapt to your needs. Thanks to
its internal architecture it allows you to change some specific components while
keeping the rest of it working as usual. Each {es} official client is composed
of the following components:
* `API layer`: every {es} API that you can call.
* `Transport`: a component that takes care of preparing a request before sending
it and handling all the retry and sniffing strategies.
* `ConnectionPool`: {es} is a cluster and might have multiple nodes, the
`ConnectionPool` takes care of them.
* `Serializer`: A class with all the serialization strategies, from the basic
JSON to the new line delimited JSON.
* `Connection`: The actual HTTP library.
The best way to mock {es} with the official clients is to replace the
`Connection` component since it has very few responsibilities and it does not
interact with other internal components other than getting requests and
returning responses.
[discrete]
==== `@elastic/elasticsearch-mock`
Writing each time a mock for your test can be annoying and error-prone, so we
have built a simple yet powerful mocking library specifically designed for this
client, and you can install it with the following command:
[source,sh]
----
npm install @elastic/elasticsearch-mock --save-dev
----
With this library you can create custom mocks for any request you can send to
{es}. It offers a simple and intuitive API and it mocks only the HTTP layer,
leaving the rest of the client working as usual.
Before showing all of its features, and what you can do with it, lets see an
example:
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const Mock = require('@elastic/elasticsearch-mock')
const mock = new Mock()
const client = new Client({
cloud: { id: '<cloud-id>' },
auth: { apiKey: 'base64EncodedKey' },
Connection: mock.getConnection()
})
mock.add({
method: 'GET',
path: '/'
}, () => {
return { status: 'ok' }
})
client.info().then(console.log, console.log)
----
As you can see it works closely with the client itself, once you have created a
new instance of the mock library you just need to call the mock.getConnection()
method and pass its result to the Connection option of the client. From now on,
every request is handled by the mock library, and the HTTP layer will never be
touched. As a result, your test is significantly faster and you are able to
easily parallelize them!
The library allows you to write both “strict” and “loose” mocks, which means
that you can write a mock that handles a very specific request or be looser and
handle a group of request, lets see this in action:
[source,js]
----
mock.add({
method: 'POST',
path: '/indexName/_search'
}, () => {
return {
hits: {
total: { value: 1, relation: 'eq' },
hits: [{ _source: { baz: 'faz' } }]
}
}
})
mock.add({
method: 'POST',
path: '/indexName/_search',
body: { query: { match: { foo: 'bar' } } }
}, () => {
return {
hits: {
total: { value: 0, relation: 'eq' },
hits: []
}
}
})
----
In the example above, every search request gets the first response, while every
search request that uses the query described in the second mock gets the second
response.
You can also specify dynamic paths:
[source,js]
----
mock.add({
method: 'GET',
path: '/:index/_count'
}, () => {
return { count: 42 }
})
client.count({ index: 'foo' }).then(console.log, console.log) // => { count: 42 }
client.count({ index: 'bar' }).then(console.log, console.log) // => { count: 42 }
----
And wildcards are supported as well.
Another very interesting use case is the ability to create a test that randomly
fails to see how your code reacts to failures:
[source,js]
----
mock.add({
method: 'GET',
path: '/:index/_count'
}, () => {
if (Math.random() > 0.8) {
return ResponseError({ body: {}, statusCode: 500 })
} else {
return { count: 42 }
}
})
----
We have seen how simple is mocking {es} and testing your application, you can
find many more features and examples in the
https://github.com/elastic/elasticsearch-js-mock[module documentation].

View File

@ -1,8 +0,0 @@
[[timeout-best-practices]]
=== Timeout best practices
Starting in 9.0.0, this client is configured to not time out any HTTP request by default. {es} will always eventually respond to any request, even if it takes several minutes. Reissuing a request that it has not responded to yet can cause performance side effects. See the {ref}/modules-network.html#_http_client_configuration[official {es} recommendations for HTTP clients] for more information.
Prior to 9.0, this client was configured by default to operate like many HTTP client libraries do, by using a relatively short (30 second) timeout on all requests sent to {es}, raising a `TimeoutError` when that time period elapsed without receiving a response.
If your circumstances require you to set timeouts on Elasticsearch requests, setting the `requestTimeout` value to a millisecond value will cause this client to operate as it did prior to 9.0.

View File

@ -1,73 +0,0 @@
[[transport]]
=== Transport
This class is responsible for performing the request to {es} and handling
errors, it also handles sniffing.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const { Transport } = require('@elastic/transport')
class MyTransport extends Transport {
request (params, options, callback) {
// your code
}
}
const client = new Client({
Transport: MyTransport
})
----
Sometimes you need to inject a small snippet of your code and then continue to
use the usual client code. In such cases, call `super.method`:
[source,js]
----
class MyTransport extends Transport {
request (params, options, callback) {
// your code
return super.request(params, options, callback)
}
}
----
==== Supported content types
Depending on the `content-type` of the response, the transport will return the body as different types:
[cols="1,1"]
|===
|Content-Type |JavaScript type
|`application/json`
|`object`
|`text/plain`
|`string`
|`application/vnd.elasticsearch+json`
|`object`
|`application/vnd.mapbox-vector-tile`
|`Buffer`
|`application/vnd.apache.arrow.stream`
|`Buffer`
|`application/vnd.elasticsearch+arrow+stream`
|`Buffer`
|`application/smile`
|`Buffer`
|`application/vnd.elasticsearch+smile`
|`Buffer`
|`application/cbor`
|`Buffer`
|`application/vnd.elasticsearch+cbor`
|`Buffer`
|===

18
index.d.ts vendored
View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
import Client from './lib/client'

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
'use strict'

View File

@ -1,6 +1,6 @@
{
"name": "@elastic/elasticsearch",
"version": "9.0.0-alpha.4",
"version": "9.0.0",
"versionCanary": "9.0.0-canary.0",
"description": "The official Elasticsearch client for Node.js",
"main": "./index.js",
@ -22,6 +22,7 @@
"lint": "ts-standard src",
"lint:fix": "ts-standard --fix src",
"license-checker": "license-checker --production --onlyAllow='MIT;Apache-2.0;Apache1.1;ISC;BSD-3-Clause;BSD-2-Clause;0BSD'",
"license-header": "./scripts/check-spdx",
"prebuild": "npm run clean-build && npm run lint",
"build": "tsc && rm lib/package.json && mv lib/src/* lib/ && rm -rf lib/src",
"clean-build": "rimraf ./lib && mkdir lib",
@ -89,7 +90,7 @@
"zx": "7.2.3"
},
"dependencies": {
"@elastic/transport": "9.0.0-alpha.1",
"@elastic/transport": "^9.0.0",
"apache-arrow": "^18.0.0",
"tslib": "^2.4.0"
},

27
scripts/check-spdx Executable file
View File

@ -0,0 +1,27 @@
#!/usr/bin/env bash
# Copyright Elasticsearch B.V. and contributors
# SPDX-License-Identifier: Apache-2.0
correct='/*
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/'
the_exit=0
check_file() {
if $(diff <(head -n4 "$1") <(echo "$correct") &>/dev/null); then
echo "Correct: $1"
else
echo "Incorrect: $1"
the_exit=1
fi
}
echo "SPDX license header check"
for file in $(git ls-files | grep -E '\.(ts|js|mjs)$'); do
check_file "$file"
done
exit "$the_exit"

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
'use strict'

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
const { join } = require('path')
@ -91,6 +77,7 @@ ${source.trim()}
}
const options = minimist(process.argv.slice(2), {
boolean: ['debug'],
string: ['version'],
default: {
version: 'master'
@ -102,7 +89,7 @@ generate(options.version)
.catch(err => log.fail(err.message))
.finally(() => {
const keys = Object.keys(failures)
if (keys.length > 0) {
if (keys.length > 0 && options.debug) {
let message = 'Some examples failed to generate:\n\n'
for (const key of keys) {
message += `${key}: ${failures[key]}\n`

View File

@ -1,143 +0,0 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict'
const { join } = require('path')
const { readdirSync, writeFileSync, readFileSync } = require('fs')
const minimist = require('minimist')
const ora = require('ora')
const rimraf = require('rimraf')
const standard = require('standard')
const downloadArtifacts = require('./download-artifacts')
const {
generate,
genFactory,
generateDocs,
generateRequestTypes
} = require('./utils')
start(minimist(process.argv.slice(2), {
string: ['version', 'hash']
}))
function start (opts) {
if (opts.version == null) {
console.error('Missing version parameter')
process.exit(1)
}
const packageFolder = join(__dirname, '..', 'api')
const apiOutputFolder = join(packageFolder, 'api')
const mainOutputFile = join(packageFolder, 'index.js')
const docOutputFile = join(__dirname, '..', 'docs', 'reference.asciidoc')
const typeDefFile = join(__dirname, '..', 'index.d.ts')
const requestParamsOutputFile = join(packageFolder, 'requestParams.d.ts')
let log
downloadArtifacts({ version: opts.version, hash: opts.hash })
.then(onArtifactsDownloaded)
.catch(err => {
console.log(err)
process.exit(1)
})
function onArtifactsDownloaded () {
log = ora('Generating APIs').start()
log.text = 'Cleaning API folder...'
rimraf.sync(join(apiOutputFolder, '*.js'))
const allSpec = readdirSync(downloadArtifacts.locations.specFolder)
.filter(file => file !== '_common.json')
.filter(file => !file.includes('deprecated'))
.sort()
.map(file => require(join(downloadArtifacts.locations.specFolder, file)))
const namespaces = namespacify(readdirSync(downloadArtifacts.locations.specFolder))
for (const namespace in namespaces) {
if (namespace === '_common') continue
const code = generate(namespace, namespaces[namespace], downloadArtifacts.locations.specFolder, opts.version)
const filePath = join(apiOutputFolder, `${namespace}.js`)
writeFileSync(filePath, code, { encoding: 'utf8' })
}
writeFileSync(
requestParamsOutputFile,
generateRequestTypes(opts.version, allSpec),
{ encoding: 'utf8' }
)
const { fn: factory, types } = genFactory(apiOutputFolder, downloadArtifacts.locations.specFolder, namespaces)
writeFileSync(
mainOutputFile,
factory,
{ encoding: 'utf8' }
)
const oldTypeDefString = readFileSync(typeDefFile, 'utf8')
const start = oldTypeDefString.indexOf('/* GENERATED */')
const end = oldTypeDefString.indexOf('/* /GENERATED */')
const newTypeDefString = oldTypeDefString.slice(0, start + 15) + '\n' + types + '\n ' + oldTypeDefString.slice(end)
writeFileSync(
typeDefFile,
newTypeDefString,
{ encoding: 'utf8' }
)
lintFiles(log, () => {
log.text = 'Generating documentation'
writeFileSync(
docOutputFile,
generateDocs(require(join(downloadArtifacts.locations.specFolder, '_common.json')), allSpec),
{ encoding: 'utf8' }
)
log.succeed('Done!')
})
}
function lintFiles (log, cb) {
log.text = 'Linting...'
const files = [join(packageFolder, '*.js'), join(apiOutputFolder, '*.js')]
standard.lintFiles(files, { fix: true }, err => {
if (err) {
return log.fail(err.message)
}
cb()
})
}
function namespacify (apis) {
return apis
.map(api => api.slice(0, -5))
.filter(api => api !== '_common')
.filter(api => !api.includes('deprecated'))
.reduce((acc, val) => {
if (val.includes('.')) {
val = val.split('.')
acc[val[0]] = acc[val[0]] || []
acc[val[0]].push(val[1])
} else {
acc[val] = []
}
return acc
}, {})
}
}

View File

@ -1,8 +0,0 @@
#!/bin/bash
exec docker run \
--rm \
-e ELASTICSEARCH_URL="http://elasticsearch:9200" \
-p 5601:5601 \
--network=elastic \
docker.elastic.co/kibana/kibana:7.0.0-beta1

View File

@ -1,3 +1,8 @@
/*
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
'use strict'
/**
@ -130,9 +135,9 @@ release(
'dry-run',
// help text
'help',
'help'
],
alias: { help: 'h' },
alias: { help: 'h' }
})
)
.catch(err => {

View File

@ -1,139 +0,0 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict'
const { accessSync, mkdirSync } = require('fs')
const { join } = require('path')
const Git = require('simple-git')
const esRepo = 'https://github.com/elastic/elasticsearch.git'
const esFolder = join(__dirname, '..', '..', 'elasticsearch')
const apiFolder = join(esFolder, 'rest-api-spec', 'src', 'main', 'resources', 'rest-api-spec', 'api')
const xPackFolder = join(esFolder, 'x-pack', 'plugin', 'src', 'test', 'resources', 'rest-api-spec', 'api')
function cloneAndCheckout (opts, callback) {
const { log, tag, branch } = opts
withTag(tag, callback)
/**
* Sets the elasticsearch repository to the given tag.
* If the repository is not present in `esFolder` it will
* clone the repository and the checkout the tag.
* If the repository is already present but it cannot checkout to
* the given tag, it will perform a pull and then try again.
* @param {string} tag
* @param {function} callback
*/
function withTag (tag, callback) {
let fresh = false
let retry = 0
if (!pathExist(esFolder)) {
if (!createFolder(esFolder)) {
log.fail('Failed folder creation')
return
}
fresh = true
}
const git = Git(esFolder)
if (fresh) {
clone(checkout)
} else if (opts.branch) {
checkout(true)
} else {
checkout()
}
function checkout (alsoPull = false) {
if (branch) {
log.text = `Checking out branch '${branch}'`
} else {
log.text = `Checking out tag '${tag}'`
}
git.checkout(branch || tag, err => {
if (err) {
if (retry++ > 0) {
callback(new Error(`Cannot checkout tag '${tag}'`), { apiFolder, xPackFolder })
return
}
return pull(checkout)
}
if (alsoPull) {
return pull(checkout)
}
callback(null, { apiFolder, xPackFolder })
})
}
function pull (cb) {
log.text = 'Pulling elasticsearch repository...'
git.pull(err => {
if (err) {
callback(err, { apiFolder, xPackFolder })
return
}
cb()
})
}
function clone (cb) {
log.text = 'Cloning elasticsearch repository...'
git.clone(esRepo, esFolder, err => {
if (err) {
callback(err, { apiFolder, xPackFolder })
return
}
cb()
})
}
}
/**
* Checks if the given path exists
* @param {string} path
* @returns {boolean} true if exists, false if not
*/
function pathExist (path) {
try {
accessSync(path)
return true
} catch (err) {
return false
}
}
/**
* Creates the given folder
* @param {string} name
* @returns {boolean} true on success, false on failure
*/
function createFolder (name) {
try {
mkdirSync(name)
return true
} catch (err) {
return false
}
}
}
module.exports = cloneAndCheckout

View File

@ -1,553 +0,0 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* eslint camelcase: 0 */
'use strict'
const { join } = require('path')
const dedent = require('dedent')
const allowedMethods = {
noBody: ['GET', 'HEAD', 'DELETE'],
body: ['POST', 'PUT', 'DELETE']
}
// if a parameter is depracted in a minor release
// we should be able to support it until the next major
const deprecatedParameters = require('./patch.json')
// list of apis that does not need any kind of validation
// because of how the url is built or the `type` handling in ES7
const noPathValidation = [
'create',
'exists',
'explain',
'get',
'get_source',
'index',
'indices.get_alias',
'indices.exists_alias',
'indices.get_field_mapping',
'indices.get_mapping',
'indices.get_settings',
'indices.put_mapping',
'indices.stats',
'delete',
'nodes.info',
'nodes.stats',
'nodes.usage',
'tasks.cancel',
'termvectors',
'update'
]
function generateNamespace (namespace, nested, specFolder, version) {
const common = require(join(specFolder, '_common.json'))
let code = dedent`
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict'
/* eslint camelcase: 0 */
/* eslint no-unused-vars: 0 */
const { handleError, snakeCaseKeys, normalizeArguments, kConfigurationError } = require('../utils')
`
if (nested.length > 0) {
let getters = ''
for (const n of nested) {
if (n.includes('_')) {
const nameSnaked = n
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
.replace(/_([a-z])/g, k => k[1].toUpperCase())
getters += `${n}: { get () { return this.${nameSnaked} } },\n`
}
}
const api = generateMultiApi(version, namespace, nested, common, specFolder)
if (getters.length > 0) {
getters = `Object.defineProperties(${api.namespace}Api.prototype, {\n${getters}})`
}
code += `
const acceptedQuerystring = ${JSON.stringify(api.acceptedQuerystring)}
const snakeCase = ${JSON.stringify(api.snakeCase)}
function ${api.namespace}Api (transport, ConfigurationError) {
this.transport = transport
this[kConfigurationError] = ConfigurationError
}
${api.code}
${getters}
module.exports = ${api.namespace}Api
`
} else {
const spec = require(join(specFolder, `${namespace}.json`))
const api = generateSingleApi(version, spec, common)
code += `
const acceptedQuerystring = ${JSON.stringify(api.acceptedQuerystring)}
const snakeCase = ${JSON.stringify(api.snakeCase)}
${api.code}
module.exports = ${api.name}Api
`
}
return code
}
function generateMultiApi (version, namespace, nested, common, specFolder) {
const namespaceSnaked = namespace
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
.replace(/_([a-z])/g, k => k[1].toUpperCase())
let code = ''
const snakeCase = {}
const acceptedQuerystring = []
for (const n of nested) {
const nameSnaked = n
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
.replace(/_([a-z])/g, k => k[1].toUpperCase())
const spec = require(join(specFolder, `${namespace}.${n}.json`))
const api = generateSingleApi(version, spec, common)
code += `${Uppercase(namespaceSnaked)}Api.prototype.${nameSnaked} = ${api.code}\n\n`
Object.assign(snakeCase, api.snakeCase)
for (const q of api.acceptedQuerystring) {
if (!acceptedQuerystring.includes(q)) {
acceptedQuerystring.push(q)
}
}
}
return { code, snakeCase, acceptedQuerystring, namespace: Uppercase(namespaceSnaked) }
}
function generateSingleApi (version, spec, common) {
const release = version.charAt(0)
const api = Object.keys(spec)[0]
const name = api
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
.replace(/_([a-z])/g, k => k[1].toUpperCase())
const { paths } = spec[api].url
const { params } = spec[api]
const acceptedQuerystring = []
const required = []
const methods = paths.reduce((acc, val) => {
for (const method of val.methods) {
if (!acc.includes(method)) acc.push(method)
}
return acc
}, [])
const parts = paths.reduce((acc, val) => {
if (!val.parts) return acc
for (const part of Object.keys(val.parts)) {
if (!acc.includes(part)) acc.push(part)
}
return acc
}, [])
// get the required parts from the url
// if the url has at least one static path,
// then there are not required parts of the url
let allParts = []
for (const path of paths) {
if (path.parts) {
allParts.push(Object.keys(path.parts))
} else {
allParts = []
break
}
}
if (allParts.length > 0) {
intersect(...allParts).forEach(r => required.push(r))
}
for (const key in params) {
if (params[key].required) {
required.push(key)
}
acceptedQuerystring.push(key)
if (deprecatedParameters[release] && deprecatedParameters[release][key]) {
acceptedQuerystring.push(deprecatedParameters[release][key])
}
}
for (const key in spec[api]) {
const k = spec[api][key]
if (k && k.required) {
required.push(key)
}
}
if (common && common.params) {
for (const key in common.params) {
acceptedQuerystring.push(key)
}
}
const code = `
function ${name}Api (params, options, callback) {
;[params, options, callback] = normalizeArguments(params, options, callback)
${genRequiredChecks()}
${genUrlValidation(paths, api)}
let { ${genQueryDenylist(false)}, ...querystring } = params
querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring)
let path = ''
${buildPath()}
// build request object
const request = {
method,
path,
${genBody(api, methods, spec[api].body, spec)}
querystring
}
return this.transport.request(request, options, callback)
}
`.trim() // always call trim to avoid newlines
return {
name,
code,
acceptedQuerystring: acceptedQuerystring,
snakeCase: genSnakeCaseMap(),
documentation: generateDocumentation(spec[api], api)
}
function genRequiredChecks () {
const code = required
.map(_genRequiredCheck)
.concat(_noBody())
.filter(Boolean)
if (code.length) {
code.unshift('// check required parameters')
}
return code.join('\n ')
function _genRequiredCheck (param) {
const camelCased = param[0] === '_'
? '_' + param.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
: param.replace(/_([a-z])/g, k => k[1].toUpperCase())
if (param === camelCased) {
const check = `
if (params['${param}'] == null) {
const err = new this[kConfigurationError]('Missing required parameter: ${param}')
return handleError(err, callback)
}
`
return check.trim()
} else {
const check = `
if (params['${param}'] == null && params['${camelCased}'] == null) {
const err = new this[kConfigurationError]('Missing required parameter: ${param} or ${camelCased}')
return handleError(err, callback)
}
`
return check.trim()
}
}
function _noBody () {
const check = `
if (params.body != null) {
const err = new this[kConfigurationError]('This API does not require a body')
return handleError(err, callback)
}
`
return spec[api].body === null ? check.trim() : ''
}
}
function genSnakeCaseMap () {
const toCamelCase = str => {
return str[0] === '_'
? '_' + str.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
: str.replace(/_([a-z])/g, k => k[1].toUpperCase())
}
return acceptedQuerystring.reduce((acc, val, index) => {
if (toCamelCase(val) !== val) {
acc[toCamelCase(val)] = val
}
return acc
}, {})
}
function genQueryDenylist (addQuotes = true) {
const toCamelCase = str => {
return str[0] === '_'
? '_' + str.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
: str.replace(/_([a-z])/g, k => k[1].toUpperCase())
}
const denylist = ['method', 'body']
parts.forEach(p => {
const camelStr = toCamelCase(p)
if (camelStr !== p) denylist.push(`${camelStr}`)
denylist.push(`${p}`)
})
return addQuotes ? denylist.map(q => `'${q}'`) : denylist
}
function buildPath () {
const toCamelCase = str => {
return str[0] === '_'
? '_' + str.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
: str.replace(/_([a-z])/g, k => k[1].toUpperCase())
}
const genAccessKey = str => {
const camelStr = toCamelCase(str)
return camelStr === str
? str
: `${str} || ${camelStr}`
}
const genCheck = path => {
return path
.split('/')
.filter(Boolean)
.map(p => p.startsWith('{') ? `(${genAccessKey(p.slice(1, -1))}) != null` : false)
.filter(Boolean)
.join(' && ')
}
const genPath = path => {
path = path
.split('/')
.filter(Boolean)
.map(p => p.startsWith('{') ? `encodeURIComponent(${genAccessKey(p.slice(1, -1))})` : `'${p}'`)
.join(' + \'/\' + ')
return path.length > 0 ? ('\'/\' + ' + path) : '\'/\''
}
let hasStaticPath = false
let sortedPaths = paths
// some legacy API have mutliple statis paths
// this filter removes them
.filter(p => {
if (p.path.includes('{')) return true
if (hasStaticPath === false && p.deprecated == null) {
hasStaticPath = true
return true
}
return false
})
// sort by number of parameters (desc)
.sort((a, b) => Object.keys(b.parts || {}).length - Object.keys(a.parts || {}).length)
const allDeprecated = paths.filter(path => path.deprecated != null)
if (allDeprecated.length === paths.length) sortedPaths = [paths[0]]
let code = ''
for (let i = 0; i < sortedPaths.length; i++) {
const { path, methods } = sortedPaths[i]
if (sortedPaths.length === 1) {
code += `if (method == null) method = ${generatePickMethod(methods)}
path = ${genPath(path)}
`
} else if (i === 0) {
code += `if (${genCheck(path)}) {
if (method == null) method = ${generatePickMethod(methods)}
path = ${genPath(path)}
}
`
} else if (i === sortedPaths.length - 1) {
code += ` else {
if (method == null) method = ${generatePickMethod(methods)}
path = ${genPath(path)}
}
`
} else {
code += ` else if (${genCheck(path)}) {
if (method == null) method = ${generatePickMethod(methods)}
path = ${genPath(path)}
}
`
}
}
return code
}
}
function generatePickMethod (methods) {
if (methods.length === 1) {
return `'${methods[0]}'`
}
const bodyMethod = getBodyMethod(methods)
const noBodyMethod = getNoBodyMethod(methods)
if (bodyMethod && noBodyMethod) {
return `body == null ? '${noBodyMethod}' : '${bodyMethod}'`
} else if (bodyMethod) {
return `'${bodyMethod}'`
} else {
return `'${noBodyMethod}'`
}
}
function genBody (api, methods, body, spec) {
const bodyMethod = getBodyMethod(methods)
const { content_type } = spec[api].headers
if (content_type && content_type.includes('application/x-ndjson')) {
return 'bulkBody: body,'
}
if (body === null && bodyMethod) {
return 'body: \'\','
} else if (bodyMethod) {
return 'body: body || \'\','
} else {
return 'body: null,'
}
}
function getBodyMethod (methods) {
const m = methods.filter(m => ~allowedMethods.body.indexOf(m))
if (m.length) return m[0]
return null
}
function getNoBodyMethod (methods) {
const m = methods.filter(m => ~allowedMethods.noBody.indexOf(m))
if (m.length) return m[0]
return null
}
function genUrlValidation (paths, api) {
// this api does not need url validation
if (!needsPathValidation(api)) return ''
// gets only the dynamic components of the url in an array
// then we reverse it. A parameters always require what is
// at its right in the array.
const chunks = paths
.sort((a, b) => Object.keys(a.parts || {}).length > Object.keys(b.parts || {}).length ? -1 : 1)
.slice(0, 1)
.reduce((acc, val) => val.path, '')
// .reduce((a, b) => a.path.split('/').length > b.path.split('/').length ? a.path : b.path)
.split('/')
.filter(s => s.startsWith('{'))
.map(s => s.slice(1, -1))
.reverse()
let code = ''
const len = chunks.length
chunks.forEach((chunk, index) => {
if (index === len - 1) return
const params = []
let camelCased = chunk[0] === '_'
? '_' + chunk.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
: chunk.replace(/_([a-z])/g, k => k[1].toUpperCase())
if (chunk === camelCased) {
code += `${index ? '} else ' : ''}if (params['${chunk}'] != null && (`
} else {
code += `${index ? '} else ' : ''}if ((params['${chunk}'] != null || params['${camelCased}'] != null) && (`
}
for (let i = index + 1; i < len; i++) {
params.push(chunks[i])
// url parts can be declared in camelCase fashion
camelCased = chunks[i][0] === '_'
? '_' + chunks[i].slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
: chunks[i].replace(/_([a-z])/g, k => k[1].toUpperCase())
if (chunks[i] === camelCased) {
code += `params['${chunks[i]}'] == null${i === len - 1 ? '' : ' || '}`
} else {
code += `(params['${chunks[i]}'] == null && params['${camelCased}'] == null)${i === len - 1 ? '' : ' || '}`
}
}
code += `)) {
const err = new this[kConfigurationError]('Missing required parameter of the url: ${params.join(', ')}')
return handleError(err, callback)
`
})
if (chunks.length > 1) {
code += '\n}'
}
if (code.length) {
code = '// check required url components\n' + code
}
return code.trim()
}
function generateDocumentation ({ documentation }, op) {
// we use `replace(/\u00A0/g, ' ')` to remove no breaking spaces
// because some parts of the description fields are using it
if (documentation == null) return ''
let doc = '/**\n'
doc += ` * Perform a ${op} request\n`
if (documentation.description) {
doc += ` * ${documentation.description.replace(/\u00A0/g, ' ')}\n`
}
if (documentation.url) {
doc += ` * ${documentation.url}\n`
}
doc += ' */'
return doc
}
function needsPathValidation (api) {
return noPathValidation.indexOf(api) === -1
}
function intersect (first, ...rest) {
return rest.reduce((accum, current) => {
return accum.filter(x => current.indexOf(x) !== -1)
}, first)
}
function Uppercase (str) {
return str[0].toUpperCase() + str.slice(1)
}
module.exports = generateNamespace

View File

@ -1,318 +0,0 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict'
const { readdirSync } = require('fs')
const { join } = require('path')
const dedent = require('dedent')
const codeExamples = readdirSync(join(__dirname, '..', '..', 'docs', 'examples'))
.map(file => file.slice(0, -9))
.filter(api => api !== 'index')
function generateDocs (common, spec) {
let doc = dedent`
[[api-reference]]
////////
===========================================================================================================================
|| ||
|| ||
|| ||
|| ██████╗ ███████╗ █████╗ ██████╗ ███╗ ███╗███████╗ ||
|| ██╔══██╗██╔════╝██╔══██╗██╔══██╗████╗ ████║██╔════╝ ||
|| ██████╔╝█████╗ ███████║██║ ██║██╔████╔██║█████╗ ||
|| ██╔══██╗██╔══╝ ██╔══██║██║ ██║██║╚██╔╝██║██╔══╝ ||
|| ██║ ██║███████╗██║ ██║██████╔╝██║ ╚═╝ ██║███████╗ ||
|| ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝ ||
|| ||
|| ||
|| This file is autogenerated, DO NOT send pull requests that changes this file directly. ||
|| You should update the script that does the generation, which can be found in '/scripts/utils/generateDocs.js'. ||
|| ||
|| You can run the script with the following command: ||
|| node scripts/generate --branch <branch_name> ||
|| or ||
|| node scripts/generate --tag <tag_name> ||
|| ||
|| ||
|| ||
===========================================================================================================================
////////
== API Reference
This document contains the entire list of the Elasticsearch API supported by the client, both OSS and commercial. The client is entirely licensed under Apache 2.0.
Elasticsearch exposes an HTTP layer to communicate with, and the client is a library that will help you do this. Because of this reason, you will see HTTP related parameters, such as ${'`'}body${'`'} or ${'`'}headers${'`'}.
Every API can accept two objects, the first contains all the parameters that will be sent to Elasticsearch, while the second includes the request specific parameters, such as timeouts, headers, and so on.
In the first object, every parameter but the body will be sent via querystring or url parameter, depending on the API, and every unrecognized parameter will be sent as querystring.
[source,js]
----
// promise API
const result = await client.search({
index: 'my-index',
from: 20,
size: 10,
body: { foo: 'bar' }
}, {
ignore: [404],
maxRetries: 3
})
// callback API
client.search({
index: 'my-index',
from: 20,
size: 10,
body: { foo: 'bar' }
}, {
ignore: [404],
maxRetries: 3
}, (err, result) => {
if (err) console.log(err)
})
----
In this document, you will find the reference of every parameter accepted by the querystring or the url. If you also need to send the body, you can find the documentation of its format in the reference link that is present along with every endpoint.
\n\n`
doc += commonParameters(common)
spec.forEach(s => {
doc += '\n' + generateApiDoc(s)
})
return doc
}
function commonParameters (spec) {
let doc = dedent`
[discrete]
=== Common parameters
Parameters that are accepted by all API endpoints.
link:{ref}/common-options.html[Documentation]
[cols=2*]
|===\n`
Object.keys(spec.params).forEach(key => {
const name = isSnakeCased(key) && key !== camelify(key)
? '`' + key + '` or `' + camelify(key) + '`'
: '`' + key + '`'
doc += dedent`
|${name}
|${'`' + spec.params[key].type + '`'} - ${spec.params[key].description}`
if (spec.params[key].default) {
doc += ` +
_Default:_ ${'`' + spec.params[key].default + '`'}`
}
doc += '\n\n'
})
doc += dedent`
|===
`
return doc
}
function generateApiDoc (spec) {
const name = Object.keys(spec)[0]
const documentationUrl = spec[name].documentation && spec[name].documentation.url
? fixLink(name, spec[name].documentation.url)
: ''
const params = []
// url params
const urlParts = spec[name].url.paths.reduce((acc, path) => {
if (!path.parts) return acc
for (const part in path.parts) {
if (acc[part] != null) continue
acc[part] = path.parts[part]
}
return acc
}, {})
if (urlParts) {
Object.keys(urlParts).forEach(param => {
params.push({
name: param,
type: getType(urlParts[param].type, urlParts[param].options),
description: urlParts[param].description,
default: urlParts[param].default,
deprecated: !!urlParts[param].deprecated
})
})
}
// query params
const urlParams = spec[name].params
if (urlParams) {
Object.keys(urlParams).forEach(param => {
const duplicate = params.find(ele => ele.name === param)
if (duplicate) return
params.push({
name: param,
type: getType(urlParams[param].type, urlParams[param].options),
description: urlParams[param].description,
default: urlParams[param].default,
deprecated: !!urlParams[param].deprecated
})
})
}
// body params
const body = spec[name].body
if (body) {
params.push({
name: 'body',
type: 'object',
description: body.description,
default: body.default,
deprecated: !!body.deprecated
})
}
const codeParameters = params
.reduce((acc, val) => {
const code = `${val.name}: ${val.type},`
acc += acc === ''
? code
: '\n ' + code
return acc
}, '')
// remove last comma
.slice(0, -1)
const stability = spec[name].stability === 'stable'
? ''
: `*Stability:* ${spec[name].stability}`
let doc = dedent`
[discrete]
=== ${camelify(name)}
${stability}
[source,ts]
----
client.${camelify(name)}(${codeParameters.length > 0 ? `{\n ${codeParameters}\n}` : ''})
----\n`
if (documentationUrl) {
doc += `link:${documentationUrl}[Documentation] +\n`
}
if (codeExamples.includes(name)) {
doc += `{jsclient}/${name.replace(/\./g, '_')}_examples.html[Code Example] +\n`
}
if (params.length !== 0) {
doc += dedent`[cols=2*]
|===\n`
doc += params.reduce((acc, val) => {
const name = isSnakeCased(val.name) && val.name !== camelify(val.name)
? '`' + val.name + '` or `' + camelify(val.name) + '`'
: '`' + val.name + '`'
acc += dedent`
|${name}
|${'`' + val.type.replace(/\|/g, '\\|') + '`'} - ${val.description}`
if (val.default) {
acc += ` +\n_Default:_ ${'`' + val.default + '`'}`
}
if (val.deprecated) {
acc += ' +\n\nWARNING: This parameter has been deprecated.'
}
return acc + '\n\n'
}, '')
doc += dedent`
|===
`
}
doc += '\n'
return doc
}
const LINK_OVERRIDES = {
'license.delete': '{ref}/delete-license.html',
'license.get': '{ref}/get-license.html',
'license.get_basic_status': '{ref}/get-basic-status.html',
'license.get_trial_status': '{ref}/get-trial-status.html',
'license.post': '{ref}/update-license.html',
'license.post_start_basic': '{ref}/start-basic.html',
'license.post_start_trial': '{ref}/start-trial.html',
'migration.deprecations': '{ref}/migration-api-deprecation.html',
'monitoring.bulk': '{ref}/monitor-elasticsearch-cluster.html',
'ingest.delete_pipeline': '{ref}/delete-pipeline-api.html',
'ingest.get_pipeline': '{ref}/get-pipeline-api.html',
'ingest.put_pipeline': '{ref}/put-pipeline-api.html',
'ingest.simulate': '{ref}/simulate-pipeline-api.html',
'ingest.processor_grok': '{ref}/grok-processor.html#grok-processor-rest-get'
}
// Fixes bad urls in the JSON spec
function fixLink (name, str) {
/* In 6.x some API start with `xpack.` when in master they do not. We
* can safely ignore that for link generation. */
name = name.replace(/^xpack\./, '')
const override = LINK_OVERRIDES[name]
if (override) return override
if (!str) return ''
/* Replace references to the guide with the attribute {ref} because
* the json files in the Elasticsearch repo are a bit of a mess. */
str = str.replace(/^.+guide\/en\/elasticsearch\/reference\/[^/]+\/([^./]*\.html(?:#.+)?)$/, '{ref}/$1')
str = str.replace(/frozen\.html/, 'freeze-index-api.html')
str = str.replace(/ml-file-structure\.html/, 'ml-find-file-structure.html')
str = str.replace(/security-api-get-user-privileges\.html/, 'security-api-get-privileges.html')
return str
}
function getType (type, options) {
switch (type) {
case 'list':
return 'string | string[]'
case 'date':
case 'time':
case 'timeout':
return 'string'
case 'enum':
return options.map(k => `'${k}'`).join(' | ')
case 'int':
case 'double':
case 'long':
return 'number'
default:
return type
}
}
function camelify (str) {
return str[0] === '_'
? '_' + str.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
: str.replace(/_([a-z])/g, k => k[1].toUpperCase())
}
function isSnakeCased (str) {
return !!~str.indexOf('_')
}
module.exports = generateDocs

View File

@ -1,299 +0,0 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* eslint-disable no-template-curly-in-string */
/* eslint camelcase: 0 */
'use strict'
const { readdirSync } = require('fs')
const { join } = require('path')
const dedent = require('dedent')
const deepmerge = require('deepmerge')
function genFactory (folder, specFolder, namespaces) {
// get all the API files
// const apiFiles = readdirSync(folder)
const apiFiles = readdirSync(specFolder)
.filter(file => file !== '_common.json')
.filter(file => !file.includes('deprecated'))
.sort()
const types = apiFiles
.map(file => {
const name = file
.slice(0, -5)
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
.replace(/_([a-z])/g, k => k[1].toUpperCase())
return file
.slice(0, -5) // remove `.json` extension
.split('.')
.reverse()
.reduce((acc, val) => {
const spec = readSpec(specFolder, file.slice(0, -5))
const isHead = isHeadMethod(spec, file.slice(0, -5))
const body = hasBody(spec, file.slice(0, -5))
const methods = acc === null ? buildMethodDefinition({ kibana: false }, val, name, body, isHead, spec) : null
const obj = {}
if (methods) {
for (const m of methods) {
obj[m.key] = m.val
}
} else {
obj[val] = acc
if (isSnakeCased(val)) {
obj[camelify(val)] = acc
}
}
return obj
}, null)
})
.reduce((acc, val) => deepmerge(acc, val), {})
const kibanaTypes = apiFiles
.map(file => {
const name = file
.slice(0, -5)
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
.replace(/_([a-z])/g, k => k[1].toUpperCase())
return file
.slice(0, -5) // remove `.json` extension
.split('.')
.reverse()
.reduce((acc, val) => {
const spec = readSpec(specFolder, file.slice(0, -5))
const isHead = isHeadMethod(spec, file.slice(0, -5))
const body = hasBody(spec, file.slice(0, -5))
const methods = acc === null ? buildMethodDefinition({ kibana: true }, val, name, body, isHead, spec) : null
const obj = {}
if (methods) {
for (const m of methods) {
obj[m.key] = m.val
}
} else {
obj[camelify(val)] = acc
}
return obj
}, null)
})
.reduce((acc, val) => deepmerge(acc, val), {})
// serialize the type object
const typesStr = Object.keys(types)
.map(key => {
const line = ` ${key}: ${JSON.stringify(types[key], null, 4)}`
if (line.slice(-1) === '}') {
return line.slice(0, -1) + ' }'
}
return line
})
.join('\n')
// remove useless quotes and commas
.replace(/"/g, '')
.replace(/,$/gm, '')
const kibanaTypesStr = Object.keys(kibanaTypes)
.map(key => {
const line = ` ${key}: ${JSON.stringify(kibanaTypes[key], null, 4)}`
if (line.slice(-1) === '}') {
return line.slice(0, -1) + ' }'
}
return line
})
.join('\n')
// remove useless quotes and commas
.replace(/"/g, '')
.replace(/,$/gm, '')
let apisStr = ''
const getters = []
for (const namespace in namespaces) {
if (namespaces[namespace].length > 0) {
getters.push(`${camelify(namespace)}: {
get () {
if (this[k${toPascalCase(camelify(namespace))}] === null) {
this[k${toPascalCase(camelify(namespace))}] = new ${toPascalCase(camelify(namespace))}Api(this.transport, this[kConfigurationError])
}
return this[k${toPascalCase(camelify(namespace))}]
}
},\n`)
if (namespace.includes('_')) {
getters.push(`${namespace}: { get () { return this.${camelify(namespace)} } },\n`)
}
} else {
apisStr += `ESAPI.prototype.${camelify(namespace)} = ${camelify(namespace)}Api\n`
if (namespace.includes('_')) {
getters.push(`${namespace}: { get () { return this.${camelify(namespace)} } },\n`)
}
}
}
apisStr += '\nObject.defineProperties(ESAPI.prototype, {\n'
for (const getter of getters) {
apisStr += getter
}
apisStr += '})'
let modules = ''
let symbols = ''
let symbolsInstance = ''
for (const namespace in namespaces) {
if (namespaces[namespace].length > 0) {
modules += `const ${toPascalCase(camelify(namespace))}Api = require('./api/${namespace}')\n`
symbols += `const k${toPascalCase(camelify(namespace))} = Symbol('${toPascalCase(camelify(namespace))}')\n`
symbolsInstance += `this[k${toPascalCase(camelify(namespace))}] = null\n`
} else {
modules += `const ${camelify(namespace)}Api = require('./api/${namespace}')\n`
}
}
const fn = dedent`
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict'
${modules}
const { kConfigurationError } = require('./utils')
${symbols}
function ESAPI (opts) {
this[kConfigurationError] = opts.ConfigurationError
${symbolsInstance}
}
${apisStr}
module.exports = ESAPI
`
// new line at the end of file
return { fn: fn + '\n', types: typesStr, kibanaTypes: kibanaTypesStr }
}
// from snake_case to camelCase
function camelify (str) {
return str.replace(/_([a-z])/g, k => k[1].toUpperCase())
}
function isSnakeCased (str) {
return !!~str.indexOf('_')
}
function toPascalCase (str) {
return str[0].toUpperCase() + str.slice(1)
}
function buildMethodDefinition (opts, api, name, hasBody, isHead, spec) {
const Name = toPascalCase(name)
const { content_type } = spec[Object.keys(spec)[0]].headers
const bodyType = content_type && content_type.includes('application/x-ndjson') ? 'RequestNDBody' : 'RequestBody'
const responseType = isHead ? 'boolean' : 'Record<string, any>'
const defaultBodyType = content_type && content_type.includes('application/x-ndjson') ? 'Record<string, any>[]' : 'Record<string, any>'
if (opts.kibana) {
if (hasBody) {
return [
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params?: RequestParams.${Name}<TRequestBody>, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' }
]
} else {
return [
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(params?: RequestParams.${Name}, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' }
]
}
}
if (hasBody) {
let methods = [
{ key: `${api}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params?: RequestParams.${Name}<TRequestBody>, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' },
{ key: `${api}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
{ key: `${api}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params: RequestParams.${Name}<TRequestBody>, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
{ key: `${api}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params: RequestParams.${Name}<TRequestBody>, options: TransportRequestOptions, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' }
]
if (isSnakeCased(api)) {
methods = methods.concat([
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params?: RequestParams.${Name}<TRequestBody>, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' },
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params: RequestParams.${Name}<TRequestBody>, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params: RequestParams.${Name}<TRequestBody>, options: TransportRequestOptions, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' }
])
}
return methods
} else {
let methods = [
{ key: `${api}<TResponse = ${responseType}, TContext = Context>(params?: RequestParams.${Name}, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' },
{ key: `${api}<TResponse = ${responseType}, TContext = Context>(callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
{ key: `${api}<TResponse = ${responseType}, TContext = Context>(params: RequestParams.${Name}, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
{ key: `${api}<TResponse = ${responseType}, TContext = Context>(params: RequestParams.${Name}, options: TransportRequestOptions, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' }
]
if (isSnakeCased(api)) {
methods = methods.concat([
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(params?: RequestParams.${Name}, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' },
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(params: RequestParams.${Name}, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(params: RequestParams.${Name}, options: TransportRequestOptions, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' }
])
}
return methods
}
}
function hasBody (spec, api) {
return !!spec[api].body
}
function isHeadMethod (spec, api) {
const { paths } = spec[api].url
const methods = []
for (const path of paths) {
for (const method of path.methods) {
if (!methods.includes(method)) {
methods.push(method)
}
}
}
return methods.length === 1 && methods[0] === 'HEAD'
}
function readSpec (specFolder, file) {
try {
return require(join(specFolder, file))
} catch (err) {
throw new Error(`Cannot read spec file ${file}`)
}
}
module.exports = genFactory

View File

@ -1,191 +0,0 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* eslint camelcase: 0 */
'use strict'
const deprecatedParameters = require('./patch.json')
function generate (version, api) {
const release = version.charAt(0)
let types = `/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { RequestBody, RequestNDBody } from '../lib/Transport'
export interface Generic {
method?: string;
filter_path?: string | string[];
pretty?: boolean;
human?: boolean;
error_trace?: boolean;
source?: string;
}
`
api.forEach(generateRequestType)
return types
function generateRequestType (spec) {
const api = Object.keys(spec)[0]
const name = api
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
.replace(/_([a-z])/g, k => k[1].toUpperCase())
const { paths = {} } = spec[api].url
const { body, params = {} } = spec[api]
// get the required parts from the url
// if the url has at least one static path,
// then there are not required parts of the url
let allParts = []
let requiredParts = []
for (const path of paths) {
if (path.parts) {
allParts.push(Object.keys(path.parts))
} else {
allParts = []
break
}
}
if (allParts.length > 0) {
requiredParts = intersect(...allParts)
}
const parts = paths.reduce((acc, path) => {
if (!path.parts) return acc
for (const part in path.parts) {
if (acc[part] != null) continue
acc[part] = { key: part, value: path.parts[part], required: requiredParts.includes(part) }
}
return acc
}, {})
const deprecatedParametersToAdd = []
const paramsArr = Object.keys(params)
.filter(k => !Object.keys(parts).includes(k))
.map(k => {
if (deprecatedParameters[release] && deprecatedParameters[release][k]) {
deprecatedParametersToAdd.push({
key: deprecatedParameters[release][k],
value: params[k],
required: params[k].required
})
}
return { key: k, value: params[k], required: params[k].required }
})
const partsArr = Object.keys(parts).map(k => parts[k])
deprecatedParametersToAdd.forEach(k => partsArr.push(k))
const genLine = e => {
const optional = e.required ? '' : '?'
return `${e.key}${optional}: ${getType(e.value.type, e.value.options)};`
}
const { content_type } = spec[api].headers
const bodyGeneric = content_type && content_type.includes('application/x-ndjson') ? 'RequestNDBody' : 'RequestBody'
const code = `
export interface ${toPascalCase(name)}${body ? `<T = ${bodyGeneric}>` : ''} extends Generic {
${partsArr.map(genLine).join('\n ')}
${paramsArr.map(genLine).join('\n ')}
${body ? `body${body.required ? '' : '?'}: T;` : ''}
}
`
types += '\n'
// remove empty lines
types += code.replace(/^\s*\n/gm, '')
}
function getType (type, options) {
switch (type) {
case 'list':
return 'string | string[]'
case 'date':
case 'time':
case 'timeout':
return 'string'
case 'enum': {
// the following code changes 'true' | 'false' to boolean
let foundTrue = false
let foundFalse = false
options = options
.map(k => {
if (k === 'true') {
foundTrue = true
return true
} else if (k === 'false') {
foundFalse = true
return false
} else {
return `'${k}'`
}
})
.filter(k => {
if (foundTrue && foundFalse && (k === true || k === false)) {
return false
}
return true
})
if (foundTrue && foundFalse) {
options.push('boolean')
}
return options.join(' | ')
}
case 'int':
case 'double':
case 'long':
return 'number'
case 'boolean|long':
return 'boolean | number'
default:
return type
}
}
}
function intersect (first, ...rest) {
return rest.reduce((accum, current) => {
return accum.filter(x => current.indexOf(x) !== -1)
}, first)
}
function toPascalCase (str) {
return str[0].toUpperCase() + str.slice(1)
}
module.exports = generate

View File

@ -1,34 +0,0 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict'
const generate = require('./generateApis')
const cloneAndCheckout = require('./clone-es')
const genFactory = require('./generateMain')
const generateDocs = require('./generateDocs')
const generateRequestTypes = require('./generateRequestTypes')
module.exports = {
generate,
cloneAndCheckout,
genFactory,
generateDocs,
generateRequestTypes
}

View File

@ -1,14 +0,0 @@
{
"6": {
"_source_includes": "_source_include",
"_source_excludes": "_source_exclude"
},
"7": {
"_source_includes": "_source_include",
"_source_excludes": "_source_exclude"
},
"8": {
"_source_includes": "_source_include",
"_source_excludes": "_source_exclude"
}
}

View File

@ -1,21 +0,0 @@
#!/bin/bash
TEST_ES_SERVER=${TEST_ES_SERVER:-"http://localhost:9200"}
attempt_counter=0
max_attempts=5
url="${TEST_ES_SERVER}/_cluster/health?wait_for_status=green&timeout=50s"
echo "Waiting for Elasticsearch..."
while [[ "$(curl -s -o /dev/null -w ''%{http_code}'' --max-time 55 "$url")" != "200" ]]; do
if [ ${attempt_counter} -eq ${max_attempts} ];then
echo "\nCouldn't connect to Elasticsearch"
exit 1
fi
printf '.'
attempt_counter=$(($attempt_counter+1))
sleep 5
done
echo "\nReady"

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -166,7 +152,7 @@ export default class AsyncSearch {
/**
* Delete an async search. If the asynchronous search is still running, it is cancelled. Otherwise, the saved search results are deleted. If the Elasticsearch security features are enabled, the deletion of a specific async search is restricted to: the authenticated user that submitted the original search request; users that have the `cancel_task` cluster privilege.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-async-search-submit | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-async-search-submit | Elasticsearch API documentation}
*/
async delete (this: That, params: T.AsyncSearchDeleteRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.AsyncSearchDeleteResponse>
async delete (this: That, params: T.AsyncSearchDeleteRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.AsyncSearchDeleteResponse, unknown>>
@ -211,7 +197,7 @@ export default class AsyncSearch {
/**
* Get async search results. Retrieve the results of a previously submitted asynchronous search request. If the Elasticsearch security features are enabled, access to the results of a specific async search is restricted to the user or API key that submitted it.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-async-search-submit | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-async-search-submit | Elasticsearch API documentation}
*/
async get<TDocument = unknown, TAggregations = Record<T.AggregateName, T.AggregationsAggregate>> (this: That, params: T.AsyncSearchGetRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.AsyncSearchGetResponse<TDocument, TAggregations>>
async get<TDocument = unknown, TAggregations = Record<T.AggregateName, T.AggregationsAggregate>> (this: That, params: T.AsyncSearchGetRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.AsyncSearchGetResponse<TDocument, TAggregations>, unknown>>
@ -256,7 +242,7 @@ export default class AsyncSearch {
/**
* Get the async search status. Get the status of a previously submitted async search request given its identifier, without retrieving search results. If the Elasticsearch security features are enabled, the access to the status of a specific async search is restricted to: * The user or API key that submitted the original async search request. * Users that have the `monitor` cluster privilege or greater privileges.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-async-search-submit | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-async-search-submit | Elasticsearch API documentation}
*/
async status (this: That, params: T.AsyncSearchStatusRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.AsyncSearchStatusResponse>
async status (this: That, params: T.AsyncSearchStatusRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.AsyncSearchStatusResponse, unknown>>
@ -301,7 +287,7 @@ export default class AsyncSearch {
/**
* Run an async search. When the primary sort of the results is an indexed field, shards get sorted based on minimum and maximum value that they hold for that field. Partial results become available following the sort criteria that was requested. Warning: Asynchronous search does not support scroll or search requests that include only the suggest section. By default, Elasticsearch does not allow you to store an async search response larger than 10Mb and an attempt to do this results in an error. The maximum allowed size for a stored async search response can be set by changing the `search.max_async_search_response_size` cluster level setting.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-async-search-submit | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-async-search-submit | Elasticsearch API documentation}
*/
async submit<TDocument = unknown, TAggregations = Record<T.AggregateName, T.AggregationsAggregate>> (this: That, params?: T.AsyncSearchSubmitRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.AsyncSearchSubmitResponse<TDocument, TAggregations>>
async submit<TDocument = unknown, TAggregations = Record<T.AggregateName, T.AggregationsAggregate>> (this: That, params?: T.AsyncSearchSubmitRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.AsyncSearchSubmitResponse<TDocument, TAggregations>, unknown>>

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -92,7 +78,7 @@ export default class Autoscaling {
/**
* Delete an autoscaling policy. NOTE: This feature is designed for indirect use by Elasticsearch Service, Elastic Cloud Enterprise, and Elastic Cloud on Kubernetes. Direct use is not supported.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-autoscaling-delete-autoscaling-policy | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-autoscaling-delete-autoscaling-policy | Elasticsearch API documentation}
*/
async deleteAutoscalingPolicy (this: That, params: T.AutoscalingDeleteAutoscalingPolicyRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.AutoscalingDeleteAutoscalingPolicyResponse>
async deleteAutoscalingPolicy (this: That, params: T.AutoscalingDeleteAutoscalingPolicyRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.AutoscalingDeleteAutoscalingPolicyResponse, unknown>>
@ -137,7 +123,7 @@ export default class Autoscaling {
/**
* Get the autoscaling capacity. NOTE: This feature is designed for indirect use by Elasticsearch Service, Elastic Cloud Enterprise, and Elastic Cloud on Kubernetes. Direct use is not supported. This API gets the current autoscaling capacity based on the configured autoscaling policy. It will return information to size the cluster appropriately to the current workload. The `required_capacity` is calculated as the maximum of the `required_capacity` result of all individual deciders that are enabled for the policy. The operator should verify that the `current_nodes` match the operators knowledge of the cluster to avoid making autoscaling decisions based on stale or incomplete information. The response contains decider-specific information you can use to diagnose how and why autoscaling determined a certain capacity was required. This information is provided for diagnosis only. Do not use this information to make autoscaling decisions.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-autoscaling-get-autoscaling-capacity | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-autoscaling-get-autoscaling-capacity | Elasticsearch API documentation}
*/
async getAutoscalingCapacity (this: That, params?: T.AutoscalingGetAutoscalingCapacityRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.AutoscalingGetAutoscalingCapacityResponse>
async getAutoscalingCapacity (this: That, params?: T.AutoscalingGetAutoscalingCapacityRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.AutoscalingGetAutoscalingCapacityResponse, unknown>>
@ -180,7 +166,7 @@ export default class Autoscaling {
/**
* Get an autoscaling policy. NOTE: This feature is designed for indirect use by Elasticsearch Service, Elastic Cloud Enterprise, and Elastic Cloud on Kubernetes. Direct use is not supported.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-autoscaling-get-autoscaling-capacity | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-autoscaling-get-autoscaling-capacity | Elasticsearch API documentation}
*/
async getAutoscalingPolicy (this: That, params: T.AutoscalingGetAutoscalingPolicyRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.AutoscalingGetAutoscalingPolicyResponse>
async getAutoscalingPolicy (this: That, params: T.AutoscalingGetAutoscalingPolicyRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.AutoscalingGetAutoscalingPolicyResponse, unknown>>
@ -225,7 +211,7 @@ export default class Autoscaling {
/**
* Create or update an autoscaling policy. NOTE: This feature is designed for indirect use by Elasticsearch Service, Elastic Cloud Enterprise, and Elastic Cloud on Kubernetes. Direct use is not supported.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-autoscaling-put-autoscaling-policy | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-autoscaling-put-autoscaling-policy | Elasticsearch API documentation}
*/
async putAutoscalingPolicy (this: That, params: T.AutoscalingPutAutoscalingPolicyRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.AutoscalingPutAutoscalingPolicyResponse>
async putAutoscalingPolicy (this: That, params: T.AutoscalingPutAutoscalingPolicyRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.AutoscalingPutAutoscalingPolicyResponse, unknown>>

File diff suppressed because one or more lines are too long

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -369,7 +355,7 @@ export default class Cat {
/**
* Get aliases. Get the cluster's index aliases, including filter and routing information. This API does not return data stream aliases. IMPORTANT: CAT APIs are only intended for human consumption using the command line or the Kibana console. They are not intended for use by applications. For application consumption, use the aliases API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-aliases | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-aliases | Elasticsearch API documentation}
*/
async aliases (this: That, params?: T.CatAliasesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatAliasesResponse>
async aliases (this: That, params?: T.CatAliasesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatAliasesResponse, unknown>>
@ -422,7 +408,7 @@ export default class Cat {
/**
* Get shard allocation information. Get a snapshot of the number of shards allocated to each data node and their disk space. IMPORTANT: CAT APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-allocation | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-allocation | Elasticsearch API documentation}
*/
async allocation (this: That, params?: T.CatAllocationRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatAllocationResponse>
async allocation (this: That, params?: T.CatAllocationRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatAllocationResponse, unknown>>
@ -475,7 +461,7 @@ export default class Cat {
/**
* Get component templates. Get information about component templates in a cluster. Component templates are building blocks for constructing index templates that specify index mappings, settings, and aliases. IMPORTANT: CAT APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the get component template API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-component-templates | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-component-templates | Elasticsearch API documentation}
*/
async componentTemplates (this: That, params?: T.CatComponentTemplatesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatComponentTemplatesResponse>
async componentTemplates (this: That, params?: T.CatComponentTemplatesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatComponentTemplatesResponse, unknown>>
@ -528,7 +514,7 @@ export default class Cat {
/**
* Get a document count. Get quick access to a document count for a data stream, an index, or an entire cluster. The document count only includes live documents, not deleted documents which have not yet been removed by the merge process. IMPORTANT: CAT APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the count API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-count | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-count | Elasticsearch API documentation}
*/
async count (this: That, params?: T.CatCountRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatCountResponse>
async count (this: That, params?: T.CatCountRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatCountResponse, unknown>>
@ -581,7 +567,7 @@ export default class Cat {
/**
* Get field data cache information. Get the amount of heap memory currently used by the field data cache on every data node in the cluster. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the nodes stats API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-fielddata | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-fielddata | Elasticsearch API documentation}
*/
async fielddata (this: That, params?: T.CatFielddataRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatFielddataResponse>
async fielddata (this: That, params?: T.CatFielddataRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatFielddataResponse, unknown>>
@ -634,7 +620,7 @@ export default class Cat {
/**
* Get the cluster health status. IMPORTANT: CAT APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the cluster health API. This API is often used to check malfunctioning clusters. To help you track cluster health alongside log files and alerting systems, the API returns timestamps in two formats: `HH:MM:SS`, which is human-readable but includes no date information; `Unix epoch time`, which is machine-sortable and includes date information. The latter format is useful for cluster recoveries that take multiple days. You can use the cat health API to verify cluster health across multiple nodes. You also can use the API to track the recovery of a large cluster over a longer period of time.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-health | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-health | Elasticsearch API documentation}
*/
async health (this: That, params?: T.CatHealthRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatHealthResponse>
async health (this: That, params?: T.CatHealthRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatHealthResponse, unknown>>
@ -677,7 +663,7 @@ export default class Cat {
/**
* Get CAT help. Get help for the CAT APIs.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/group/endpoint-cat | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/group/endpoint-cat | Elasticsearch API documentation}
*/
async help (this: That, params?: T.CatHelpRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatHelpResponse>
async help (this: That, params?: T.CatHelpRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatHelpResponse, unknown>>
@ -720,7 +706,7 @@ export default class Cat {
/**
* Get index information. Get high-level information about indices in a cluster, including backing indices for data streams. Use this request to get the following information for each index in a cluster: - shard count - document count - deleted document count - primary store size - total store size of all shards, including shard replicas These metrics are retrieved directly from Lucene, which Elasticsearch uses internally to power indexing and search. As a result, all document counts include hidden nested documents. To get an accurate count of Elasticsearch documents, use the cat count or count APIs. CAT APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use an index endpoint.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-indices | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-indices | Elasticsearch API documentation}
*/
async indices (this: That, params?: T.CatIndicesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatIndicesResponse>
async indices (this: That, params?: T.CatIndicesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatIndicesResponse, unknown>>
@ -773,7 +759,7 @@ export default class Cat {
/**
* Get master node information. Get information about the master node, including the ID, bound IP address, and name. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the nodes info API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-master | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-master | Elasticsearch API documentation}
*/
async master (this: That, params?: T.CatMasterRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMasterResponse>
async master (this: That, params?: T.CatMasterRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMasterResponse, unknown>>
@ -816,7 +802,7 @@ export default class Cat {
/**
* Get data frame analytics jobs. Get configuration and usage information about data frame analytics jobs. IMPORTANT: CAT APIs are only intended for human consumption using the Kibana console or command line. They are not intended for use by applications. For application consumption, use the get data frame analytics jobs statistics API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-ml-data-frame-analytics | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-ml-data-frame-analytics | Elasticsearch API documentation}
*/
async mlDataFrameAnalytics (this: That, params?: T.CatMlDataFrameAnalyticsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMlDataFrameAnalyticsResponse>
async mlDataFrameAnalytics (this: That, params?: T.CatMlDataFrameAnalyticsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMlDataFrameAnalyticsResponse, unknown>>
@ -869,7 +855,7 @@ export default class Cat {
/**
* Get datafeeds. Get configuration and usage information about datafeeds. This API returns a maximum of 10,000 datafeeds. If the Elasticsearch security features are enabled, you must have `monitor_ml`, `monitor`, `manage_ml`, or `manage` cluster privileges to use this API. IMPORTANT: CAT APIs are only intended for human consumption using the Kibana console or command line. They are not intended for use by applications. For application consumption, use the get datafeed statistics API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-ml-datafeeds | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-ml-datafeeds | Elasticsearch API documentation}
*/
async mlDatafeeds (this: That, params?: T.CatMlDatafeedsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMlDatafeedsResponse>
async mlDatafeeds (this: That, params?: T.CatMlDatafeedsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMlDatafeedsResponse, unknown>>
@ -922,7 +908,7 @@ export default class Cat {
/**
* Get anomaly detection jobs. Get configuration and usage information for anomaly detection jobs. This API returns a maximum of 10,000 jobs. If the Elasticsearch security features are enabled, you must have `monitor_ml`, `monitor`, `manage_ml`, or `manage` cluster privileges to use this API. IMPORTANT: CAT APIs are only intended for human consumption using the Kibana console or command line. They are not intended for use by applications. For application consumption, use the get anomaly detection job statistics API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-ml-jobs | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-ml-jobs | Elasticsearch API documentation}
*/
async mlJobs (this: That, params?: T.CatMlJobsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMlJobsResponse>
async mlJobs (this: That, params?: T.CatMlJobsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMlJobsResponse, unknown>>
@ -975,7 +961,7 @@ export default class Cat {
/**
* Get trained models. Get configuration and usage information about inference trained models. IMPORTANT: CAT APIs are only intended for human consumption using the Kibana console or command line. They are not intended for use by applications. For application consumption, use the get trained models statistics API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-ml-trained-models | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-ml-trained-models | Elasticsearch API documentation}
*/
async mlTrainedModels (this: That, params?: T.CatMlTrainedModelsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMlTrainedModelsResponse>
async mlTrainedModels (this: That, params?: T.CatMlTrainedModelsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMlTrainedModelsResponse, unknown>>
@ -1028,7 +1014,7 @@ export default class Cat {
/**
* Get node attribute information. Get information about custom node attributes. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the nodes info API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-nodeattrs | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-nodeattrs | Elasticsearch API documentation}
*/
async nodeattrs (this: That, params?: T.CatNodeattrsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatNodeattrsResponse>
async nodeattrs (this: That, params?: T.CatNodeattrsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatNodeattrsResponse, unknown>>
@ -1071,7 +1057,7 @@ export default class Cat {
/**
* Get node information. Get information about the nodes in a cluster. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the nodes info API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-nodes | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-nodes | Elasticsearch API documentation}
*/
async nodes (this: That, params?: T.CatNodesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatNodesResponse>
async nodes (this: That, params?: T.CatNodesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatNodesResponse, unknown>>
@ -1114,7 +1100,7 @@ export default class Cat {
/**
* Get pending task information. Get information about cluster-level changes that have not yet taken effect. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the pending cluster tasks API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-pending-tasks | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-pending-tasks | Elasticsearch API documentation}
*/
async pendingTasks (this: That, params?: T.CatPendingTasksRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatPendingTasksResponse>
async pendingTasks (this: That, params?: T.CatPendingTasksRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatPendingTasksResponse, unknown>>
@ -1157,7 +1143,7 @@ export default class Cat {
/**
* Get plugin information. Get a list of plugins running on each node of a cluster. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the nodes info API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-plugins | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-plugins | Elasticsearch API documentation}
*/
async plugins (this: That, params?: T.CatPluginsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatPluginsResponse>
async plugins (this: That, params?: T.CatPluginsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatPluginsResponse, unknown>>
@ -1200,7 +1186,7 @@ export default class Cat {
/**
* Get shard recovery information. Get information about ongoing and completed shard recoveries. Shard recovery is the process of initializing a shard copy, such as restoring a primary shard from a snapshot or syncing a replica shard from a primary shard. When a shard recovery completes, the recovered shard is available for search and indexing. For data streams, the API returns information about the streams backing indices. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the index recovery API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-recovery | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-recovery | Elasticsearch API documentation}
*/
async recovery (this: That, params?: T.CatRecoveryRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatRecoveryResponse>
async recovery (this: That, params?: T.CatRecoveryRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatRecoveryResponse, unknown>>
@ -1253,7 +1239,7 @@ export default class Cat {
/**
* Get snapshot repository information. Get a list of snapshot repositories for a cluster. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the get snapshot repository API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-repositories | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-repositories | Elasticsearch API documentation}
*/
async repositories (this: That, params?: T.CatRepositoriesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatRepositoriesResponse>
async repositories (this: That, params?: T.CatRepositoriesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatRepositoriesResponse, unknown>>
@ -1296,7 +1282,7 @@ export default class Cat {
/**
* Get segment information. Get low-level information about the Lucene segments in index shards. For data streams, the API returns information about the backing indices. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the index segments API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-segments | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-segments | Elasticsearch API documentation}
*/
async segments (this: That, params?: T.CatSegmentsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatSegmentsResponse>
async segments (this: That, params?: T.CatSegmentsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatSegmentsResponse, unknown>>
@ -1349,7 +1335,7 @@ export default class Cat {
/**
* Get shard information. Get information about the shards in a cluster. For data streams, the API returns information about the backing indices. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-shards | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-shards | Elasticsearch API documentation}
*/
async shards (this: That, params?: T.CatShardsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatShardsResponse>
async shards (this: That, params?: T.CatShardsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatShardsResponse, unknown>>
@ -1402,7 +1388,7 @@ export default class Cat {
/**
* Get snapshot information. Get information about the snapshots stored in one or more repositories. A snapshot is a backup of an index or running Elasticsearch cluster. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the get snapshot API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-snapshots | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-snapshots | Elasticsearch API documentation}
*/
async snapshots (this: That, params?: T.CatSnapshotsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatSnapshotsResponse>
async snapshots (this: That, params?: T.CatSnapshotsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatSnapshotsResponse, unknown>>
@ -1455,7 +1441,7 @@ export default class Cat {
/**
* Get task information. Get information about tasks currently running in the cluster. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the task management API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-tasks | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-tasks | Elasticsearch API documentation}
*/
async tasks (this: That, params?: T.CatTasksRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatTasksResponse>
async tasks (this: That, params?: T.CatTasksRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatTasksResponse, unknown>>
@ -1498,7 +1484,7 @@ export default class Cat {
/**
* Get index template information. Get information about the index templates in a cluster. You can use index templates to apply index settings and field mappings to new indices at creation. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the get index template API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-templates | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-templates | Elasticsearch API documentation}
*/
async templates (this: That, params?: T.CatTemplatesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatTemplatesResponse>
async templates (this: That, params?: T.CatTemplatesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatTemplatesResponse, unknown>>
@ -1551,7 +1537,7 @@ export default class Cat {
/**
* Get thread pool statistics. Get thread pool statistics for each node in a cluster. Returned information includes all built-in thread pools and custom thread pools. IMPORTANT: cat APIs are only intended for human consumption using the command line or Kibana console. They are not intended for use by applications. For application consumption, use the nodes info API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-thread-pool | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-thread-pool | Elasticsearch API documentation}
*/
async threadPool (this: That, params?: T.CatThreadPoolRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatThreadPoolResponse>
async threadPool (this: That, params?: T.CatThreadPoolRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatThreadPoolResponse, unknown>>
@ -1604,7 +1590,7 @@ export default class Cat {
/**
* Get transform information. Get configuration and usage information about transforms. CAT APIs are only intended for human consumption using the Kibana console or command line. They are not intended for use by applications. For application consumption, use the get transform statistics API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cat-transforms | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cat-transforms | Elasticsearch API documentation}
*/
async transforms (this: That, params?: T.CatTransformsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatTransformsResponse>
async transforms (this: That, params?: T.CatTransformsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatTransformsResponse, unknown>>

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -218,7 +204,7 @@ export default class Ccr {
/**
* Delete auto-follow patterns. Delete a collection of cross-cluster replication auto-follow patterns.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-delete-auto-follow-pattern | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-delete-auto-follow-pattern | Elasticsearch API documentation}
*/
async deleteAutoFollowPattern (this: That, params: T.CcrDeleteAutoFollowPatternRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrDeleteAutoFollowPatternResponse>
async deleteAutoFollowPattern (this: That, params: T.CcrDeleteAutoFollowPatternRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrDeleteAutoFollowPatternResponse, unknown>>
@ -263,7 +249,7 @@ export default class Ccr {
/**
* Create a follower. Create a cross-cluster replication follower index that follows a specific leader index. When the API returns, the follower index exists and cross-cluster replication starts replicating operations from the leader index to the follower index.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-follow | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-follow | Elasticsearch API documentation}
*/
async follow (this: That, params: T.CcrFollowRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrFollowResponse>
async follow (this: That, params: T.CcrFollowRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrFollowResponse, unknown>>
@ -320,7 +306,7 @@ export default class Ccr {
/**
* Get follower information. Get information about all cross-cluster replication follower indices. For example, the results include follower index names, leader index names, replication options, and whether the follower indices are active or paused.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-follow-info | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-follow-info | Elasticsearch API documentation}
*/
async followInfo (this: That, params: T.CcrFollowInfoRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrFollowInfoResponse>
async followInfo (this: That, params: T.CcrFollowInfoRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrFollowInfoResponse, unknown>>
@ -365,7 +351,7 @@ export default class Ccr {
/**
* Get follower stats. Get cross-cluster replication follower stats. The API returns shard-level stats about the "following tasks" associated with each shard for the specified indices.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-follow-stats | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-follow-stats | Elasticsearch API documentation}
*/
async followStats (this: That, params: T.CcrFollowStatsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrFollowStatsResponse>
async followStats (this: That, params: T.CcrFollowStatsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrFollowStatsResponse, unknown>>
@ -410,7 +396,7 @@ export default class Ccr {
/**
* Forget a follower. Remove the cross-cluster replication follower retention leases from the leader. A following index takes out retention leases on its leader index. These leases are used to increase the likelihood that the shards of the leader index retain the history of operations that the shards of the following index need to run replication. When a follower index is converted to a regular index by the unfollow API (either by directly calling the API or by index lifecycle management tasks), these leases are removed. However, removal of the leases can fail, for example when the remote cluster containing the leader index is unavailable. While the leases will eventually expire on their own, their extended existence can cause the leader index to hold more history than necessary and prevent index lifecycle management from performing some operations on the leader index. This API exists to enable manually removing the leases when the unfollow API is unable to do so. NOTE: This API does not stop replication by a following index. If you use this API with a follower index that is still actively following, the following index will add back retention leases on the leader. The only purpose of this API is to handle the case of failure to remove the following retention leases after the unfollow API is invoked.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-forget-follower | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-forget-follower | Elasticsearch API documentation}
*/
async forgetFollower (this: That, params: T.CcrForgetFollowerRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrForgetFollowerResponse>
async forgetFollower (this: That, params: T.CcrForgetFollowerRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrForgetFollowerResponse, unknown>>
@ -467,7 +453,7 @@ export default class Ccr {
/**
* Get auto-follow patterns. Get cross-cluster replication auto-follow patterns.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-get-auto-follow-pattern-1 | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-get-auto-follow-pattern-1 | Elasticsearch API documentation}
*/
async getAutoFollowPattern (this: That, params?: T.CcrGetAutoFollowPatternRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrGetAutoFollowPatternResponse>
async getAutoFollowPattern (this: That, params?: T.CcrGetAutoFollowPatternRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrGetAutoFollowPatternResponse, unknown>>
@ -520,7 +506,7 @@ export default class Ccr {
/**
* Pause an auto-follow pattern. Pause a cross-cluster replication auto-follow pattern. When the API returns, the auto-follow pattern is inactive. New indices that are created on the remote cluster and match the auto-follow patterns are ignored. You can resume auto-following with the resume auto-follow pattern API. When it resumes, the auto-follow pattern is active again and automatically configures follower indices for newly created indices on the remote cluster that match its patterns. Remote indices that were created while the pattern was paused will also be followed, unless they have been deleted or closed in the interim.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-pause-auto-follow-pattern | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-pause-auto-follow-pattern | Elasticsearch API documentation}
*/
async pauseAutoFollowPattern (this: That, params: T.CcrPauseAutoFollowPatternRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrPauseAutoFollowPatternResponse>
async pauseAutoFollowPattern (this: That, params: T.CcrPauseAutoFollowPatternRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrPauseAutoFollowPatternResponse, unknown>>
@ -565,7 +551,7 @@ export default class Ccr {
/**
* Pause a follower. Pause a cross-cluster replication follower index. The follower index will not fetch any additional operations from the leader index. You can resume following with the resume follower API. You can pause and resume a follower index to change the configuration of the following task.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-pause-follow | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-pause-follow | Elasticsearch API documentation}
*/
async pauseFollow (this: That, params: T.CcrPauseFollowRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrPauseFollowResponse>
async pauseFollow (this: That, params: T.CcrPauseFollowRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrPauseFollowResponse, unknown>>
@ -610,7 +596,7 @@ export default class Ccr {
/**
* Create or update auto-follow patterns. Create a collection of cross-cluster replication auto-follow patterns for a remote cluster. Newly created indices on the remote cluster that match any of the patterns are automatically configured as follower indices. Indices on the remote cluster that were created before the auto-follow pattern was created will not be auto-followed even if they match the pattern. This API can also be used to update auto-follow patterns. NOTE: Follower indices that were configured automatically before updating an auto-follow pattern will remain unchanged even if they do not match against the new patterns.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-put-auto-follow-pattern | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-put-auto-follow-pattern | Elasticsearch API documentation}
*/
async putAutoFollowPattern (this: That, params: T.CcrPutAutoFollowPatternRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrPutAutoFollowPatternResponse>
async putAutoFollowPattern (this: That, params: T.CcrPutAutoFollowPatternRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrPutAutoFollowPatternResponse, unknown>>
@ -667,7 +653,7 @@ export default class Ccr {
/**
* Resume an auto-follow pattern. Resume a cross-cluster replication auto-follow pattern that was paused. The auto-follow pattern will resume configuring following indices for newly created indices that match its patterns on the remote cluster. Remote indices created while the pattern was paused will also be followed unless they have been deleted or closed in the interim.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-resume-auto-follow-pattern | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-resume-auto-follow-pattern | Elasticsearch API documentation}
*/
async resumeAutoFollowPattern (this: That, params: T.CcrResumeAutoFollowPatternRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrResumeAutoFollowPatternResponse>
async resumeAutoFollowPattern (this: That, params: T.CcrResumeAutoFollowPatternRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrResumeAutoFollowPatternResponse, unknown>>
@ -712,7 +698,7 @@ export default class Ccr {
/**
* Resume a follower. Resume a cross-cluster replication follower index that was paused. The follower index could have been paused with the pause follower API. Alternatively it could be paused due to replication that cannot be retried due to failures during following tasks. When this API returns, the follower index will resume fetching operations from the leader index.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-resume-follow | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-resume-follow | Elasticsearch API documentation}
*/
async resumeFollow (this: That, params: T.CcrResumeFollowRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrResumeFollowResponse>
async resumeFollow (this: That, params: T.CcrResumeFollowRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrResumeFollowResponse, unknown>>
@ -769,7 +755,7 @@ export default class Ccr {
/**
* Get cross-cluster replication stats. This API returns stats about auto-following and the same shard-level stats as the get follower stats API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-stats | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-stats | Elasticsearch API documentation}
*/
async stats (this: That, params?: T.CcrStatsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrStatsResponse>
async stats (this: That, params?: T.CcrStatsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrStatsResponse, unknown>>
@ -812,7 +798,7 @@ export default class Ccr {
/**
* Unfollow an index. Convert a cross-cluster replication follower index to a regular index. The API stops the following task associated with a follower index and removes index metadata and settings associated with cross-cluster replication. The follower index must be paused and closed before you call the unfollow API. > info > Currently cross-cluster replication does not support converting an existing regular index to a follower index. Converting a follower index to a regular index is an irreversible operation.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-ccr-unfollow | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-ccr-unfollow | Elasticsearch API documentation}
*/
async unfollow (this: That, params: T.CcrUnfollowRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CcrUnfollowResponse>
async unfollow (this: That, params: T.CcrUnfollowRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CcrUnfollowResponse, unknown>>

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -54,7 +40,7 @@ const acceptedParams: Record<string, { path: string[], body: string[], query: st
/**
* Clear a scrolling search. Clear the search context and results for a scrolling search.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-clear-scroll | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-clear-scroll | Elasticsearch API documentation}
*/
export default async function ClearScrollApi (this: That, params?: T.ClearScrollRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClearScrollResponse>
export default async function ClearScrollApi (this: That, params?: T.ClearScrollRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClearScrollResponse, unknown>>

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -54,7 +40,7 @@ const acceptedParams: Record<string, { path: string[], body: string[], query: st
/**
* Close a point in time. A point in time must be opened explicitly before being used in search requests. The `keep_alive` parameter tells Elasticsearch how long it should persist. A point in time is automatically closed when the `keep_alive` period has elapsed. However, keeping points in time has a cost; close them as soon as they are no longer required for search requests.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-open-point-in-time | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-open-point-in-time | Elasticsearch API documentation}
*/
export default async function ClosePointInTimeApi (this: That, params: T.ClosePointInTimeRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClosePointInTimeResponse>
export default async function ClosePointInTimeApi (this: That, params: T.ClosePointInTimeRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClosePointInTimeResponse, unknown>>

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -235,7 +221,7 @@ export default class Cluster {
/**
* Explain the shard allocations. Get explanations for shard allocations in the cluster. For unassigned shards, it provides an explanation for why the shard is unassigned. For assigned shards, it provides an explanation for why the shard is remaining on its current node and has not moved or rebalanced to another node. This API can be very useful when attempting to diagnose why a shard is unassigned or why a shard continues to remain on its current node when you might expect otherwise.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-allocation-explain | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-allocation-explain | Elasticsearch API documentation}
*/
async allocationExplain (this: That, params?: T.ClusterAllocationExplainRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterAllocationExplainResponse>
async allocationExplain (this: That, params?: T.ClusterAllocationExplainRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterAllocationExplainResponse, unknown>>
@ -290,7 +276,7 @@ export default class Cluster {
/**
* Delete component templates. Component templates are building blocks for constructing index templates that specify index mappings, settings, and aliases.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-put-component-template | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-put-component-template | Elasticsearch API documentation}
*/
async deleteComponentTemplate (this: That, params: T.ClusterDeleteComponentTemplateRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterDeleteComponentTemplateResponse>
async deleteComponentTemplate (this: That, params: T.ClusterDeleteComponentTemplateRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterDeleteComponentTemplateResponse, unknown>>
@ -335,7 +321,7 @@ export default class Cluster {
/**
* Clear cluster voting config exclusions. Remove master-eligible nodes from the voting configuration exclusion list.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-post-voting-config-exclusions | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-post-voting-config-exclusions | Elasticsearch API documentation}
*/
async deleteVotingConfigExclusions (this: That, params?: T.ClusterDeleteVotingConfigExclusionsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterDeleteVotingConfigExclusionsResponse>
async deleteVotingConfigExclusions (this: That, params?: T.ClusterDeleteVotingConfigExclusionsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterDeleteVotingConfigExclusionsResponse, unknown>>
@ -378,7 +364,7 @@ export default class Cluster {
/**
* Check component templates. Returns information about whether a particular component template exists.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-put-component-template | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-put-component-template | Elasticsearch API documentation}
*/
async existsComponentTemplate (this: That, params: T.ClusterExistsComponentTemplateRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterExistsComponentTemplateResponse>
async existsComponentTemplate (this: That, params: T.ClusterExistsComponentTemplateRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterExistsComponentTemplateResponse, unknown>>
@ -423,7 +409,7 @@ export default class Cluster {
/**
* Get component templates. Get information about component templates.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-put-component-template | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-put-component-template | Elasticsearch API documentation}
*/
async getComponentTemplate (this: That, params?: T.ClusterGetComponentTemplateRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterGetComponentTemplateResponse>
async getComponentTemplate (this: That, params?: T.ClusterGetComponentTemplateRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterGetComponentTemplateResponse, unknown>>
@ -476,7 +462,7 @@ export default class Cluster {
/**
* Get cluster-wide settings. By default, it returns only settings that have been explicitly defined.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-get-settings | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-get-settings | Elasticsearch API documentation}
*/
async getSettings (this: That, params?: T.ClusterGetSettingsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterGetSettingsResponse>
async getSettings (this: That, params?: T.ClusterGetSettingsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterGetSettingsResponse, unknown>>
@ -519,7 +505,7 @@ export default class Cluster {
/**
* Get the cluster health status. You can also use the API to get the health status of only specified data streams and indices. For data streams, the API retrieves the health status of the streams backing indices. The cluster health status is: green, yellow or red. On the shard level, a red status indicates that the specific shard is not allocated in the cluster. Yellow means that the primary shard is allocated but replicas are not. Green means that all shards are allocated. The index level status is controlled by the worst shard status. One of the main benefits of the API is the ability to wait until the cluster reaches a certain high watermark health level. The cluster status is controlled by the worst index status.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-health | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-health | Elasticsearch API documentation}
*/
async health (this: That, params?: T.ClusterHealthRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterHealthResponse>
async health (this: That, params?: T.ClusterHealthRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterHealthResponse, unknown>>
@ -572,7 +558,7 @@ export default class Cluster {
/**
* Get cluster info. Returns basic information about the cluster.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-info | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-info | Elasticsearch API documentation}
*/
async info (this: That, params: T.ClusterInfoRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterInfoResponse>
async info (this: That, params: T.ClusterInfoRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterInfoResponse, unknown>>
@ -617,7 +603,7 @@ export default class Cluster {
/**
* Get the pending cluster tasks. Get information about cluster-level changes (such as create index, update mapping, allocate or fail shard) that have not yet taken effect. NOTE: This API returns a list of any pending updates to the cluster state. These are distinct from the tasks reported by the task management API which include periodic tasks and tasks initiated by the user, such as node stats, search queries, or create index requests. However, if a user-initiated task such as a create index command causes a cluster state update, the activity of this task might be reported by both task api and pending cluster tasks API.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-pending-tasks | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-pending-tasks | Elasticsearch API documentation}
*/
async pendingTasks (this: That, params?: T.ClusterPendingTasksRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterPendingTasksResponse>
async pendingTasks (this: That, params?: T.ClusterPendingTasksRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterPendingTasksResponse, unknown>>
@ -660,7 +646,7 @@ export default class Cluster {
/**
* Update voting configuration exclusions. Update the cluster voting config exclusions by node IDs or node names. By default, if there are more than three master-eligible nodes in the cluster and you remove fewer than half of the master-eligible nodes in the cluster at once, the voting configuration automatically shrinks. If you want to shrink the voting configuration to contain fewer than three nodes or to remove half or more of the master-eligible nodes in the cluster at once, use this API to remove departing nodes from the voting configuration manually. The API adds an entry for each specified node to the clusters voting configuration exclusions list. It then waits until the cluster has reconfigured its voting configuration to exclude the specified nodes. Clusters should have no voting configuration exclusions in normal operation. Once the excluded nodes have stopped, clear the voting configuration exclusions with `DELETE /_cluster/voting_config_exclusions`. This API waits for the nodes to be fully removed from the cluster before it returns. If your cluster has voting configuration exclusions for nodes that you no longer intend to remove, use `DELETE /_cluster/voting_config_exclusions?wait_for_removal=false` to clear the voting configuration exclusions without waiting for the nodes to leave the cluster. A response to `POST /_cluster/voting_config_exclusions` with an HTTP status code of 200 OK guarantees that the node has been removed from the voting configuration and will not be reinstated until the voting configuration exclusions are cleared by calling `DELETE /_cluster/voting_config_exclusions`. If the call to `POST /_cluster/voting_config_exclusions` fails or returns a response with an HTTP status code other than 200 OK then the node may not have been removed from the voting configuration. In that case, you may safely retry the call. NOTE: Voting exclusions are required only when you remove at least half of the master-eligible nodes from a cluster in a short time period. They are not required when removing master-ineligible nodes or when removing fewer than half of the master-eligible nodes.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-post-voting-config-exclusions | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-post-voting-config-exclusions | Elasticsearch API documentation}
*/
async postVotingConfigExclusions (this: That, params?: T.ClusterPostVotingConfigExclusionsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterPostVotingConfigExclusionsResponse>
async postVotingConfigExclusions (this: That, params?: T.ClusterPostVotingConfigExclusionsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterPostVotingConfigExclusionsResponse, unknown>>
@ -703,7 +689,7 @@ export default class Cluster {
/**
* Create or update a component template. Component templates are building blocks for constructing index templates that specify index mappings, settings, and aliases. An index template can be composed of multiple component templates. To use a component template, specify it in an index templates `composed_of` list. Component templates are only applied to new data streams and indices as part of a matching index template. Settings and mappings specified directly in the index template or the create index request override any settings or mappings specified in a component template. Component templates are only used during index creation. For data streams, this includes data stream creation and the creation of a streams backing indices. Changes to component templates do not affect existing indices, including a streams backing indices. You can use C-style `/* *\/` block comments in component templates. You can include comments anywhere in the request body except before the opening curly bracket. **Applying component templates** You cannot directly apply a component template to a data stream or index. To be applied, a component template must be included in an index template's `composed_of` list.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-put-component-template | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-put-component-template | Elasticsearch API documentation}
*/
async putComponentTemplate (this: That, params: T.ClusterPutComponentTemplateRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterPutComponentTemplateResponse>
async putComponentTemplate (this: That, params: T.ClusterPutComponentTemplateRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterPutComponentTemplateResponse, unknown>>
@ -760,7 +746,7 @@ export default class Cluster {
/**
* Update the cluster settings. Configure and update dynamic settings on a running cluster. You can also configure dynamic settings locally on an unstarted or shut down node in `elasticsearch.yml`. Updates made with this API can be persistent, which apply across cluster restarts, or transient, which reset after a cluster restart. You can also reset transient or persistent settings by assigning them a null value. If you configure the same setting using multiple methods, Elasticsearch applies the settings in following order of precedence: 1) Transient setting; 2) Persistent setting; 3) `elasticsearch.yml` setting; 4) Default setting value. For example, you can apply a transient setting to override a persistent setting or `elasticsearch.yml` setting. However, a change to an `elasticsearch.yml` setting will not override a defined transient or persistent setting. TIP: In Elastic Cloud, use the user settings feature to configure all cluster settings. This method automatically rejects unsafe settings that could break your cluster. If you run Elasticsearch on your own hardware, use this API to configure dynamic cluster settings. Only use `elasticsearch.yml` for static cluster settings and node settings. The API doesnt require a restart and ensures a settings value is the same on all nodes. WARNING: Transient cluster settings are no longer recommended. Use persistent cluster settings instead. If a cluster becomes unstable, transient settings can clear unexpectedly, resulting in a potentially undesired cluster configuration.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-put-settings | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-put-settings | Elasticsearch API documentation}
*/
async putSettings (this: That, params?: T.ClusterPutSettingsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterPutSettingsResponse>
async putSettings (this: That, params?: T.ClusterPutSettingsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterPutSettingsResponse, unknown>>
@ -815,7 +801,7 @@ export default class Cluster {
/**
* Get remote cluster information. Get information about configured remote clusters. The API returns connection and endpoint information keyed by the configured remote cluster alias. > info > This API returns information that reflects current state on the local cluster. > The `connected` field does not necessarily reflect whether a remote cluster is down or unavailable, only whether there is currently an open connection to it. > Elasticsearch does not spontaneously try to reconnect to a disconnected remote cluster. > To trigger a reconnection, attempt a cross-cluster search, ES|QL cross-cluster search, or try the [resolve cluster endpoint](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-resolve-cluster).
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-remote-info | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-remote-info | Elasticsearch API documentation}
*/
async remoteInfo (this: That, params?: T.ClusterRemoteInfoRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterRemoteInfoResponse>
async remoteInfo (this: That, params?: T.ClusterRemoteInfoRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterRemoteInfoResponse, unknown>>
@ -858,7 +844,7 @@ export default class Cluster {
/**
* Reroute the cluster. Manually change the allocation of individual shards in the cluster. For example, a shard can be moved from one node to another explicitly, an allocation can be canceled, and an unassigned shard can be explicitly allocated to a specific node. It is important to note that after processing any reroute commands Elasticsearch will perform rebalancing as normal (respecting the values of settings such as `cluster.routing.rebalance.enable`) in order to remain in a balanced state. For example, if the requested allocation includes moving a shard from node1 to node2 then this may cause a shard to be moved from node2 back to node1 to even things out. The cluster can be set to disable allocations using the `cluster.routing.allocation.enable` setting. If allocations are disabled then the only allocations that will be performed are explicit ones given using the reroute command, and consequent allocations due to rebalancing. The cluster will attempt to allocate a shard a maximum of `index.allocation.max_retries` times in a row (defaults to `5`), before giving up and leaving the shard unallocated. This scenario can be caused by structural problems such as having an analyzer which refers to a stopwords file which doesnt exist on all nodes. Once the problem has been corrected, allocation can be manually retried by calling the reroute API with the `?retry_failed` URI query parameter, which will attempt a single retry round for these shards.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-reroute | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-reroute | Elasticsearch API documentation}
*/
async reroute (this: That, params?: T.ClusterRerouteRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterRerouteResponse>
async reroute (this: That, params?: T.ClusterRerouteRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterRerouteResponse, unknown>>
@ -913,7 +899,7 @@ export default class Cluster {
/**
* Get the cluster state. Get comprehensive information about the state of the cluster. The cluster state is an internal data structure which keeps track of a variety of information needed by every node, including the identity and attributes of the other nodes in the cluster; cluster-wide settings; index metadata, including the mapping and settings for each index; the location and status of every shard copy in the cluster. The elected master node ensures that every node in the cluster has a copy of the same cluster state. This API lets you retrieve a representation of this internal state for debugging or diagnostic purposes. You may need to consult the Elasticsearch source code to determine the precise meaning of the response. By default the API will route requests to the elected master node since this node is the authoritative source of cluster states. You can also retrieve the cluster state held on the node handling the API request by adding the `?local=true` query parameter. Elasticsearch may need to expend significant effort to compute a response to this API in larger clusters, and the response may comprise a very large quantity of data. If you use this API repeatedly, your cluster may become unstable. WARNING: The response is a representation of an internal data structure. Its format is not subject to the same compatibility guarantees as other more stable APIs and may change from version to version. Do not query this API using external monitoring tools. Instead, obtain the information you require using other more stable cluster APIs.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-state | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-state | Elasticsearch API documentation}
*/
async state (this: That, params?: T.ClusterStateRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterStateResponse>
async state (this: That, params?: T.ClusterStateRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterStateResponse, unknown>>
@ -970,7 +956,7 @@ export default class Cluster {
/**
* Get cluster statistics. Get basic index metrics (shard numbers, store size, memory usage) and information about the current nodes that form the cluster (number, roles, os, jvm versions, memory usage, cpu and installed plugins).
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-cluster-stats | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-cluster-stats | Elasticsearch API documentation}
*/
async stats (this: That, params?: T.ClusterStatsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterStatsResponse>
async stats (this: That, params?: T.ClusterStatsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ClusterStatsResponse, unknown>>

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -375,7 +361,7 @@ export default class Connector {
/**
* Check in a connector. Update the `last_seen` field in the connector and set it to the current timestamp.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-check-in | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-check-in | Elasticsearch API documentation}
*/
async checkIn (this: That, params: T.ConnectorCheckInRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorCheckInResponse>
async checkIn (this: That, params: T.ConnectorCheckInRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorCheckInResponse, unknown>>
@ -420,7 +406,7 @@ export default class Connector {
/**
* Delete a connector. Removes a connector and associated sync jobs. This is a destructive action that is not recoverable. NOTE: This action doesnt delete any API keys, ingest pipelines, or data indices associated with the connector. These need to be removed manually.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-delete | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-delete | Elasticsearch API documentation}
*/
async delete (this: That, params: T.ConnectorDeleteRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorDeleteResponse>
async delete (this: That, params: T.ConnectorDeleteRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorDeleteResponse, unknown>>
@ -465,7 +451,7 @@ export default class Connector {
/**
* Get a connector. Get the details about a connector.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-get | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-get | Elasticsearch API documentation}
*/
async get (this: That, params: T.ConnectorGetRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorGetResponse>
async get (this: That, params: T.ConnectorGetRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorGetResponse, unknown>>
@ -510,7 +496,7 @@ export default class Connector {
/**
* Update the connector last sync stats. Update the fields related to the last sync of a connector. This action is used for analytics and monitoring.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-last-sync | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-last-sync | Elasticsearch API documentation}
*/
async lastSync (this: That, params: T.ConnectorLastSyncRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorLastSyncResponse>
async lastSync (this: That, params: T.ConnectorLastSyncRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorLastSyncResponse, unknown>>
@ -567,7 +553,7 @@ export default class Connector {
/**
* Get all connectors. Get information about all connectors.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-list | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-list | Elasticsearch API documentation}
*/
async list (this: That, params?: T.ConnectorListRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorListResponse>
async list (this: That, params?: T.ConnectorListRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorListResponse, unknown>>
@ -610,7 +596,7 @@ export default class Connector {
/**
* Create a connector. Connectors are Elasticsearch integrations that bring content from third-party data sources, which can be deployed on Elastic Cloud or hosted on your own infrastructure. Elastic managed connectors (Native connectors) are a managed service on Elastic Cloud. Self-managed connectors (Connector clients) are self-managed on your infrastructure.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-put | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-put | Elasticsearch API documentation}
*/
async post (this: That, params?: T.ConnectorPostRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorPostResponse>
async post (this: That, params?: T.ConnectorPostRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorPostResponse, unknown>>
@ -665,7 +651,7 @@ export default class Connector {
/**
* Create or update a connector.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-put | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-put | Elasticsearch API documentation}
*/
async put (this: That, params?: T.ConnectorPutRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorPutResponse>
async put (this: That, params?: T.ConnectorPutRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorPutResponse, unknown>>
@ -903,7 +889,7 @@ export default class Connector {
/**
* Cancel a connector sync job. Cancel a connector sync job, which sets the status to cancelling and updates `cancellation_requested_at` to the current time. The connector service is then responsible for setting the status of connector sync jobs to cancelled.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-sync-job-cancel | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-sync-job-cancel | Elasticsearch API documentation}
*/
async syncJobCancel (this: That, params: T.ConnectorSyncJobCancelRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorSyncJobCancelResponse>
async syncJobCancel (this: That, params: T.ConnectorSyncJobCancelRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorSyncJobCancelResponse, unknown>>
@ -948,7 +934,7 @@ export default class Connector {
/**
* Check in a connector sync job. Check in a connector sync job and set the `last_seen` field to the current time before updating it in the internal index. To sync data using self-managed connectors, you need to deploy the Elastic connector service on your own infrastructure. This service runs automatically on Elastic Cloud for Elastic managed connectors.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-sync-job-check-in | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-sync-job-check-in | Elasticsearch API documentation}
*/
async syncJobCheckIn (this: That, params: T.ConnectorSyncJobCheckInRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorSyncJobCheckInResponse>
async syncJobCheckIn (this: That, params: T.ConnectorSyncJobCheckInRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorSyncJobCheckInResponse, unknown>>
@ -993,7 +979,7 @@ export default class Connector {
/**
* Claim a connector sync job. This action updates the job status to `in_progress` and sets the `last_seen` and `started_at` timestamps to the current time. Additionally, it can set the `sync_cursor` property for the sync job. This API is not intended for direct connector management by users. It supports the implementation of services that utilize the connector protocol to communicate with Elasticsearch. To sync data using self-managed connectors, you need to deploy the Elastic connector service on your own infrastructure. This service runs automatically on Elastic Cloud for Elastic managed connectors.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-sync-job-claim | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-sync-job-claim | Elasticsearch API documentation}
*/
async syncJobClaim (this: That, params: T.ConnectorSyncJobClaimRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorSyncJobClaimResponse>
async syncJobClaim (this: That, params: T.ConnectorSyncJobClaimRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorSyncJobClaimResponse, unknown>>
@ -1050,7 +1036,7 @@ export default class Connector {
/**
* Delete a connector sync job. Remove a connector sync job and its associated data. This is a destructive action that is not recoverable.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-sync-job-delete | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-sync-job-delete | Elasticsearch API documentation}
*/
async syncJobDelete (this: That, params: T.ConnectorSyncJobDeleteRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorSyncJobDeleteResponse>
async syncJobDelete (this: That, params: T.ConnectorSyncJobDeleteRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorSyncJobDeleteResponse, unknown>>
@ -1095,7 +1081,7 @@ export default class Connector {
/**
* Set a connector sync job error. Set the `error` field for a connector sync job and set its `status` to `error`. To sync data using self-managed connectors, you need to deploy the Elastic connector service on your own infrastructure. This service runs automatically on Elastic Cloud for Elastic managed connectors.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-sync-job-error | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-sync-job-error | Elasticsearch API documentation}
*/
async syncJobError (this: That, params: T.ConnectorSyncJobErrorRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorSyncJobErrorResponse>
async syncJobError (this: That, params: T.ConnectorSyncJobErrorRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorSyncJobErrorResponse, unknown>>
@ -1152,7 +1138,7 @@ export default class Connector {
/**
* Get a connector sync job.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-sync-job-get | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-sync-job-get | Elasticsearch API documentation}
*/
async syncJobGet (this: That, params: T.ConnectorSyncJobGetRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorSyncJobGetResponse>
async syncJobGet (this: That, params: T.ConnectorSyncJobGetRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorSyncJobGetResponse, unknown>>
@ -1197,7 +1183,7 @@ export default class Connector {
/**
* Get all connector sync jobs. Get information about all stored connector sync jobs listed by their creation date in ascending order.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-sync-job-list | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-sync-job-list | Elasticsearch API documentation}
*/
async syncJobList (this: That, params?: T.ConnectorSyncJobListRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorSyncJobListResponse>
async syncJobList (this: That, params?: T.ConnectorSyncJobListRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorSyncJobListResponse, unknown>>
@ -1240,7 +1226,7 @@ export default class Connector {
/**
* Create a connector sync job. Create a connector sync job document in the internal index and initialize its counters and timestamps with default values.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-sync-job-post | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-sync-job-post | Elasticsearch API documentation}
*/
async syncJobPost (this: That, params: T.ConnectorSyncJobPostRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorSyncJobPostResponse>
async syncJobPost (this: That, params: T.ConnectorSyncJobPostRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorSyncJobPostResponse, unknown>>
@ -1294,7 +1280,7 @@ export default class Connector {
/**
* Set the connector sync job stats. Stats include: `deleted_document_count`, `indexed_document_count`, `indexed_document_volume`, and `total_document_count`. You can also update `last_seen`. This API is mainly used by the connector service for updating sync job information. To sync data using self-managed connectors, you need to deploy the Elastic connector service on your own infrastructure. This service runs automatically on Elastic Cloud for Elastic managed connectors.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-sync-job-update-stats | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-sync-job-update-stats | Elasticsearch API documentation}
*/
async syncJobUpdateStats (this: That, params: T.ConnectorSyncJobUpdateStatsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorSyncJobUpdateStatsResponse>
async syncJobUpdateStats (this: That, params: T.ConnectorSyncJobUpdateStatsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorSyncJobUpdateStatsResponse, unknown>>
@ -1351,7 +1337,7 @@ export default class Connector {
/**
* Activate the connector draft filter. Activates the valid draft filtering for a connector.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-filtering | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-filtering | Elasticsearch API documentation}
*/
async updateActiveFiltering (this: That, params: T.ConnectorUpdateActiveFilteringRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateActiveFilteringResponse>
async updateActiveFiltering (this: That, params: T.ConnectorUpdateActiveFilteringRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateActiveFilteringResponse, unknown>>
@ -1396,7 +1382,7 @@ export default class Connector {
/**
* Update the connector API key ID. Update the `api_key_id` and `api_key_secret_id` fields of a connector. You can specify the ID of the API key used for authorization and the ID of the connector secret where the API key is stored. The connector secret ID is required only for Elastic managed (native) connectors. Self-managed connectors (connector clients) do not use this field.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-api-key-id | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-api-key-id | Elasticsearch API documentation}
*/
async updateApiKeyId (this: That, params: T.ConnectorUpdateApiKeyIdRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateApiKeyIdResponse>
async updateApiKeyId (this: That, params: T.ConnectorUpdateApiKeyIdRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateApiKeyIdResponse, unknown>>
@ -1453,7 +1439,7 @@ export default class Connector {
/**
* Update the connector configuration. Update the configuration field in the connector document.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-configuration | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-configuration | Elasticsearch API documentation}
*/
async updateConfiguration (this: That, params: T.ConnectorUpdateConfigurationRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateConfigurationResponse>
async updateConfiguration (this: That, params: T.ConnectorUpdateConfigurationRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateConfigurationResponse, unknown>>
@ -1510,7 +1496,7 @@ export default class Connector {
/**
* Update the connector error field. Set the error field for the connector. If the error provided in the request body is non-null, the connectors status is updated to error. Otherwise, if the error is reset to null, the connector status is updated to connected.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-error | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-error | Elasticsearch API documentation}
*/
async updateError (this: That, params: T.ConnectorUpdateErrorRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateErrorResponse>
async updateError (this: That, params: T.ConnectorUpdateErrorRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateErrorResponse, unknown>>
@ -1567,7 +1553,7 @@ export default class Connector {
/**
* Update the connector features. Update the connector features in the connector document. This API can be used to control the following aspects of a connector: * document-level security * incremental syncs * advanced sync rules * basic sync rules Normally, the running connector service automatically manages these features. However, you can use this API to override the default behavior. To sync data using self-managed connectors, you need to deploy the Elastic connector service on your own infrastructure. This service runs automatically on Elastic Cloud for Elastic managed connectors.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-features | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-features | Elasticsearch API documentation}
*/
async updateFeatures (this: That, params: T.ConnectorUpdateFeaturesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateFeaturesResponse>
async updateFeatures (this: That, params: T.ConnectorUpdateFeaturesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateFeaturesResponse, unknown>>
@ -1624,7 +1610,7 @@ export default class Connector {
/**
* Update the connector filtering. Update the draft filtering configuration of a connector and marks the draft validation state as edited. The filtering draft is activated once validated by the running Elastic connector service. The filtering property is used to configure sync rules (both basic and advanced) for a connector.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-filtering | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-filtering | Elasticsearch API documentation}
*/
async updateFiltering (this: That, params: T.ConnectorUpdateFilteringRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateFilteringResponse>
async updateFiltering (this: That, params: T.ConnectorUpdateFilteringRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateFilteringResponse, unknown>>
@ -1681,7 +1667,7 @@ export default class Connector {
/**
* Update the connector draft filtering validation. Update the draft filtering validation info for a connector.
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/update-connector-filtering-validation-api.html | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-filtering-validation | Elasticsearch API documentation}
*/
async updateFilteringValidation (this: That, params: T.ConnectorUpdateFilteringValidationRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateFilteringValidationResponse>
async updateFilteringValidation (this: That, params: T.ConnectorUpdateFilteringValidationRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateFilteringValidationResponse, unknown>>
@ -1738,7 +1724,7 @@ export default class Connector {
/**
* Update the connector index name. Update the `index_name` field of a connector, specifying the index where the data ingested by the connector is stored.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-index-name | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-index-name | Elasticsearch API documentation}
*/
async updateIndexName (this: That, params: T.ConnectorUpdateIndexNameRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateIndexNameResponse>
async updateIndexName (this: That, params: T.ConnectorUpdateIndexNameRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateIndexNameResponse, unknown>>
@ -1795,7 +1781,7 @@ export default class Connector {
/**
* Update the connector name and description.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-name | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-name | Elasticsearch API documentation}
*/
async updateName (this: That, params: T.ConnectorUpdateNameRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateNameResponse>
async updateName (this: That, params: T.ConnectorUpdateNameRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateNameResponse, unknown>>
@ -1852,7 +1838,7 @@ export default class Connector {
/**
* Update the connector is_native flag.
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/update-connector-native-api.html | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-native | Elasticsearch API documentation}
*/
async updateNative (this: That, params: T.ConnectorUpdateNativeRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateNativeResponse>
async updateNative (this: That, params: T.ConnectorUpdateNativeRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateNativeResponse, unknown>>
@ -1909,7 +1895,7 @@ export default class Connector {
/**
* Update the connector pipeline. When you create a new connector, the configuration of an ingest pipeline is populated with default settings.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-pipeline | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-pipeline | Elasticsearch API documentation}
*/
async updatePipeline (this: That, params: T.ConnectorUpdatePipelineRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdatePipelineResponse>
async updatePipeline (this: That, params: T.ConnectorUpdatePipelineRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdatePipelineResponse, unknown>>
@ -1966,7 +1952,7 @@ export default class Connector {
/**
* Update the connector scheduling.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-scheduling | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-scheduling | Elasticsearch API documentation}
*/
async updateScheduling (this: That, params: T.ConnectorUpdateSchedulingRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateSchedulingResponse>
async updateScheduling (this: That, params: T.ConnectorUpdateSchedulingRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateSchedulingResponse, unknown>>
@ -2023,7 +2009,7 @@ export default class Connector {
/**
* Update the connector service type.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-service-type | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-service-type | Elasticsearch API documentation}
*/
async updateServiceType (this: That, params: T.ConnectorUpdateServiceTypeRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateServiceTypeResponse>
async updateServiceType (this: That, params: T.ConnectorUpdateServiceTypeRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateServiceTypeResponse, unknown>>
@ -2080,7 +2066,7 @@ export default class Connector {
/**
* Update the connector status.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-connector-update-status | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-connector-update-status | Elasticsearch API documentation}
*/
async updateStatus (this: That, params: T.ConnectorUpdateStatusRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ConnectorUpdateStatusResponse>
async updateStatus (this: That, params: T.ConnectorUpdateStatusRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.ConnectorUpdateStatusResponse, unknown>>

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -71,7 +57,7 @@ const acceptedParams: Record<string, { path: string[], body: string[], query: st
/**
* Count search results. Get the number of documents matching a query. The query can be provided either by using a simple query string as a parameter, or by defining Query DSL within the request body. The query is optional. When no query is provided, the API uses `match_all` to count all the documents. The count API supports multi-target syntax. You can run a single count API search across multiple data streams and indices. The operation is broadcast across all shards. For each shard ID group, a replica is chosen and the search is run against it. This means that replicas increase the scalability of the count.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-count | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-count | Elasticsearch API documentation}
*/
export default async function CountApi (this: That, params?: T.CountRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CountResponse>
export default async function CountApi (this: That, params?: T.CountRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CountResponse, unknown>>

File diff suppressed because one or more lines are too long

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -79,7 +65,7 @@ export default class DanglingIndices {
/**
* Delete a dangling index. If Elasticsearch encounters index data that is absent from the current cluster state, those indices are considered to be dangling. For example, this can happen if you delete more than `cluster.indices.tombstones.size` indices while an Elasticsearch node is offline.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-dangling-indices-delete-dangling-index | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-dangling-indices-delete-dangling-index | Elasticsearch API documentation}
*/
async deleteDanglingIndex (this: That, params: T.DanglingIndicesDeleteDanglingIndexRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.DanglingIndicesDeleteDanglingIndexResponse>
async deleteDanglingIndex (this: That, params: T.DanglingIndicesDeleteDanglingIndexRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.DanglingIndicesDeleteDanglingIndexResponse, unknown>>
@ -124,7 +110,7 @@ export default class DanglingIndices {
/**
* Import a dangling index. If Elasticsearch encounters index data that is absent from the current cluster state, those indices are considered to be dangling. For example, this can happen if you delete more than `cluster.indices.tombstones.size` indices while an Elasticsearch node is offline.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-dangling-indices-import-dangling-index | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-dangling-indices-import-dangling-index | Elasticsearch API documentation}
*/
async importDanglingIndex (this: That, params: T.DanglingIndicesImportDanglingIndexRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.DanglingIndicesImportDanglingIndexResponse>
async importDanglingIndex (this: That, params: T.DanglingIndicesImportDanglingIndexRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.DanglingIndicesImportDanglingIndexResponse, unknown>>
@ -169,7 +155,7 @@ export default class DanglingIndices {
/**
* Get the dangling indices. If Elasticsearch encounters index data that is absent from the current cluster state, those indices are considered to be dangling. For example, this can happen if you delete more than `cluster.indices.tombstones.size` indices while an Elasticsearch node is offline. Use this API to list dangling indices, which you can then import or delete.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-dangling-indices-list-dangling-indices | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-dangling-indices-list-dangling-indices | Elasticsearch API documentation}
*/
async listDanglingIndices (this: That, params?: T.DanglingIndicesListDanglingIndicesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.DanglingIndicesListDanglingIndicesResponse>
async listDanglingIndices (this: That, params?: T.DanglingIndicesListDanglingIndicesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.DanglingIndicesListDanglingIndicesResponse, unknown>>

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -62,7 +48,7 @@ const acceptedParams: Record<string, { path: string[], body: string[], query: st
/**
* Delete a document. Remove a JSON document from the specified index. NOTE: You cannot send deletion requests directly to a data stream. To delete a document in a data stream, you must target the backing index containing the document. **Optimistic concurrency control** Delete operations can be made conditional and only be performed if the last modification to the document was assigned the sequence number and primary term specified by the `if_seq_no` and `if_primary_term` parameters. If a mismatch is detected, the operation will result in a `VersionConflictException` and a status code of `409`. **Versioning** Each document indexed is versioned. When deleting a document, the version can be specified to make sure the relevant document you are trying to delete is actually being deleted and it has not changed in the meantime. Every write operation run on a document, deletes included, causes its version to be incremented. The version number of a deleted document remains available for a short time after deletion to allow for control of concurrent operations. The length of time for which a deleted document's version remains available is determined by the `index.gc_deletes` index setting. **Routing** If routing is used during indexing, the routing value also needs to be specified to delete a document. If the `_routing` mapping is set to `required` and no routing value is specified, the delete API throws a `RoutingMissingException` and rejects the request. For example: ``` DELETE /my-index-000001/_doc/1?routing=shard-1 ``` This request deletes the document with ID 1, but it is routed based on the user. The document is not deleted if the correct routing is not specified. **Distributed** The delete operation gets hashed into a specific shard ID. It then gets redirected into the primary shard within that ID group and replicated (if needed) to shard replicas within that ID group.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-delete | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-delete | Elasticsearch API documentation}
*/
export default async function DeleteApi (this: That, params: T.DeleteRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.DeleteResponse>
export default async function DeleteApi (this: That, params: T.DeleteRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.DeleteResponse, unknown>>

File diff suppressed because one or more lines are too long

View File

@ -1,20 +1,6 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable import/export */
@ -54,7 +40,7 @@ const acceptedParams: Record<string, { path: string[], body: string[], query: st
/**
* Throttle a delete by query operation. Change the number of requests per second for a particular delete by query operation. Rethrottling that speeds up the query takes effect immediately but rethrotting that slows down the query takes effect after completing the current batch to prevent scroll timeouts.
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-delete-by-query-rethrottle | Elasticsearch API documentation}
* @see {@link https://www.elastic.co/docs/api/doc/elasticsearch/v9/operation/operation-delete-by-query-rethrottle | Elasticsearch API documentation}
*/
export default async function DeleteByQueryRethrottleApi (this: That, params: T.DeleteByQueryRethrottleRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.DeleteByQueryRethrottleResponse>
export default async function DeleteByQueryRethrottleApi (this: That, params: T.DeleteByQueryRethrottleRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.DeleteByQueryRethrottleResponse, unknown>>

Some files were not shown because too many files have changed in this diff Show More