Configurationedit

The Client constructor accepts a single object as its argument. In the Config options section all of the available options/keys are listed.

var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
  ... config options ...
});
Warning

Due to the complex nature of the configuration, the config object you pass in will be modified and can only be used to create one Client instance. Sorry for the inconvenience. Related Github issue: https://github.com/elasticsearch/elasticsearch-js/issues/33

Config optionsedit

host or hosts

String, String[], Object[] — Specify the hosts that this client will connect to. If sniffing is enabled, or you call client.sniff(), this list will be used as seeds to discover the rest of your cluster.

The value(s) are passed to the Host constructor. Host objects can help enforce path-prefixes, default headers and query strings, and can be helpful in making more intelligent selection algorithms; Head over to the Host docs for more information.

Default
'http://localhost:9200'

httpAuth

String — Specifies the default http auth as a String with username and password separated by a colon (eg. user:pass). Applies to any host defined in the original config, and any hosts discovered while sniffing.

log

String, String[], Object, Object[], Constructor — Unless a constructor is specified, this sets the output settings for the bundled logger. See the section on configuring-logging[logging] for more information.

Default in Node
[{
  type: 'stdio',
  levels: ['error', 'warning']
}]

apiVersion

String — Change the API that they client provides, specify the major version of the Elasticsearch nodes you will be connecting to.

Warning

This default will track the latest version of Elasticsearch, and is only intended to be used during development. It is highly recommended that you set this parameter in all code that is headed to production.

Default
'5.3'
Options in node
  • '5.3'
  • '5.2'
  • '5.1'
  • '5.0'
  • '2.4'
  • '1.7'
  • '0.90'
  • '5.x' (unstable)
  • 'master' (unstable)
Options in the browser
  • '5.3'
  • '5.2'
  • '5.1'
  • '5.0'
  • '2.4'
  • '5.x' (unstable)
  • 'master' (unstable)

plugins

Function[] — Plugin instantiators that will be called when the Client initializes. Each function is called in order with the arguments Constructor, config, and components.

Constructor is the class that will be newed up to create the client instance. It’s prototype contains the api methods that correlate to the apiVersion requested.

config is the config object that was passed to the elasticsearch.Client constructor.

components is a map of the internal classes for this version of the elasticsearch client. The values on this object are listed here.

sniffOnStart

Boolean — Should the client attempt to detect the rest of the cluster when it is first instantiated?

Default
false

sniffInterval

Number, false — Every n milliseconds, perform a sniff operation and make sure our list of nodes is complete.

Default
false

sniffOnConnectionFault

Boolean — Should the client immediately sniff for a more current list of nodes when a connection dies?

Default
false

maxRetries

Integer — How many times should the client try to connect to other nodes before returning a ConnectionFault error.

Default
3

requestTimeout

Number — Milliseconds before an HTTP request will be aborted and retried. This can also be set per request.

Default
30000

deadTimeout

Number — Milliseconds that a dead connection will wait before attempting to revive itself.

Default
60000

pingTimeout

Number — Milliseconds that a ping request can take before timing out.

Default
3000

maxSockets

Number — Maximum number of sockets to allow per host.

Default
Infinity

keepAlive

Boolean — Should the connections to the node be kept open forever? This behavior is recommended when you are connecting directly to Elasticsearch.

Default
true

keepAliveInterval

Number — How often, in milliseconds, should TCP KeepAlive packets be sent over sockets being kept alive. Only relevant if keepAlive is set to true.

Default
1000

keepAliveMaxFreeSockets

Number — Maximum number of inactive sockets to keep connected to a node. Only relevant if keepAlive is set to true.

Default
256

keepAliveFreeSocketTimeout

Number — Sets inactive sockets to timeout after milliseconds of inactivity. Only relevant if keepAlive is set to true.

Default
60000

suggestCompression

Boolean — The client should inform Elasticsearch, on each request, that it can accept compressed responses. In order for the responses to actually be compressed, you must enable http.compression in Elasticsearch. See these docs for additional info.

Default
false

connectionClass

String, Constructor — Defines the class that will be used to create connections to store in the connection pool. If you are looking to implement additional protocols you should probably start by writing a Connection class that extends the ConnectionAbstract.

Defaults
  • Node: "http"
  • Browser Build: "xhr"
  • Angular Build: "angular"
  • jQuery Build: "jquery"

sniffedNodesProtocol

String — Defines the protocol that will be used to communicate with nodes discovered during sniffing.

Default
If all of the hosts/host passed to the client via configuration use the same protocol then this defaults to that protocol, otherwise it defaults to "http".

ssl

Object — An object defining HTTPS/SSL configuration to use for all nodes. The properties of this mimic the options accepted by tls.connect() with the exception of rejectUnauthorized, which defaults to false allowing self-signed certificates to work out-of-the-box.

Additional information available in SSL and Authentication.

