Files
elasticsearch-js/docs/usage.asciidoc
2019-04-11 16:38:16 +02:00

306 lines
6.8 KiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

[[client-usage]]
== Usage
Use the client is pretty straightforward, it supports all the public APIs of Elasticsearch, and every method exposes the same signature.
[source,js]
----
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })
// promise API
const result = await client.search({
index: 'my-index',
body: { foo: 'bar' }
})
// callback API
client.search({
index: 'my-index',
body: { foo: 'bar' }
}, (err, result) => {
if (err) console.log(err)
})
----
The returned value of every API call is formed as follows:
[source,ts]
----
{
body: object | boolean
statusCode: number
headers: object
warnings: [string],
meta: object
}
----
NOTE: The body will be a boolean value when using `HEAD` APIs.
The above value will be returned even if there is an error during the execution of the request, this means that you can safely use the https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment[destructuring assignment].
The `meta` key contains all the information regarding the request, such as attempt, options, and the connection that has been used.
[source,js]
----
// promise API
const { body } = await client.search({
index: 'my-index',
body: { foo: 'bar' }
})
// callback API
client.search({
index: 'my-index',
body: { foo: 'bar' }
}, (err, { body }) => {
if (err) console.log(err)
})
----
=== Aborting a request
When using the callback style API, the function will also return an object that allows you to abort the API request.
[source,js]
----
// calback API
const request = client.search({
index: 'my-index',
body: { foo: 'bar' }
}, {
ignore: [404],
maxRetries: 3
}, (err, { body }) => {
if (err) console.log(err)
})
request.abort()
----
Aborting a request with the promise style API is not supported, but you can easily achieve that with convenience wrapper.
[source,js]
----
function abortableRequest (params, options) {
var request = null
const promise = new Promise((resolve, reject) => {
request = client.search(params, options, (err, result) => {
err ? reject(err) : resolve(res)
})
})
return {
promise,
abort: () => request.abort()
}
}
const request = abortableRequest({
index: 'my-index',
body: { foo: 'bar' }
}, {
ignore: [404],
maxRetries: 3
})
request.abort()
// access the promise with `request.promise.[method]`
----
=== Request specific options
If needed you can pass request specific options in a second object:
[source,js]
----
// promise API
const result = await client.search({
index: 'my-index',
body: { foo: 'bar' }
}, {
ignore: [404],
maxRetries: 3
})
// calback API
client.search({
index: 'my-index',
body: { foo: 'bar' }
}, {
ignore: [404],
maxRetries: 3
}, (err, { body }) => {
if (err) console.log(err)
})
----
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` - Max request timeout for the request, it overrides the client default. +
_Default:_ `30000`
|`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 will 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`
|===
=== 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)
----
Following you can find the errors exported by the client.
[cols=2*]
|===
|`ElasticsearchClientErrors`
|Every error inherits from this class, it is the basic error generated by the client.
|`TimeoutError`
|Generated when a request exceeds the `requestTimeout` option.
|`ConnectionError`
|Generated when an error occurs during the reequest, it can be a connection error or a malformed stream of data.
|`NoLivingConnectionsError`
|Generated in case of all connections present in the connection pool are dead.
|`SerializationError`
|Generated if the serialization fails.
|`DeserializationError`
|Generated if the deserialization fails.
|`ConfigurationError`
|Generated if there is a malformed configuration or parameter.
|`ResponseError`
|Generated when in case of a `4xx` or `5xx` response.
|===
=== Events
The client is an event emitter, this means that you can listen for its event and add additional logic to your code, without need to change the client internals or your normal usage. +
You can find the events names by access the `events` key of the client.
[source,js]
----
const { events } = require('@elastic/elasticsearch')
console.log(events)
----
The event emitter functionality can be useful if you want to log every request, response and error that is happening during the use of the client.
[source,js]
----
const logger = require('my-logger')()
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })
client.on('response', (err, req) => {
if (err) {
logger.error(err)
} else {
logger.info(req)
}
})
----
The client emits the following events:
[cols=2*]
|===
|`request`
a|Emitted before to send the actual request to Elasticsearch.
[source,js]
----
client.on('request', (err, req) => {
console.log(err, req)
})
----
|`response`
a|Emitted before to send the actual request to Elasticsearch.
[source,js]
----
client.on('response', (err, req) => {
console.log(err, req)
})
----
|`sniff`
a|Emitted before to send the actual request to Elasticsearch.
[source,js]
----
client.on('sniff', (err, req) => {
console.log(err, req)
})
----
|`resurrect`
a|Emitted before to send the actual request to Elasticsearch.
[source,js]
----
client.on('resurrect', (err, req) => {
console.log(err, req)
})
----
|===
The values of `req` in `request`, `response` and `sniff` will be:
[source,ts]
----
body: any;
statusCode: number | null;
headers: anyObject | null;
warnings: string[] | null;
meta: {
request: {
params: TransportRequestParams;
options: TransportRequestOptions;
};
connection: Connection;
attempts: number;
aborted: boolean;
sniff?: {
hosts: any[];
reason: string;
};
};
----
While the `req` value in `resurrect` will be:
[source,ts]
----
export interface ResurrectEvent {
strategy: string;
isAlive: boolean;
connection: Connection;
}
----