Best practice creating ES API using NodeJS

I developed simple nodejs project using ES as our search engine and
ElasticSearchClient for node

Node is exposing api to the user(using expressJS for that)

I have few search categories (search by username, search by firstname,
search by lastname, etc...)

This is the function (using promises) which returning search by username:

  • please ignore the inline params. this is just a POC

function performSearch(termToSearch) {

var deferred = Q.defer();
console.log("Request handler 'search' was called.");
var qryObj =
    "query": {
        "match": {
            "username": termToSearch
};'my_index", "users", qryObj).
    on('data', function (data) {
    .on('error', function (err) {
        return deferred.resolve(err);
return  deferred.promise;


My question is what if I want to implement the next fields.. I need to
duplicate this code with different queries? any best practical example to
upgrade that code.


You received this message because you are subscribed to the Google Groups "elasticsearch" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit
For more options, visit

Store your query into a variable (json) and pass to the same function