danpaz / bodybuilder

An elasticsearch query body builder :muscle:

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

how to merge two DSL results?

elixiao opened this issue · comments

I got two DSL results from two bodybuilder statements:

// const first = bodybuilder().filter('term', 'name', 'david').build()
{
  query: {
    bool: { filter: { term: { name: 'david' } } }
  }
}
// const second = bodybuilder().sort('dateCreated', 'desc').filter('term', 'company', 'xxx').build()
{
  sort: [ { dateCreated: { order: 'desc' } } ],
  query: {
    bool: { filter: { term: { company: 'xxx' } } }
  }
}

How to merge the two DSL results into one without building from scratch ?

// const final = bodybuilder().filter('term', 'name', 'david').sort('dateCreated', 'desc').filter('term', 'company', 'xxx').build()
{
  sort: [ { dateCreated: { order: 'desc' } } ],
  query: {
    bool: {
      filter: {
        bool: {
          must: [ { term: { name: 'david' } }, { term: { company: 'xxx' } } ]
        }
      }
    }
  }
}

lodash merge is not correct:

// lodash.merge(first, second)
{
  query: {
    bool: { filter: { term: { name: 'david', company: 'xxx' } } }
  },
  sort: [ { dateCreated: { order: 'desc' } } ]
}
bodybuilder()
  .sort('dateCreated', 'desc')
  .filter('term', 'company', 'xxx')
  .filter('term', 'name', 'david')
  .build()

==>

{
  "sort": [
    {
      "dateCreated": {
        "order": "desc"
      }
    }
  ],
  "query": {
    "bool": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "company": "xxx"
              }
            },
            {
              "term": {
                "name": "david"
              }
            }
          ]
        }
      }
    }
  }
}

@ferronrsmith How to merge the two DSL results into one without building from scratch? I don't known the building process so I cannot build using the statement you provided. Actually The first DSL result is sending from client side, I got it on the server side and want to add some query condition on this basis.

Can I provide an initial value and extend the DSL like the following statement?

const initalValue = {
  query: {
    bool: { filter: { term: { name: 'david' } } }
  }
}
const result = bodybuilder(initalValue).sort('dateCreated', 'desc').filter('term', 'company', 'xxx').build()
// got the extended DSL

That’s not possible sorry

@elixiao Were you able to find an workaround/fix?