Home > Mobile >  elasticsearch query dsl show products with higher product quantity at the top
elasticsearch query dsl show products with higher product quantity at the top

Time:06-22

i want to search products based on some filters and a keyword which in my code identified by q. what i trying to do is to show products which product_quantity is not equal to zero at the top. this is my current query.

"query":{
     "bool":{
        "filter":[
           {
              "term":{
                 "status":{
                    "value":1
                 }
              }
           },
           {
              "range":{
                 "published_at":{
                    "lt":"2022-06-21 14:23:58"
                 }
              }
           }
        ],
        "must_not":[
           {
              "terms":{
                 "categories.id":[
                    "2754",
                    "2377"
                 ]
              }
           }
        ],
        "should":[
           {
              "multi_match":{
                 "fields":[
                    "title",
                    "code",
                    "seo.title",
                    "categories.title",
                    "subtitle",
                    "part_number"
                 ],
                 "boost":10,
                 "type":"phrase",
                 "tie_breaker":0.3,
                 "query":"cpu"
              }
           },
           {
              "multi_match":{
                 "fields":[
                    "title",
                    "seo.title",
                    "categories.title",
                    "subtitle"
                 ],
                 "type":"most_fields",
                 "fuzziness":"AUTO",
                 "query":"cpu"
              }
           }
        ]
     }
  },

and this is my script sort query:

{
        "_script": {
            "type": "number",
            "script": {
                "lang": "painless",
                "source": "if(Math.abs(doc['product_quantity'].value) > 0) { 1 } else { 1 }"
            },
            "order":"desc"
        }
    },
    {
        "_score":"desc"
    }

but it is not accurate. my question is what is the best way to search with analyzer and set higher score to products with higher than zero quantity to show at the top.

CodePudding user response:

Your sort clause should be like below, else clause should have value 0 and not 1:

"sort": [
    {
      "_script": {
            "type": "number",
            "script": {
                "lang": "painless",
                "source": "if(Math.abs(doc['qty'].value) > 0) { 1 } else { 0 }"
            },
            "order":"desc"
        }
    },
    {
        "_score":"desc"
    }
  ]
  • Related