bodybuilder icon indicating copy to clipboard operation
bodybuilder copied to clipboard

[Question] Is there a way to convert ES queries to bodybuilder implementation?

Open lucianopf opened this issue 4 years ago • 3 comments

I've been trying to convert complex ES queries to bodybuilder but it's quite hard to figure it out without much knowledge of the library. Maybe it would be nice to have a converter from query to bodybuilder to help newcomers to learn how does the lib works :grimacing:

lucianopf avatar Oct 20 '21 21:10 lucianopf

I've thought for a while that something like this would be useful, but I think implementing it would be pretty difficult since the api is so flexible.

Have you tried using https://bodybuilder.js.org to try to recreate your queries using bodybuilder? You can also ask here if you have a specific complex query, I or someone else may be able to help you along.

danpaz avatar Oct 21 '21 00:10 danpaz

reverse convert is so hard, is @danpaz able to convert this back to bodybuilder js code ?

{
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "should": [
            {
              "term": {
                "content.keyword": {
                  "value": "小說",
                  "boost": 2
                }
              }
            },
            {
              "match": {
                "content": "小說"
              }
            }
          ]
        }
      },
      "functions": [
        {
          "field_value_factor": {
            "field": "numAuthors",
            "factor": 1.2,
            "modifier": "log2p",
            "missing": 1
          }
        },
        {
          "field_value_factor": {
            "field": "numArticles",
            "modifier": "log2p",
            "missing": 1
          }
        }
      ]
    }
  },
  "size": 20
}

tx0c avatar Apr 27 '22 23:04 tx0c

@tx0c the function_score query could be expressed in bodybuilder syntax pretty easily, but the functions array is probably best handled separately. Give this a try:

let body = bodybuilder()
  .query('function_score', b => {
    return b
      .orQuery('term', 'content.keyword', { value: '小說', boost: 2 })
      .orQuery('match', 'content', '小說')
  })
  .build()

body.query.function_score.functions = [
  {
    "field_value_factor": {
      "field": "numAuthors",
      "factor": 1.2,
      "modifier": "log2p",
      "missing": 1
    }
  },
  {
    "field_value_factor": {
      "field": "numArticles",
      "modifier": "log2p",
      "missing": 1
    }
  }
]

return body

danpaz avatar May 04 '22 02:05 danpaz