ElasticSearch
Constant Score Query
Function Score Query
Search Query Comparison
Database Management

ElasticSearch constant_score query vs function_score query

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Elasticsearch provides a variety of ways to customize and boost query results according to specific criteria. Two such query types in Elasticsearch’s rich query DSL (Domain Specific Language) are constant_score and function_score. These queries modify the usual scoring mechanism to fit particular use cases, whether by ignoring score completely or adjusting it according to specified functions. Below, we delve deeper into each of these queries, outlining their purposes, differences, and practical applications.

Understanding the Constant Score Query

The constant_score query is used when you want to return all matching documents with an equal score, regardless of their match strength according to the standard scoring algorithm. That is, it wraps a filter (or a query that acts as a filter) and assigns a single, constant score to all documents that pass the filter.

This is particularly useful in scenarios where you only care about whether a document matches the criteria and not how well it matches. A typical use case is filtering documents in binary conditions, such as when documents either fit or do not fit the specified criteria, with no gradation between matches deemed necessary.

Example of constant_score:

json
1GET /_search
2{
3  "query": {
4    "constant_score": {
5      "filter": {
6        "term": { "status": "active" }
7      },
8      "boost": 1.2
9    }
10  }
11}

In the example above, all documents where the status field is active are returned with the same score of 1.2.

Understanding the Function Score Query

The function_score query provides a much more flexible approach compared to the constant_score query. It allows you to modify the scores of documents that match a specified query. The modification can be done using a variety of functions, such as:

  • Weight: Adjust the score of documents with a certain weight.
  • Field Value Factor: Use a numeric field from the document to influence the score.
  • Random Score: Apply a random score to add elements of chance.
  • Decay Functions: Decrease the score based on a field value’s proximity to a specified value.

These functions can be combined and further controlled with factors such as boost_mode and score_mode to fine-tune how the computed scores influence the final score used for ranking documents.

Example of function_score:

json
1GET /_search
2{
3  "query": {
4    "function_score": {
5      "query": { "match": { "message": "elasticsearch" }},
6      "boost": "5",
7      "functions": [
8        {
9          "filter": { "match": { "status": "urgent" }},
10          "weight": 2
11        },
12        {
13          "random_score": {}, 
14          "weight": 0.1
15        }
16      ],
17      "max_boost": 10,
18      "score_mode": "max",
19      "boost_mode": "multiply"
20    }
21  }
22}

In this example, documents matching the query message: elasticsearch are initially found then re-scored using additional criteria. If they match the status urgent, their score is increased by a factor of 2, and a random factor is applied with a smaller weight.

Comparison Table: constant_score vs function_score

FeatureConstant Score QueryFunction Score Query
PurposeApply a constant score to all matchesModify scores of matching documents with complex functions
FlexibilityLow (only uses filters)High (various functions and modifiers)
Use CaseBinary match conditionsScoring influenced by multiple factors
PerformanceGenerally faster (simple calculations)Can be slower, depending on complexity

Conclusion

The choice between constant_score and function_score depends largely on your specific needs. Use constant_score when the mere fact of matching is all that matters, while function_score shines when the quality or context of matches influences their relevance. The ability to finely tune how scores are computed in function_score query makes it exceptionally powerful for nuanced search experiences.

By understanding and utilizing these queries effectively, developers and search architects can significantly enhance the quality and relevance of search results in applications powered by Elasticsearch.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.