dtrix legend
dtrix legend

Reputation: 13

Elasticsearch - boost some documents on top if sorted on a field value

This is my current elastic query. Currently its sorted based on review_rating. I want some products to be boosted on top of it. Is there any way to update the script function to update the review_rating value so that product_id "abc-xyz" and "dfgh-rt" can be boosted on the top.

GET products/_search
{
    "query": {
        "boosting": {
            "positive": {
                "function_score": {
                    "query": {
                        "bool": {
                            "boost": "0.1",
                            "must": [
                                {
                                    "match_all": {}
                                }
                            ]
                        }
                    },
                    "boost_mode": "avg",
                    "score_mode": "sum",
                    "functions": [
                        {
                            "script_score": {
                                "script": {
                                    "source": "double mscore;\n  int initBoostFactor = params.initBoostFactor;\nif(params.boost_products.size()>0 && (doc[params.boost_field].size()!=0 && params.boost_products.contains(doc[params.boost_field].value))){\n mscore=(priority+1)*initBoostFactor;\n}\n return mscore",
                                    "lang": "painless",
                                    "params": {
                                        "boost_products": [
                                            "abc-xyz",
                                            "dfgh-rt"
                                        ]
                                    "initBoostFactor": 100,
                                        "boost_field": "product_id"
                                    }
                                }
                            }
                        }
                    ]
                }
            }
        }
    },
    "sort": [
        {
            "review_rating": {
                "order": "desc"
            }
        }
    ]
}

Upvotes: 0

Views: 578

Answers (1)

Kaveh
Kaveh

Reputation: 1310

You can use pinned query to achieve what you are looking for Pinned query promotes selected documents to rank higher than those matching a given query. This feature is typically used to guide searchers to curated documents that are promoted over and above any "organic" matches for a search. The promoted or "pinned" documents are identified using the document IDs stored in the _id field.

So your query should look like this:

GET /_search
{
  "query": {
    "pinned": {
      "ids": [ "abc-xyz", "dfgh-rt"],
      "organic": {
        [-->your query here<--]
      }
    }
  }
}

Upvotes: 0

Related Questions