Skip to content

Instantly share code, notes, and snippets.

@MikeyBurkman
Last active June 29, 2017 14:31
Show Gist options
  • Save MikeyBurkman/110dc9357a43559ab855821f14470179 to your computer and use it in GitHub Desktop.
Save MikeyBurkman/110dc9357a43559ab855821f14470179 to your computer and use it in GitHub Desktop.
ElasticSearch Example
#! /usr/bin/env cecil
// Usage:
// ./esclient.js http://your-elasticsearch-host.com
var elasticsearch = include('elasticsearch', '^11.0.0');
var moment = include('moment', '^2.13.0');
var R = include('ramda', '^0.21.0');
var Promise = include('bluebird', '^3.4.0');
var index = 'testindex';
var times = R.map(function() {
var bias = 2.0;
var n = Math.pow(Math.random(), bias);
return Math.floor(n*1500) + 25;
}, R.range(0, 1000));
var services = [
'foo',
'foo',
'foo',
'bar',
'bar',
'qux'
];
var envs = [
'dev',
'test',
'test',
'prod',
'prod',
'prod'
];
var host = process.argv[2];
if (!host) {
console.log('Host needs to be specified as first argument');
process.exit(0);
}
var client = new elasticsearch.Client({
host: host,
log: 'info'
});
Promise.resolve()
//.then(clear)
//.then(createIndex)
.then(function() {
return Promise.map(R.range(0, 50), send);
})
.then(function() {
console.log('Finished!');
});
/////////
function clear() {
return client.indices.delete({
index: index
})
.catch(function(err) {
if (err.message.indexOf('IndexMissingException') === -1) {
throw err;
}
});
}
function createIndex() {
return client.indices.create({
index: index,
body: {
mappings: {
'testType': {
properties: {
name: { type: 'string', index: 'not_analyzed' },
env: { type: 'string', index: 'not_analyzed' },
time: { type: 'integer' },
created: { type: 'date'}
}
}
}
}
});
}
function send() {
var items = [];
for (var i = 0; i < 500; i += 1) {
items.push({ index: { _index: index, _type: 'testType' } });
items.push({
created: moment().subtract(randomInt(0, 500000), 'seconds').toISOString(),
env: randomElement(envs),
name: randomElement(services),
time: randomElement(times)
});
}
return client.bulk({
body: items
});
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function randomElement(arr) {
return arr[randomInt(0, arr.length)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment