sudo-suhas/elastic-builder

adding-filters-dynamically

jparish3 opened this issue · 1 comments

Is there a way to add filters, etc. dynamically from an array as in the example below?

// https://stackoverflow.com/questions/44738531/adding-filters-dynamically-to-dsl-query-body-generated-using-bodybuilder-js

  const filterTerms = ['red', 'green', 'black']
  const body = bodybuilder()
  body.query('match', 'searchable', 'foobar')
  filterTerms.reduce((filterBody, term) => {
    return filterBody.filter('match', 'term', term)
  }, body)
  console.log(JSON.stringify(body.build(), null, 2))

Not that different with elastic-builder:

const filterTerms = ['red', 'green', 'black'];
const qry = esb.boolQuery()
    .must(esb.matchQuery('searchable', 'foobar'));
filterTerms.forEach(c => {
    qry.filter(esb.termQuery('color', c))
})
const body = esb.requestBodySearch()
    .query(qry);

This produces the following output:

{
  "query": {
    "bool": {
      "must": {
        "match": {
          "searchable": "foobar"
        }
      },
      "filter": [
        {
          "term": {
            "color": "red"
          }
        },
        {
          "term": {
            "color": "green"
          }
        },
        {
          "term": {
            "color": "black"
          }
        }
      ]
    }
  }
}