Painless Script - Custom Scoring

Plainless Script Exploration Part #1

·

1 min read

In this series, we will explore multiple ways in how Painless scripts can be used and how it can make your use cases grow.

In this example, we will explore how we can customise the scoring of a document based on a certain logic.

Lets dive in directly to code:

POST products/_search
{
  "query": {
    "function_score": {
      "functions": [
        {
          "script_score": {
            "script": {
              "lang": "painless",
              "source": "double priceToWeight = doc['price'].value / doc['weight'].value; return priceToWeight;"
            }
          }
        }
      ]
    }
  }
}

In this example, the function_score query is used to apply a custom scoring function to the search results. The functions array contains a single function that uses the script_score function to apply a Painless script to each document in the search results.

The Painless script calculates the price-to-weight ratio of each product by dividing the value of the price field by the value of the weight field, and returns this value as the score for the document.

Note that the doc['price'].value and doc['weight'].value expressions access the values of the price and weight fields in the document being scored.

This sums up the article, However, we are going to explore more painless script ways in the upcoming article.

If you have any other ideas or suggestions, please do share them in the comments or connect with me on Twitter.