tencent cloud

Elasticsearch Service

DokumentasiElasticsearch ServiceVector Search GuideSpecial Note on Using script_score Flexibly and with Caution for Brute-Force Vector Search

Special Note on Using script_score Flexibly and with Caution for Brute-Force Vector Search

Download
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-08-12 18:13:53
Diterjemahkan oleh AI
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": {
// Call the built-in function to compute cosine similarity.
// title_vector is the vector in the document.
// params.query_vector is the query vector passed in from an external source.
// + 1.0 ensures the score is positive (cosine similarity ranges from -1 to 1).
"source": "cosineSimilarity(params.query_vector, 'title_vector') + 1.0",
"params": {
"query_vector": [4, 3.4, -0.2]
}
}
}
}
}

Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan