Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
elasticsearch service using node.js
var http = require('http'),
url = require('url'),
_ = require('underscore'),
elastical = require('elastical');
var client = new elastical.Client();
if (process.argv.length < 3) {
console.log('Port number is required');
return;
}
var port = parseInt(process.argv[2]);
var server = http.createServer(function (request, response) {
var params = url.parse(request.url, true)['query'];
response.writeHead(200, {'Content-Type': 'application/json'});
var fullQuery = {},
innerQuery = {};
if (params.q) {
innerQuery = params.q;
} else {
innerQuery.match_all = {};
}
// If tags are passed, then do a filtered query
if (params.tags) {
fullQuery.filtered = {
query: innerQuery,
filter: {
terms: { tags: params.tags.split(',') }
}
};
} else {
fullQuery = innerQuery;
}
client.search({
query: fullQuery,
facets: {
title: {
terms: {
field: "title",
size: 100
}
},
tags: {
terms: {
field: "tags",
size: 500
}
},
category: {
terms: {
field: "category",
size: 100
}
},
date: {
date_histogram : {
field : "date",
interval : "month"
}
}
}
}, function(err, results, fullData) {
// data = {
// total: results.total,
// documents: _.pluck(results.hits, '_source'),
// tags: fullData.facets.tags.terms
// };
response.end(JSON.stringify(fullData));
});
});
server.listen(port)
console.log('Server running at http://127.0.0.1:' + port + '/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.