Customizing Search Result Scoring in Elasticsearch
Elasticsearch’s default relevance ranking works fine for basic search, but real products usually need more control. E-commerce sites factor in popularity and ratings, news platforms weigh recency and authority, and internal knowledge bases care about document importance. Function Score Query lets you plug those business rules into the score so results rank the way your product actually needs.
Every hit returned by an Elasticsearch query has a relevance score, and results are sorted by score descending by default.
function_score queries let you customize how that final score is computed.
Scoring logic
We’ll use three shorthand terms throughout this post:
def_score: Elasticsearch’s default query scorefun_score: the score produced by your custom scoring functionult_score: the final score used to rank documents
Without a function_score query, def_score equals ult_score.
With a function_score query, ult_score is calculated in three steps:
- Run the base query to get
def_score. - Run the custom scoring function(s) to compute a new score,
fun_score, for each document. - Combine
fun_scoreanddef_scoreaccording to a chosen mode (multiplication by default) to produceult_score.
Basic usage:
1 | POST index/_search |
How def_score and fun_score are combined is controlled by boost_mode:
multiply: multiply (default),ult_score = def_score * fun_scorereplace: replace,ult_score = fun_scoresum: add,ult_score = def_score + fun_scoreavg: average of both,ult_score = Avg(def_score, fun_score)max: maximum of both,ult_score = Max(def_score, fun_score)min: minimum of both,ult_score = Min(def_score, fun_score)
Scoring functions
weight
Basic usage:
1 | POST index/_search |
This boosts every matching document by the same factor, scaling all def_score values proportionally without changing their relative order.
To control which documents get boosted, pair weight with a filter:
1 | POST index/_search |
Now only documents where brand_name matches "西门子" (Siemens) get their def_score boosted, pushing the documents we care about closer to the top.
random_score
random_score generates a random number in the [0, 1) range.
Basic usage:
1 | POST index/_search |
Written like this, the result order changes on every request.
If you need a given user to see a consistent randomized order across requests, pass a per-user seed:
1 | POST index/_search |
That gives you consistent ordering, but Elasticsearch will emit a warning:

In short, starting in Elasticsearch 7.0, whenever you set seed you also need to provide a field parameter.
Without field, Elasticsearch falls back to Lucene doc IDs as the source of randomness, which uses a lot of memory.
The official recommendation is to set field to _seq_no (the index sequence number).
Note: if a document gets updated, its _seq_no changes too, which will change its random score.
1 | POST index/_search |
field_value_factor
Uses the value of a specified document field to calculate ult_score.
For example, suppose a brand index has a numeric sort field and we want matching documents ranked using it:
1 | POST index/_search |
field: the target fieldfactor: multiplier applied to the field value (defaults to1)missing: fallback value used whenfieldis missing from a documentmodifier: smoothing function applied to prevent extreme score gaps:none: no transformation (default)log: base-10 logarithm,log(factor * field_value)log1p: base-10 logarithm,log(1 + factor * field_value)log2p: base-10 logarithm,log(2 + factor * field_value)ln: natural logarithm,ln(factor * field_value)ln1p: natural logarithm,ln(1 + factor * field_value)ln2p: natural logarithm,ln(2 + factor * field_value)square: square,(factor * field_value)^2sqrt: square root,sqrt(factor * field_value)reciprocal: reciprocal,1/(factor * field_value)
With the query above, if document A has def_score = 0.8 and sort = 5, then:
ult_score = 0.8 * ln(1.5 * 5) = 1.612
Decay functions (decay_function)
Decay functions start from a central point (a date, number, or geo-location) and gradually reduce the score as distance from that point increases.
Basic usage:
1 | POST index/_search |
Three decay curves are available:
linear: linear functionexp: exponential functiongauss: Gaussian function
Parameters:
origin: the center point (number, date, or coordinates)scale: distance from the origin at which the score decays todecayoffset: flat plateau aroundoriginbefore decay beginsdecay: score value atorigin ± (offset + scale)
With origin set to 2000-01-05 and scale set to 10 days (plus offset of 5 days):
Documents with created_at between 2000-01-01 and 2000-01-10 receive a full weight of 1.
Documents outside scale + offset = 15 days drop to a weight of 0.5 (at the 15-day mark and lower beyond it).
script_score
The most flexible scoring function of all:
1 | POST index/_search |
Use doc['field_name'].value to read a field’s value.
source can hold whatever custom formula you need.
[Update]
Avoid hard-coding constants. Pass them through params instead, so the script stays flexible and Elasticsearch doesn’t have to recompile source every time a parameter changes:
1 | POST index/_search |
Note: script compilation is expensive, so Elasticsearch rate-limits it as a built-in safeguard. By default, it allows at most 150 script compilations per 5 minutes.
You can adjust that limit via cluster settings:
1 | PUT _cluster/settings |
You can also save and reuse scripts with the Stored Scripts API to cut down compilation time and speed up search:
1 | POST /_scripts/calc_score |
Calling a stored script:
1 |
|
Deleting a stored script:
1 | DELETE _scripts/calc_score |