# Scoring expressions

A scoring expression replaces each match's score with a formula you write. The formula can read the
text score and the document's own fields, so popularity, freshness, distance, stock and margin can
all count toward the order without changing which documents match. This page covers
the native `rescore` query, the functions an expression can use, and the Elasticsearch and Solr
forms that produce the same thing.

For when to use an expression rather than a filter, a sort or a fusion weight, see
[Ranking with business signals](ranking-with-business-signals.md).

## A first rescore

`rescore` takes a query and an expression. The query decides what matches, and the expression
decides each match's score. `score` in the expression is the query's own score:

```bash
curl -s https://api.warpsearch.io/v1/search/books \
  -H "Authorization: Bearer $WARPSEARCH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "language": "warpsearch",
    "query": "rescore(title_t:$q, expr=score * log1p(def(popularity_i, 0)))",
    "vars": {"q": "dune"},
    "limit": 10,
    "fields": ["id", "title_t", "popularity_i"]
  }'
```

This ranks matches for `dune` by text relevance times the log of their popularity. `log1p` damps
the popularity, so a book with a million sales does not bury one with a thousand that matches
the query better.

| Part | Meaning |
|---|---|
| First argument | The query whose matches are scored, in `warpsearch` syntax: `title_t:$q`, `title_t:dune AND year_i:>=1960`, and so on. |
| `expr` | The new score: a number computed per document. `score` (or `_score`) is the query's score. |
| `min_score` | Optional. Documents whose new score is below it no longer match. See [Cut-offs](#cut-offs). |
| `vars` | Values for `$name` placeholders, in the request's `vars`. A value is never parsed as syntax, so put user input here. |

Every match gets the expression, not only the top page. There is no rescoring window. Scores are
then sorted as usual, and `filters`, `sort`, facets and paging work as on any search.

### Who can send native queries

`rescore` is part of the `warpsearch` language, which is WarpSearch's own query syntax (see
[Native queries](query-languages.md#native-queries-and-replays)). It has these conditions:

- On the free plan, an unsigned `warpsearch` request is refused with `403 feature_not_available`. Use
  a paid plan, or send a signed replay from `include_translation`.
- A collection with row filters or field restrictions accepts only signed replays.
- Expressions name fields the way the collection stores them. That is the name you defined in the
  schema. A field created from an Elasticsearch mapping with `.` or `@` in its name is stored with
  `_` instead, so `event.created` is `event_created` here. See [Mappings](compat-elasticsearch.md#mappings).

The [Elasticsearch](#from-elasticsearch-function-score) and [Solr](#from-solr) forms below have
none of these conditions, and cover the common functions.

## Missing values

A document without a value for a field has no value for any expression that reads it. Missing is
not zero. A rescore expression has to produce a number for every match, so a missing value fails
the request:

```text
rescore expression is missing for matched segment doc 2; use def() in the expression or exists() in the child query
```

Give a fallback with `def(field, fallback)`, as in `def(popularity_i, 0)`, or match only documents
that have the field: `rescore(title_t:$q AND exists(popularity_i), expr=...)`.

Division by zero also makes a value missing. A result that is NaN or infinite, or an integer that
overflows, is an error that names the function.

## Expressions

An expression is arithmetic over numbers, fields, `score` and `$vars`, with the usual precedence:
`*`, `/` and `%` before `+` and `-`. Integers stay exact, and a decimal operand makes the operation
decimal. A `boolean` field reads as 1 or 0.

| Kind | Functions and operators |
|---|---|
| Arithmetic | `+ - * / %`, `abs`, `min(a, b)`, `max(a, b)`, `clamp(x, lo, hi)` |
| Fallback | `def(value, fallback)`: `fallback` when `value` is missing |
| Comparison and logic | `< <= > >= == !=` return 1 or 0. `&&`, `\|\|`, `!` treat nonzero as true. |
| Conditional | `cond ? a : b`, or `if(cond, a, b)`. Only the chosen branch is evaluated, so `x_i > 0 ? log(x_i) : 0` is safe. |
| Logs and powers | `log` (natural), `log1p`, `log2`, `log10`, `logn(base, x)`, `exp`, `expm1`, `pow`, `sqrt`, `cbrt` |
| Rounding | `floor`, `ceil`, `round`, `rint`, `trunc`, `signum`, `to_int`, `to_double` |
| Decay | `gauss_decay`, `exp_decay`, `linear_decay`. See [Decay](#decay). |
| Geo | `geo_distance(field, lat, lon)` in meters, `geo_lat`, `geo_lon`, `haversin` (km), `geo_bearing`, `geo_in_box` |
| Dates | `year`, `month`, `day_of_month`, `day_of_week`, `day_of_year`, `hour`, `minute`, `quarter`, `week_of_year`, `epoch_millis` |
| Multi-valued fields | `min`, `max`, `avg`, `sum`, `count` with one argument reduce a document's values |
| Random | `random(seed, field)`: a stable value in [0, 1) per document, keyed by a numeric field |
| Local names | `let(name, value, body)` computes `value` once and uses it as `name` in `body` |
| Other | Trigonometry, bitwise operators, `col("name")` for a field whose name is not a plain word |

`random` needs a seed and a single-valued numeric field, as in `random(42, id_i)`, so a document
keeps its value when the collection changes. Use it to vary the order of equally good results
between users without reshuffling on every request.

## Recipes

### Damped popularity

```text
rescore(title_t:$q, expr=score * log1p(def(popularity_i, 0)))
```

Multiplying keeps relevance in charge: a document that matches poorly stays low however popular it
is. A document with no popularity gets `log1p(0) = 0`. If unpopular documents should still appear,
add a floor: `score * (1 + log1p(def(popularity_i, 0)))`.

To bound the effect, clamp it: `score * clamp(1 + log1p(def(popularity_i, 0)) / 10, 1, 1.5)`
lifts a document by at most half its text score.

### Recency

Dates are numbers in an expression: epoch milliseconds for a `date` field, epoch nanoseconds for a
nanosecond date field. Durations use the same unit, so one day is `86400000`. Pass the current time
as a variable:

```json
{
  "language": "warpsearch",
  "query": "rescore(title_t:$q, expr=score * (0.8 + 0.2 * exp_decay(published_dt, $now, $month)))",
  "vars": {"q": "dune", "now": 1796083200000, "month": 2592000000}
}
```

The decay is 1 for a document published now, 0.5 a month ago, and falls toward 0 after that. The
`0.8 + 0.2 *` form means age can cost a document at most a fifth of its score, so an old document
that matches much better still wins. Use `gauss_decay` instead to leave recent documents almost
untouched and drop off later, and an offset (the fourth argument) for a period that counts as
fully fresh.

### Distance

```text
rescore(description_t:coffee, expr=score * gauss_decay(geo_distance(location_p, 40.758, -73.9855), 0, 2000, 500))
```

Places within 500 meters keep their full score, and the score halves at 2.5 km. For the
Elasticsearch form and the decay shapes, see
[Boost nearby results](geo-distance-and-nearest.md#boost-nearby-results).

### Conditional boost

```text
rescore(title_t:$q, expr=def(in_stock_b, 0) ? score * 1.2 : score * 0.8)
```

A conditional can also gate a boost on relevance, so a weak match cannot ride on popularity:

```text
rescore(title_t:$q, expr=score > $t ? score * (1 + 0.2 * log1p(def(popularity_i, 0))) : score)
```

Text scores depend on the query and the collection, so pick the threshold from real queries, and
check it again when the collection changes.

### Priors

A prior is how likely a document is to be relevant before the query is known: its authority,
quality or popularity. There are two common ways to combine one with the text score:

| Form | Effect |
|---|---|
| `score * prior` | The prior scales relevance. A prior near 0 removes the document from the top. |
| `score + w * log(prior)` | The prior adds a fixed amount, whatever the match quality. `w` sets how much. |

Both are modelling choices. Try both against a [judgment list](tuning-relevance.md#offline-evaluation-with-judgment-lists).

## Decay

```text
gauss_decay(value, origin, scale, offset, decay)
exp_decay(value, origin, scale, offset, decay)
linear_decay(value, origin, scale, offset, decay)
```

`offset` defaults to 0 and `decay` to 0.5. With `d = max(0, |value - origin| - offset)`, each returns
1 when `d` is 0, and `decay` when `d` equals `scale`:

| Function | Score | Shape |
|---|---|---|
| `gauss_decay` | `exp(ln(decay) * (d / scale)^2)` | Flat near the origin, then falls quickly. |
| `exp_decay` | `exp(ln(decay) * d / scale)` | Falls fastest close in, with a long tail. |
| `linear_decay` | `max(0, 1 - d * (1 - decay) / scale)` | Falls in a straight line and reaches 0. |

`value` is a number, a date or a `geo_distance(...)` in meters. `origin`, `scale`, `offset` and
`decay` must be constants or `$vars`. A document with no value scores 1. For a multi-valued field,
the value closest to the origin counts.

## Cut-offs

`min_score` removes documents whose new score is below it. They are gone from the hits, the total
and the facets alike:

```text
rescore(title_t:$q, expr=score * log1p(def(popularity_i, 0)), min_score=2)
```

To cut on a query's own score, keep `score` as the expression:
`rescore(title_t:$q, expr=score, min_score=1.5)`. As with any score threshold, the right value
depends on the collection, so measure it.

## From Elasticsearch: function_score

With `"language": "es"` and on the [Elasticsearch-compatible API](compat-elasticsearch.md), a
`function_score` query becomes the same rescore, and needs no paid plan or signature.
`field_value_factor`, `gauss`, `exp` and `linear` decays on numbers, dates and geo points,
`random_score`, `weight`, filtered functions, `score_mode`, `boost_mode`, `max_boost` and
`min_score` all work:

```json
{
  "language": "es",
  "query": {"function_score": {
    "query": {"match": {"title_t": "dune"}},
    "functions": [
      {"field_value_factor": {"field": "popularity_i", "modifier": "log1p", "missing": 0}},
      {"gauss": {"published_dt": {"origin": "now", "scale": "30d"}}}
    ],
    "score_mode": "multiply",
    "boost_mode": "multiply",
    "min_score": 0.5
  }}
}
```

To see the native expression a `function_score` becomes, add `"include_translation": true` and read
`translation.replay`. Elasticsearch's `log` and `log1p` modifiers are base 10, and the translation
divides by `ln(10)`, whereas `log` and `log1p` in a native expression are natural logs.

Translated queries use a smaller set of functions: arithmetic, `abs`, `sqrt`, `log`, `log1p`,
`floor`, `exp`, `pow`, `min`, `max`, `sum`, `avg`, `count`, comparisons, logic and conditionals,
the three decays and `random`. Date parts, `let`, `clamp`, rounding, trigonometry and the geo
functions other than distance decay need the native form. `script_score` and Painless scripts are
not supported.

### Around a vector search

The wrapped query can be a `knn` query, a geo query or any other query. Around a `knn` query, the
functions rescore the `k` nearest neighbors, which blends similarity with business signals:

```json
{
  "language": "es",
  "query": {"function_score": {
    "query": {"knn": {"field": "embedding_v", "query_vector": [0.75, 0.15, 0.10], "k": 50}},
    "functions": [{"field_value_factor": {"field": "popularity_i", "modifier": "log1p", "missing": 0}}],
    "boost_mode": "multiply"
  }}
}
```

Only the `k` neighbors are candidates: the functions reorder them but cannot bring in a popular
document that is not among them, so ask for more neighbors than you return. Inside a fusion, make this
`function_score` the query of a `standard` retriever to get a popularity-weighted vector source (see
[A boosted source](hybrid-search.md#a-boosted-source)). The native language has
no `knn` syntax, so this form is the way to rescore vector results.

## From Solr

Solr's `bf` and `boost` parameters on `dismax` and `edismax`, `{!func}` and `{!frange}` become
expressions too, with the same function set as `function_score`. See [Solr](compat-solr.md).

## Sorting by an expression

The same expressions can order results outright instead of rescoring them: with
`"language": "warpsearch"`, a sort key `{"expr": "...", "desc": true}`. See
[Sort by an expression](searching.md#sort-by-an-expression).

## Where to go next

1. [Ranking with business signals](ranking-with-business-signals.md) for choosing between filters,
   expressions, sorts and fusion.
2. [Tuning relevance](tuning-relevance.md) for field weights and judgment lists.
3. [Hybrid search](hybrid-search.md#sources) to use a boosted query as one source of a fusion.
