ES function_score allows you to modify the scores of documents searched by a query. This is especially useful when the scoring function is computationally expensive, and you only need to compute scores for a filtered set of documents. script_score is a type of function_score that supports using scripts to provide custom scoring for returned documents. Using script_score with User Profiles and Click Behavior Data for Scoring
ES's script_score query is a powerful advanced feature popular among ES developers in text search scenarios. It allows you to use scripts to customize document scoring, combining text relevance with business metrics for complex sorting logic. For example, you can combine user profiles and click behavior data to better optimize sorting results for more accurate search and recommendations, bringing great flexibility and practicality to your business implementations.
GET /_search
{
"query": {
"function_score": {
"query": {
"match": { "message": "elasticsearch" }
},
"script_score": {
"script": {
"source": "Math.log(2 + doc['my-int'].value)"
}
}
}
}
}
Using script_score for Brute-Force Vector Search with Caution
However, when script_score is used for vector search (see here), it performs brute-force scanning (even if you set the index type to hnsw in the index mapping), rather than the approximate k-nearest neighbor (kNN) search defined in your index settings. The script reads the stored title_vector field value for every document within the range and calls built-in vector functions (such as cosineSimilarity) to compute against the passed-in query vector parameter. Vector search performance will drop dramatically. Therefore, unless for small datasets (< 100,000) or scenarios requiring exact results, we generally do not recommend using script_score for vector search. GET my-index/_search
{
"query": {
"script_score": {
"query" : {
"bool" : {
"filter" : {
"term" : {
"status" : "published"
}
}
}
},
"script": {
"source": "cosineSimilarity(params.query_vector, 'title_vector') + 1.0",
"params": {
"query_vector": [4, 3.4, -0.2]
}
}
}
}
}