Node.js Client Examples¶
Installation¶
Installing the Node.js client is simple, using the usual npm install procedure:
$ npm install elasticsearch
Connecting¶
The example below shows the connection settings using HTTPS
. If you prefer to use HTTP
, you only need to change var protocol = 'http';
and var port = 10202;
.
var port = 20202; var protocol = ‘https’;
var elasticsearch = require('elasticsearch');
var auth = 'YOUR_USERNAME:YOUR_PASSWORD';
var port = 20202;
var protocol = 'https';
var hostUrls = [
'iad1-10202-0.es.objectrocket.com',
'iad1-10202-1.es.objectrocket.com',
'iad1-10202-2.es.objectrocket.com',
'iad1-10202-3.es.objectrocket.com
];
var hosts = hostUrls.map(function(host) {
return {
protocol: protocol,
host: host,
port: port,
auth: auth
};
});
var client = new elasticsearch.Client({
hosts: hosts
});
client.ping({
requestTimeout: 30000
}, function(error) {
if (error) {
console.trace('Error:', error);
} else {
console.log('Connected!');
}
// on finish
client.close();
});
Index a document¶
client.index({
index: 'example_index',
type: 'posts',
id: '1',
body: {
user: 'me',
post_date: new Date(),
message: 'Hello World!'
},
refresh: true
});
Search (DSL)¶
client.search({
index: 'example_index',
type: 'posts',
body: {
query: {
match: {
body: 'Hello World'
}
}
}
});
Delete a document¶
client.delete({
index: 'example_index',
type: 'posts',
id: '1',
})