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 score
  • fun_score: the score produced by your custom scoring function
  • ult_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:

  1. Run the base query to get def_score.
  2. Run the custom scoring function(s) to compute a new score, fun_score, for each document.
  3. Combine fun_score and def_score according to a chosen mode (multiplication by default) to produce ult_score.

Basic usage:

1
2
3
4
5
6
7
8
9
POST index/_search
{
"query": {
"function_score": {
"query": {"match": {"material_no": "acti"}},
"boost_mode": "multiply"
}
}
}

How def_score and fun_score are combined is controlled by boost_mode:

  • multiply: multiply (default), ult_score = def_score * fun_score
  • replace: replace, ult_score = fun_score
  • sum: add, ult_score = def_score + fun_score
  • avg: 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
2
3
4
5
6
7
8
9
POST index/_search
{
"query":{
"function_score":{
"query":{"match":{"material_no":"acti"}},
"weight":5
}
}
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
POST index/_search
{
"query":{
"function_score":{
"query:"{"match":{"material_no":"acti"}},
"functions":[
{
"filter":{"match":{"brand_name":"西门子"}},
"weight":5
}
]
}
}
}

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
2
3
4
5
6
7
8
9
POST index/_search
{
"query":{
"function_score":{
"query":{"match":{"material_no":"acti"}},
"random_score":{}
}
}
}

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
2
3
4
5
6
7
8
9
10
11
POST index/_search
{
"query":{
"function_score":{
"query":{"match":{"material_no":"acti"}},
"random_score":{
"seed":10
}
}
}
}

That gives you consistent ordering, but Elasticsearch will emit a warning:

image-2022052682009192 PM

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
2
3
4
5
6
7
8
9
10
11
12
POST index/_search
{
"query":{
"function_score":{
"query":{"match":{"material_no":"acti"}},
"random_score":{
"seed":10,
"field":"_seq_no"
}
}
}
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
POST index/_search
{
"query":{
"function_score":{
"query":{"match_all":{}},
"field_value_factor":{
"field":"sort",
"factor":1.5,
"missing":0,
"modifier":"ln"
}
}
}
}
  • field: the target field
  • factor: multiplier applied to the field value (defaults to 1)
  • missing: fallback value used when field is missing from a document
  • modifier: 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)^2
    • sqrt: 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
POST index/_search
{
"query":{
"function_score":{
"query":{"match_all":{}},
"gauss":{
"created_at":{
"origin":"2000-01-05",
"scale":"10d",
"offset":"5d",
"decay":0.5
}
}
}
}
}

Three decay curves are available:

  • linear: linear function
  • exp: exponential function
  • gauss: Gaussian function

Parameters:

  • origin: the center point (number, date, or coordinates)
  • scale: distance from the origin at which the score decays to decay
  • offset: flat plateau around origin before decay begins
  • decay: score value at origin ± (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
2
3
4
5
6
7
8
9
10
11
12
13
POST index/_search
{
"query":{
"function_score":{
"query":{"match_all":{}},
"script_score":{
"script":{
"source":"Math.log(2+doc['sort'].value)"
}
}
}
}
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
POST index/_search
{
"query":{
"function_score":{
"query":{"match_all":{}},
"script_score":{
"script":{
"source":"Math.log('multiplier'+doc['sort'].value)",
"params":{"multiplier":2}
}
}
}
}
}

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
2
3
4
PUT _cluster/settings
{
"transient" : {"script.max_compilations_rate" : "100/1m"}
}

You can also save and reuse scripts with the Stored Scripts API to cut down compilation time and speed up search:

1
2
3
4
5
6
7
POST /_scripts/calc_score
{
"script": {
"lang": "painless",
"source": "Math.log(_score * 2) + params['multiplier']"
}
}

Calling a stored script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

POST product4/_search
{
"query": {
"function_score": {
"query": { "match_all": {}},
"script_score": {
"script": {
"id": "calc_score",
"params": {"multiplier": 2}
}
}
}
}
}

Deleting a stored script:

1
DELETE _scripts/calc_score