0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Use function_score Query in Elasticsearch

Use the function_score query in Elasticsearch to modify the score of documents returned by a query by applying custom functions like weights or field values. It wraps a query and applies scoring functions to boost or adjust relevance dynamically.
📐

Syntax

The function_score query wraps a base query and applies one or more scoring functions to adjust the relevance score of each document. Key parts include:

  • query: The base query to select documents.
  • functions: An array of scoring functions like weight, random_score, or field_value_factor.
  • score_mode: How to combine multiple function scores (e.g., sum, multiply).
  • boost_mode: How to combine the function score with the original query score (e.g., multiply, replace).
json
{
  "function_score": {
    "query": { <base_query> },
    "functions": [
      { <function_1> },
      { <function_2> }
    ],
    "score_mode": "sum",
    "boost_mode": "multiply"
  }
}
💻

Example

This example boosts documents matching "status": "active" by a weight of 2 and adds a random score to diversify results.

json
{
  "query": {
    "function_score": {
      "query": {
        "match": { "status": "active" }
      },
      "functions": [
        {
          "weight": 2
        },
        {
          "random_score": {}
        }
      ],
      "score_mode": "sum",
      "boost_mode": "multiply"
    }
  }
}
Output
{ "hits": { "total": {"value": 3, "relation": "eq"}, "hits": [ {"_score": 3.5, "_source": {"status": "active", "name": "Doc1"}}, {"_score": 2.8, "_source": {"status": "active", "name": "Doc2"}}, {"_score": 2.1, "_source": {"status": "active", "name": "Doc3"}} ] } }
⚠️

Common Pitfalls

  • Not specifying a query inside function_score causes all documents to be scored, which may be unintended.
  • Using incompatible score_mode or boost_mode can lead to unexpected scoring results.
  • Forgetting to use weight or other functions inside functions array results in no score modification.
  • Random scores without a seed can cause inconsistent results across queries.
json
{
  "query": {
    "function_score": {
      "functions": [
        { "weight": 3 }
      ]
    }
  }
}

-- This will score all documents without filtering.

{
  "query": {
    "function_score": {
      "query": { "match_all": {} },
      "functions": [
        { "weight": 3 }
      ],
      "score_mode": "multiply",
      "boost_mode": "replace"
    }
  }
}

-- Correct way to apply weight to all documents with explicit query and modes.
📊

Quick Reference

ParameterDescriptionExample Values
queryBase query to select documents{"match": {"field": "value"}}
functionsArray of scoring functions[{"weight": 2}, {"random_score": {}}]
score_modeHow to combine function scores"sum", "multiply", "avg", "max", "min"
boost_modeHow to combine function score with query score"multiply", "replace", "sum", "avg", "max", "min"
weightMultiplier to boost score2, 5, 10
random_scoreAdds randomness to scores{}
field_value_factorUses numeric field value to influence score{"field": "popularity"}

Key Takeaways

The function_score query lets you customize document scores by combining a base query with scoring functions.
Use the functions array to apply weights, random scores, or field-based factors to influence relevance.
Always specify a base query inside function_score to avoid scoring all documents unintentionally.
Choose score_mode and boost_mode carefully to control how scores combine for expected results.
Random scores without a seed can cause different results on each query run.