danpaz / bodybuilder

An elasticsearch query body builder :muscle:

Home Page:http://bodybuilder.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Filters are nested under an additional bool + must clause

marija17 opened this issue · comments

I've noticed when trying to create a query with more than 1 filter, it nests what should be a simple filter array under an additional bool + must query. This is not the behavior I want because
(a) its an unnecessary level of nesting and
(b) using a must clause may mean its running in a query context, whereas I'm trying to optimize by using the filter context (I say may only because I don't know for sure what takes precedent here, the context of the inner must or the outer filter and it doesn't seem to documented - which I suppose makes sense as its sort of an unusual, unnecessary thing to do)

To be really explicit ... for the following body builder code:

const bodyObj = bodybuilder();
bodyObj.filter('term', 'display', true);
bodyObj.filter('term', 'deleted', false);

It builds the following query:

{
  "query": {
    "bool": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "display": true
              }
            },
            {
              "term": {
                "in_stock": true
              }
            }
          ]
        }
      }
    }
  }
}

As opposed to the query I want:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "display": true
          }
        },
        {
          "term": {
            "in_stock": true
          }
        }
      ]
    }
  }
}

I poked around the repo and according to this comment it seems like this may be something you're already aware of -

// nesting filters: We've introduced an unnecessary `filter.bool`

Is there an intention to revisit this? Would a contribution with this change be desirable and considered for merge?

PRs are always considered. The outer filter is an encapsulating filter context. Works the same as having the bool context and adding the different context within.

ah ok @ferronrsmith - good to know on the outer filter being encapsulated! Thank you