IMPORTANT: elasticsearch.js has been replaced by the new Elasticsearch JavaScript client. We strongly advise you to migrate to the new client. To learn more, see the migration guide.
Examples
edit
IMPORTANT: This documentation is no longer updated. Refer to Elastic's version policy and the latest documentation.
Examples
editConnect 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;
}).head();
}
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
}
});
}, []);
}
})