Bird
Raised Fist0
Elasticsearchquery~10 mins

Function score query in Elasticsearch - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Function score query
Start: Receive Query
↓
Apply Base Query
↓
Apply Functions to Modify Scores
↓
Combine Function Scores with Base Score
↓
Return Documents with Updated Scores
↓
End
The function score query starts with a base query, applies scoring functions to modify document scores, combines them, and returns the results.
Execution Sample
Elasticsearch
{
  "query": {
    "function_score": {
      "query": { "match": { "field": "value" } },
      "functions": [
        { "weight": 2 },
        { "filter": { "term": { "status": "active" } }, "weight": 3 }
      ],
      "score_mode": "sum"
    }
  }
}
This query matches documents where 'field' contains 'value', then boosts scores by weights, adding extra weight if 'status' is 'active'.
Execution Table
StepActionBase Query ResultFunction AppliedScore ChangeCombined Score
1Run base query match field:valueDoc1=1.0, Doc2=1.0, Doc3=0.0None0Doc1=1.0, Doc2=1.0, Doc3=0.0
2Apply function weight=2 to all docsSame as aboveWeight 2+2Doc1=3.0, Doc2=3.0, Doc3=2.0
3Apply function weight=3 filtered by status:activeSame as aboveWeight 3 if status=active+3 to Doc1 onlyDoc1=6.0, Doc2=3.0, Doc3=2.0
4Combine scores using sum modeFinal scoresSum of weightsN/ADoc1=6.0, Doc2=3.0, Doc3=2.0
💡 All functions applied, scores combined, final ranked documents returned.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
Doc1 Score01.03.06.06.0
Doc2 Score01.03.03.03.0
Doc3 Score00.02.02.02.0
Key Moments - 3 Insights
Why does Doc3 get a score even though it doesn't match the base query?
Because the weight function applies to all documents by default, Doc3 gets a base weight of 2 even with base score 0, as shown in step 2 of the execution_table.
How does the filter in the second function affect scoring?
The filter limits the weight of 3 to only documents where status is active, so only Doc1 gets this extra weight, as seen in step 3 of the execution_table.
What does score_mode 'sum' do with multiple function scores?
It adds all function weights to the base score, combining them by summing, resulting in the final scores shown in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is Doc2's score after applying the first weight function?
A1.0
B4.0
C3.0
D0.0
💡 Hint
Check 'After Step 2' column for Doc2 Score in variable_tracker.
At which step does the filter for status:active apply its weight?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Function Applied' column in execution_table for when the filter is used.
If the score_mode changed from 'sum' to 'multiply', how would Doc1's final score change?
AIt would be 0.0
BIt would be 1.0 * 2 * 3 = 6.0
CIt would be 6.0 multiplied by 3
DIt would be 6.0
💡 Hint
Multiplying base score and weights means multiplying 1.0 (base) * 2 * 3 for Doc1.
Concept Snapshot
Function score query syntax:
{
  "query": {
    "function_score": {
      "query": { ... },
      "functions": [ ... ],
      "score_mode": "sum"|"multiply"|...
    }
  }
}

Behavior: Modifies base query scores by applying functions with optional filters.
Key rule: Functions can boost or modify scores; score_mode controls combination.
Full Transcript
The function score query starts by running the base query to find matching documents. Then, it applies one or more functions that adjust the scores of these documents. Each function can have a filter to apply only to certain documents and a weight to boost scores. The scores from all functions combine using a mode like sum or multiply. For example, a base query matches documents with 'field' equal to 'value'. A weight function adds 2 to all documents' scores. Another function adds 3 only to documents where 'status' is 'active'. The final scores are the sum of base scores and these weights. This process helps rank documents better based on custom criteria.

Practice

(1/5)
1. What is the main purpose of a function_score query in Elasticsearch?
easy
A. To update documents in the index
B. To filter documents based on exact matches only
C. To customize how search results are ranked by modifying their scores
D. To delete documents matching a query

Solution

  1. Step 1: Understand the role of function_score query

    The function_score query is designed to change the score of documents returned by a query, allowing customization of ranking.
  2. Step 2: Compare with other query types

    Filtering or updating documents are different operations; function_score specifically adjusts scoring.
  3. Final Answer:

    To customize how search results are ranked by modifying their scores -> Option C
  4. Quick Check:

    Function score query = Custom ranking [OK]
Hint: Function score changes ranking by adjusting scores [OK]
Common Mistakes:
  • Confusing function_score with filtering queries
  • Thinking it updates or deletes documents
  • Assuming it only filters exact matches
2. Which of the following is the correct basic structure of a function_score query in Elasticsearch?
easy
A. { "function_score": { "query": { ... }, "functions": [ ... ] } }
B. { "function_score": [ { "query": { ... } }, { "functions": [ ... ] } ] }
C. { "query": { "function_score": { "functions": [ ... ] } } }
D. { "functions": { "function_score": { "query": { ... } } } }

