# Ranking with business signals

Text and vectors say how well a document matches the query. You often know more: that it is new,
popular, nearby, in stock or sponsored. This guide is about putting that knowledge into the ranking
without letting it drown out relevance.

The first question for any signal is what kind of rule it is:

| The signal is | Example | Use |
|---|---|---|
| A rule that must hold | Tenant, permissions, in stock only, category | A [filter](#rules-go-in-filters). It never changes scores. |
| A preference | Newer is better, popular is better, closer is better | A [boost](#boosts) or a [decay](#recency-and-distance) on the score. |
| A strict order | Sponsored first, then by relevance | A [multi-key sort](#strict-order-goes-in-a-sort). |
| A cap on repetition | One result per product, or at most two per brand | [Collapse or diversify](#one-result-per-entity). |

Treating a rule as a preference, or a preference as a rule, is the most common ranking mistake.
A boosted "in stock" still shows sold-out items on a short result page, and a filter on "published
this month" hides the perfect older answer.

## Rules go in filters

Filters narrow the matches without touching scores, and they cost less than scoring clauses. On a
vector search they apply while neighbors are collected, so the `k` nearest are chosen among
eligible documents:

```json
{
  "language": "es",
  "query": { "match": { "title_t": "dune" } },
  "filters": [
    { "term": { "tenant_s": "acme" } },
    { "term": { "in_stock_b": true } }
  ]
}
```

In a fusion, the request's `filters` apply to every source. `post_filters` narrow the hits but not
the facet counts, which is what a selected facet value needs; see
[Faceted navigation](facets-and-aggregations.md#faceted-navigation). For access rules that a client
must not be able to remove, use [access control](access-control.md) instead of request filters.

## Boosts

A boost changes a score with something from the document. There are two shapes:

| Shape | Formula | Behavior |
|---|---|---|
| Multiplicative | `score * f(doc)` | Relevance stays the base. A poor match stays low, however popular. A factor near 0 removes a document from the top. |
| Additive | `score + w * f(doc)` | The signal adds a fixed amount whatever the match quality. Strong enough, it overtakes relevance. |

Start multiplicative. Use additive when the signal should count even for weak matches, and keep
`w` small next to typical text scores.

Damp large numbers. Sales, views and ratings counts span orders of magnitude, so use their log:

```text
rescore(title_t:$q, expr=score * (1 + 0.1 * log1p(def(sales_i, 0))))
```

With this, ten times the sales adds about 0.23 to the multiplier, rather than ten times as much.
The same in Elasticsearch syntax is `field_value_factor` with `"modifier": "log1p"`. See
[Scoring expressions](scoring-expressions.md) and [Function scores](tuning-relevance.md#function-scores).

## Recency and distance

A decay scores a document by how far a value is from an origin: full score up to `offset`,
`decay` (0.5 by default) at `offset + scale`, and less beyond. It suits signals with a natural
"best" value, such as now or here:

| Signal | Origin | Scale and offset |
|---|---|---|
| News, changelogs, logs | Now | The age at which half the value is gone, for example `"7d"` for news, `"365d"` for documentation. Offset: how long something counts as fresh. |
| Local search | The user's location | The distance at which a place is half as attractive, for example `"2km"` in a city. Offset: walking distance. |
| Price fit | A target price | The price difference that halves the score. |

```json
{
  "language": "es",
  "query": {"function_score": {
    "query": {"match": {"body_t": "kubernetes upgrade"}},
    "functions": [{"exp": {"published_dt": {"origin": "now", "scale": "30d", "offset": "7d"}}}],
    "boost_mode": "multiply"
  }}
}
```

`gauss` keeps documents near the origin almost untouched and then falls quickly. `exp` falls fastest
close in, with a long tail. `linear` reaches zero. To keep age from ever removing a document,
blend the decay with a floor, which takes a [scoring expression](scoring-expressions.md#recency):
`score * (0.8 + 0.2 * exp_decay(...))` costs a document at most a fifth of its score.

A decay does not narrow the matches. If far-away or very old documents should not appear at all,
add a filter as well. For distance specifically, see
[Boost nearby results](geo-distance-and-nearest.md#boost-nearby-results).

## Keep boosts from promoting bad matches

A popular document that barely matches can climb above a relevant one. Three ways to stop it:

- **A minimum score.** `min_score` on a `function_score` or a `rescore` drops matches whose final
  score is too low. `min_score` on a fusion's `standard` source drops weak keyword matches before
  fusion. On a vector search, a [`similarity` threshold](vector-search.md#similarity-thresholds)
  drops neighbors that are not close enough, on a scale that does not depend on the query.
- **A conditional boost.** Apply the boost only when the match is good enough:
  `score > $t ? score * popularity_boost : score`. See
  [Conditional boost](scoring-expressions.md#conditional-boost).
- **Small, bounded boosts.** `clamp` the factor, for example to at most 1.5 times the text score.

## Priors

Some signals describe how likely a document is to be useful whatever the query: an authoritative
source, a well-reviewed product, a page many people read. Treat these as a prior and combine it with
the match score, as `score * prior` or `score + w * log(prior)`. The first lets the prior scale
relevance; the second adds an amount that grows slowly with the prior. See [Priors](scoring-expressions.md#priors).

## Strict order goes in a sort

When one signal must always win, such as sponsored listings first or exact category before
related ones, sort by it, then by score:

```json
{
  "language": "es",
  "query": { "match": { "title_t": "dune" } },
  "sort": ["sponsored_i desc", "_score"]
}
```

Keys apply in order: the second only breaks ties in the first. This is predictable and easy to
explain, but cannot trade one signal off against another. A sponsored listing that barely matches
still comes first. Use a sort for rules your business states as strict, and boosts for everything
that should be weighed. A fused search cannot also be sorted; put the sort on a source instead (see
below).

A sort key can also be computed. With `"language": "warpsearch"`, `{"expr": "...", "desc": true}`
sorts by a [value expression](scoring-expressions.md#expressions), such as a margin or a rating
blended with sales. See [Sort by an expression](searching.md#sort-by-an-expression).

## Business signals in hybrid search

A fusion merges ranked lists, and the merged list itself cannot be rescored or sorted. Add business
signals in one of two places:

- **Inside a source.** Make the keyword source's query a `function_score`, so its ranking already
  includes recency or popularity. Do the same on every source the signal should affect. See
  [A boosted source](hybrid-search.md#a-boosted-source).
- **As its own source.** Under RRF, add a `standard` source with the same query, sorted by the signal
  (`published_dt desc`, `sales_i desc`), with a weight below 1. Documents that are both relevant and
  recent gain from both lists. See [A source sorted by a field](hybrid-search.md#a-source-sorted-by-a-field).

A formula over the fused score, such as `(0.4 * keyword + 0.6 * vector) * freshness`, cannot be
reproduced exactly. Boosting each source by freshness before fusion comes close for linear fusion,
because the min-max step then works on the boosted scores. Measure against a judgment list before
relying on it.

## One result per entity

When products have many variants, or documents many chunks, one entity can fill the page. `collapse`
keeps the best hit per value of a field, and `inner_hits` can return the others under it:

```json
{
  "language": "es",
  "query": {
    "query": { "match": { "title_t": "running shoes" } },
    "collapse": { "field": "product_id_s" }
  },
  "limit": 10
}
```

Collapse works on keyword, vector, summed and fused searches. For vector searches, see
[Nearest groups](vector-search.md#nearest-groups), and for fusion,
[One result per entity](hybrid-search.md#one-result-per-entity).

When several hits per value are fine but no value should take over the page, such as at most two
products per brand, use `diversify` instead. It returns plain hits, keeping the best `max_per_key` of
each value in the search's order:

```json
{
  "query": "running shoes",
  "diversify": {"field": "brand_s", "max_per_key": 2},
  "limit": 20
}
```

See [Limit hits per value](searching.md#limit-hits-per-value).

## Checklist

1. Rules are filters, not boosts.
2. Every numeric boost is damped (`log1p`) or bounded (`clamp`, a decay).
3. Boosts are multiplicative unless there is a reason to add.
4. Weak matches cannot ride on a boost: a minimum score, a similarity threshold, or a conditional.
5. Strict business order is a sort; everything else is weighed.
6. Every change is measured with a [judgment list](tuning-relevance.md#offline-evaluation-with-judgment-lists),
   including queries where the signal should not matter.

## Where to go next

1. [Scoring expressions](scoring-expressions.md) for the full formula language.
2. [Choosing a ranking strategy](choosing-a-ranking-strategy.md) for keyword, vector and hybrid
   methods.
3. [Geo distance and nearest](geo-distance-and-nearest.md) for distance in detail.