ssl.pfx
String,Array[String] — Certificate, Private key and CA certificates to use for SSL. Default null.
ssl.key
String — Private key to use for SSL. Default null.
ssl.passphrase
String — A string of passphrase for the private key or pfx. Default null.
ssl.cert
String — Public x509 certificate to use. Default null.
ssl.ca
String,Array[String] — An authority certificate or array of authority certificates to check the remote host against. Default null.
ssl.ciphers
String — A string describing the ciphers to use or exclude. Consult http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format. Default null.
ssl.rejectUnauthorized
Boolean — If true, the server certificate is verified against the list of supplied CAs. An error event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default false
ssl.secureProtocol
String — The SSL method to use, e.g. TLSv1_method to force TLS version 1. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS. Default null.
Example
var client = new elasticsearch.Client({
  hosts: [
    'https://box1.internal.org',
    'https://box2.internal.org',
    'https://box3.internal.org'
  ],
  ssl: {
    ca: fs.readFileSync('./cacert.pem'),
    rejectUnauthorized: true
  }
});

selector

String, Function — This function will be used to select a connection from the ConnectionPool. It should received a single argument, the list of "active" connections, and return the connection to use. Use this selector to implement special logic for your client such as preferring nodes in a certain rack or data-center.

To make this function asynchronous, accept a second argument which will be the callback to use. The callback should be called Node-style with a possible error like: cb(err, selectedConnection).

Default
"roundRobin"
Options
  • "roundRobin"
  • "random"

defer

Function — Override the way that the client creates promises. If you would rather use any other promise library this is how you’d do that. Elasticsearch.js expects that the defer object has a promise property (which will be returned to promise consumers), as well as resolve and reject methods.

Default
Defer object created with ES6 Promise
To use Bluebird
var Bluebird = require('bluebird');
var client = new elasticsearch.Client({
  defer: function () {
    return Bluebird.defer();
  }
});

nodesToHostCallback

Function - This function will receive the list of nodes returned from the _cluster/nodes API during a sniff operation. The function should return an array of objects which match the specification for the hosts config.

Default
see nodes_to_host.js

createNodeAgent

Function — Override the way that the client creates node.js Agent[https://nodejs.org/api/http.html#http_class_http_agent] objects. The value of this property will be executed every time a new Node is added to the client (either from the initial seed or from sniffing) and can return any value that node’s http(s) module accepts as agent: configuration.

The function is called with two arguments, first an HttpConnector[http://github.com/spalger/elasticsearch-js/blob/master/src/lib/connectors/http.js] object and the second the config object initially passed when creating the client.

Default
HttpConnector#createAgent()
Disable Agent creation
var client = new elasticsearch.Client({
  createNodeAgent: function () {
    return false;
  }
});

Examplesedit

Connect to just a single seed node, and use sniffing to find the rest of the cluster.

var client = new elasticsearch.Client({
  host: 'localhost:9200',
  sniffOnStart: true,
  sniffInterval: 60000,
});

Specify a couple of hosts which use basic auth.

var client = new elasticsearch.Client({
  hosts: [
    'https://user:pass@box1.server.org:9200',
    'https://user:pass@box2.server.org:9200'
  ]
});

Use host objects to define extra properties, and a selector that uses those properties to pick a node.

var client = new elasticsearch.Client({
  hosts: [
    {
      protocol: 'https',
      host: 'box1.server.org',
      port: 56394,
      country: 'EU',
      weight: 10
    },
    {
      protocol: 'https',
      host: 'box2.server.org',
      port: 56394,
      country: 'US',
      weight: 50
    }
  ],
  selector: function (hosts) {
    var myCountry = process.env.COUNTRY;
    // first try to find a node that is in the same country
    var selection = _.find(nodes, function (node) {
      return node.host.country === myCountry;
    });

    if (!selection) {
      // choose the node with the smallest weight.
      selection = _(nodes).sortBy(function (node) {
        return node.host.weight;
      }).first();
    }

    return selection;
  }
});

Use a custom nodesToHostCallback that will direct all of the requests to a proxy and select the node via a query string param. 

var client = new elasticsearch.Client({
  nodesToHostCallback: function (nodes) {
    /*
     * The nodes object will look something like this
     * {
     *   "y-YWd-LITrWXWoCi4r2GlQ": {
     *     name: "Supremor",
     *     transport_address: "inet[/192.168.1.15:9300]",
     *     hostname: "Small-ESBox.infra",
     *     version: "1.0.0",
     *     http_address: "inet[/192.168.1.15:9200]",
     *     attributes: {
     *        custom: "attribute"
     *     }
     *   },
     *   ...
     * }
     */

    return _.transform(nodes, function (nodeList, node, id) {
      var port = node.http_address.match(/:(\d+)/)[1];
      nodeList.push({
        host: 'esproxy.example.com',
        port: 80,
        query: {
          nodeHostname: node.hostname,
          nodePort: port
        }
      });
    }, []);
  }
})