Solution

  1. Step 1: Recall function_score query JSON format

    The function_score query wraps a query and a list of scoring functions inside an object with keys "query" and "functions".
  2. Step 2: Validate option structure

    { "function_score": { "query": { ... }, "functions": [ ... ] } } correctly shows the function_score object containing "query" and "functions" keys as expected.
  3. Final Answer:

    { "function_score": { "query": { ... }, "functions": [ ... ] } } -> Option A
  4. Quick Check:

    Correct JSON structure = { "function_score": { "query": { ... }, "functions": [ ... ] } } [OK]
Hint: Look for "function_score" with nested "query" and "functions" keys [OK]
Common Mistakes:
  • Using arrays instead of objects for function_score
  • Placing functions outside function_score
  • Incorrect nesting of query and functions
3. Given this function_score query snippet, what is the effect of the weight parameter?
{
  "function_score": {
    "query": { "match": { "title": "elasticsearch" } },
    "functions": [
      { "weight": 3 }
    ]
  }
}
medium
A. It adds 3 points to the original score
B. It multiplies the original score of matching documents by 3
C. It filters out documents with score less than 3
D. It sets the score of all documents to 3

Solution

  1. Step 1: Understand the weight function in function_score

    The weight function multiplies the score of matching documents by the given weight value.
  2. Step 2: Analyze the query snippet

    The query matches documents with "title" containing "elasticsearch" and applies a weight of 3, multiplying their scores by 3.
  3. Final Answer:

    It multiplies the original score of matching documents by 3 -> Option B
  4. Quick Check:

    Weight multiplies score = It multiplies the original score of matching documents by 3 [OK]
Hint: Weight multiplies scores, not adds or filters [OK]
Common Mistakes:
  • Thinking weight adds to score instead of multiplying
  • Confusing weight with filtering
  • Assuming weight sets fixed score
4. Identify the error in this function_score query:
{
  "function_score": {
    "query": { "match": { "content": "search" } },
    "functions": {
      "weight": 2
    }
  }
}
medium
A. Missing "score_mode" field
B. "weight" cannot be used inside functions
C. "query" must be inside "functions"
D. "functions" should be an array, not an object

Solution

  1. Step 1: Check the type of "functions" field

    The "functions" field must be an array of function objects, not a single object.
  2. Step 2: Identify the error in the query

    Here, "functions" is incorrectly given as an object with "weight" key instead of an array containing that object.
  3. Final Answer:

    "functions" should be an array, not an object -> Option D
  4. Quick Check:

    Functions must be array = "functions" should be an array, not an object [OK]
Hint: Functions must be an array of objects [OK]
Common Mistakes:
  • Using object instead of array for functions
  • Placing query inside functions
  • Assuming score_mode is mandatory
5. You want to boost documents with a popularity field greater than 10 by a factor of 5 using a function_score query. Which snippet correctly applies this boost?
hard
A. { "function_score": { "query": { "match_all": {} }, "functions": [ { "filter": { "range": { "popularity": { "gt": 10 } } }, "weight": 5 } ] } }
B. { "function_score": { "query": { "range": { "popularity": { "gt": 10 } } }, "weight": 5 } }
C. { "function_score": { "query": { "match_all": {} }, "weight": 5, "filter": { "range": { "popularity": { "gt": 10 } } } } }
D. { "function_score": { "query": { "match_all": {} }, "functions": { "weight": 5, "filter": { "range": { "popularity": { "gt": 10 } } } } } }

Solution

  1. Step 1: Understand boosting with filter and weight

    To boost only documents matching a condition, use a function with a "filter" and a "weight" inside the "functions" array.
  2. Step 2: Analyze each option

    { "function_score": { "query": { "match_all": {} }, "functions": [ { "filter": { "range": { "popularity": { "gt": 10 } } }, "weight": 5 } ] } } correctly uses "functions" as an array with a filter on popularity > 10 and weight 5. Other options misuse weight placement or structure.
  3. Final Answer:

    { "function_score": { "query": { "match_all": {} }, "functions": [ { "filter": { "range": { "popularity": { "gt": 10 } } }, "weight": 5 } ] } } -> Option A
  4. Quick Check:

    Filter + weight inside functions array = { "function_score": { "query": { "match_all": {} }, "functions": [ { "filter": { "range": { "popularity": { "gt": 10 } } }, "weight": 5 } ] } } [OK]
Hint: Use filter and weight inside functions array to boost conditionally [OK]
Common Mistakes:
  • Placing weight outside functions array
  • Using object instead of array for functions
  • Applying weight directly on query instead of functions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard