Conditionally adding term filters to elasticsearch filter query -
i've been wondering how go checking if search parameter not empty before adding term filter filtered query. limited experience elasticsearch, seems have build exact query ahead of time.
if using node / mongo, know along lines of
var searchterms = {}; if(req.body.country){ searchterm['user.country'] = req.body.country; } if(req.body.company){ searchterm['user.company'] = req.body.company; } if(req.body.salary){ searchterm['user.salary'] = req.body.salary; } users.find(searchterm) .exec(function(err, users) { if(!err){ res.send(200, users); } else{ res.send(200, err); } });
and in angular i've built query elasticsearch works correctly long parameters filled in. guess question how conditionally , dynamically build filtered query based on parameters have been filled in user.
i.e. user fills out country , company leaves out salary. therefore, salary wouldn't included term filter.
client.search({ index: 'firebase', type: 'user', body: { "query": { "filtered" : { "query" : { "match_all" : {} }, "filter": { "and": [ { "term": { "country" : searchparameters.country } }, { "term": { "company" : searchparameters.company } }, { "term": { "salary" : searchparameters.salary } } ] } } }
thank in advance!
what have been doing node/mongo describe way go elasticsearch queries.
so js code might like:
var filters = []; var fields = ['country', 'company', 'salary',...]; // or kind of hash map req fields elasticsearch fields if appropriate for(var k = 0; k < fields.length; k++) { if(req.body[fields[k]]) { var termq = { term : {} }; termq.term[fields[k]] = req.body[fields[k]]; filters.push(termq); } } var query = { filtered : { query : { match_all : {} }, filter : filters.length ? { , : filters } : {} } }; client.search({ index: ..., type: ..., body: query }, ...);
Comments
Post a Comment