A function score query is an Elasticsearch compound query that wraps a matching query and modifies or replaces its relevance score with user-defined functions. Use it when built-in relevance is not enough—for example, when product ratings, brand preference, sponsorship, or randomness should influence ranking. section 11.0 section 11.7
A function_score query can:
- Wrap a term or other leaf query while preserving its matching behavior. section 11.7
- Apply random_score, script_score, decay functions, weights, or field values. section 11.7
- Combine multiple function results with score_mode, then combine that result with the original query score through boost_mode. section 11.7.4
Prefer LG televisions with high ratings
Search for TVs, add weight to LG products, and amplify ratings from 4.5 through 5 by squaring the rating and multiplying it by five. The functions use avg, while their combined score is added to the original term-query score. section 11.7.4
Listing 11.31 Two functions producing a unified score
GET products/_search
{
"query": {
"function_score": {
"query": {
"term": {
"product": "TV"
}
},
"functions": [ #1
{
"filter": {
"term": {
"brand": "LG"
}
},
"weight": 3 #2
},
{
"filter": {
"range": {
"user_ratings": {
"gte": 4.5,
"lte": 5
}
}
},
"field_value_factor": { #3
"field": "user_ratings",
"factor": 5,
"modifier": "square"
}
}
],
"score_mode": "avg",
"boost_mode": "sum"
}
}
}
Inspect a runnable Query DSL example showing filtered scoring functions, weight, field_value_factor, score_mode, and boost_mode. section 11.7.4
Choose function scoring when ranking depends on business requirements rather than only Elasticsearch’s relevance calculation. As more matching functions contribute, a document’s final score can increase and move it higher in the results. section 11.7 section 11.7.4
