Usage

edit

Use the client is pretty straightforward, it supports all the public APIs of Elasticsearch, and every method exposes the same signature.

const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })

// promise API
const result = await client.search({
  index: 'my-index',
  body: {
    query: {
      match: { hello: 'world' }
    }
  }
})

// callback API
client.search({
  index: 'my-index',
  body: {
    query: {
      match: { hello: 'world' }
    }
  }
}, (err, result) => {
  if (err) console.log(err)
})

The returned value of every API call is formed as follows:

{
  body: object | boolean
  statusCode: number
  headers: object
  warnings: [string],
  meta: object
}

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 destructuring assignment.

The meta key contains all the information regarding the request, such as attempt, options, and the connection that has been used.

// promise API
const { body } = await client.search({
  index: 'my-index',
  body: {
    query: {
      match: { hello: 'world' }
    }
  }
})

// callback API
client.search({
  index: 'my-index',
  body: {
    query: {
      match: { hello: 'world' }
    }
  }
}, (err, { body }) => {
  if (err) console.log(err)
})