A function score query lets you change how search results are scored or ranked by applying custom functions. This helps you show more relevant results based on your own rules.
Function score query in Elasticsearch
{
"function_score": {
"query": { ... },
"functions": [
{
"field_value_factor": {
"field": "field_name",
"factor": 1.2,
"modifier": "sqrt"
},
"weight": 2
},
{
"random_score": {}
}
],
"score_mode": "sum",
"boost_mode": "multiply"
}
}The query part defines which documents to search.
The functions array contains scoring functions to adjust scores.
popularity field values.{
"function_score": {
"query": { "match": { "title": "elasticsearch" } },
"functions": [
{
"field_value_factor": {
"field": "popularity",
"factor": 1.5
}
}
]
}
}{
"function_score": {
"query": { "match_all": {} },
"functions": [
{
"random_score": {
"seed": 12345
}
}
],
"score_mode": "sum"
}
}{
"function_score": {
"query": { "term": { "status": "active" } },
"functions": [
{
"weight": 3
}
],
"boost_mode": "replace"
}
}This query searches for documents with "coffee" in the description. It boosts scores based on the rating field using a logarithmic scale and adds extra weight to documents in the "beverages" category. The scores from functions are summed and then multiplied with the original score.
{
"query": {
"function_score": {
"query": {
"match": {
"description": "coffee"
}
},
"functions": [
{
"field_value_factor": {
"field": "rating",
"factor": 2,
"modifier": "log1p"
}
},
{
"weight": 5,
"filter": {
"term": { "category": "beverages" }
}
}
],
"score_mode": "sum",
"boost_mode": "multiply"
}
}
}You can combine multiple functions to fine-tune scoring.
Use score_mode to decide how function scores combine (sum, multiply, max, etc.).
Use boost_mode to decide how function scores combine with the original query score.
Function score query lets you customize how search results are ranked.
You can boost or reduce scores using field values, weights, or random scores.
It helps make search results more relevant to your needs.