# Synonyms, rules and ranking settings

Shoppers and site visitors type short, misspelled queries in their own words. The `text` query
language is built for that search box. It matches the last word as a prefix while people type,
tolerates typos, and applies three things you manage per collection:

- **Synonyms**, so `sofa` also finds `couch`.
- **Rules**, which change the results of chosen queries: pin a product, hide one, boost a brand,
  add a filter, or send the query to a page.
- **Ranking settings**, the defaults for every `text` search on the collection: searched fields
  and weights, typo tolerance, prefix matching, stop words.

Changes reach live searches at once, without reindexing. You can manage all three in the console
under **Collection > Relevance**, or through the API below.

Synonyms, rules and ranking settings apply only to searches in the `text` language. They do not
change searches sent in other languages, through the [Elasticsearch](compat-elasticsearch.md),
OpenSearch or [Solr](compat-solr.md) compatible APIs, or [hybrid](hybrid-search.md) searches.
For synonyms that apply in every query language and API, put a `synonym` filter in the field's
analyzer instead; [Synonym filters](synonym-filters.md) compares the two. Synonym filters that an
Elasticsearch or OpenSearch index defines only in a field's `search_analyzer` are added to these
collection synonyms when the index is created.

## Searching with the text language

Send the query as an object with `"language": "text"`:

```json
POST /v1/search/products
{
  "language": "text",
  "query": {"text": "runing shoe", "fields": ["title^3", "brand^2", "description"]},
  "filters": ["in_stock:true"],
  "facets": {"brand": {"type": "terms", "field": "brand", "size": 10}},
  "limit": 20
}
```

`text` is the only required key. An empty string matches every document, which is how a
category page with no query works. The defaults suit a search box:

| Key | Default | Meaning |
|---|---|---|
| `fields` | The collection's text fields | Fields to search, with `^weight`, in order of importance. |
| `operator` | `and` | Every word must match. `or` makes them optional, with `min_should` as the minimum. |
| `query_type` | `prefix_last` | The last word matches as a prefix, so `runn` finds `running` while people type. `prefix_all` treats every word as a prefix. `prefix_none` turns prefixes off. |
| `typo_tolerance` | `true` | Words of 4 or more characters match with one typo, and words of 8 or more with two. `false` turns it off. |
| `fuzziness` | | Tunes typo tolerance: `min_length_1`, `min_length_2`, `max_edits`, `prefix_length`, `transpositions`, and `disable_on_words` for words that must match exactly, such as brand names. Numbers do not get typos unless `numeric_tokens` is true. |
| `exact_fields` | | Fields searched without typos or prefixes, such as SKUs. |
| `optional_words` | | Words that help ranking but are not required. |
| `remove_words_if_no_results` | `none` | Retry without the `last_words` or `first_words`, or with `all_optional`, when a query finds nothing. The response says what was removed in `query_after_removal`. |
| `stop_words`, `remove_stop_words` | | Words dropped from the query. `remove_stop_words` also drops a built-in English list. |
| `advanced_syntax` | `false` | Quoted phrases must match as phrases and `-word` excludes a word. |
| `distinct` | | One hit per value of a field, for example one per `product_id` when each variant is a document. |
| `optional_filters` | | Rank documents matching a filter higher without excluding the rest, for example `{"field": "in_stock", "value": true, "score": 2}`. |
| `contexts` | | Names that switch on rules made for them, such as `mobile` or `sale`. |

Filters, facets, sorting and paging work as in any [search](searching.md). Hits carry
[highlights](highlighting.md) when you ask for them.

## Synonyms

A synonym object is one of four types:

| `type` | Fields | Effect |
|---|---|---|
| `synonym` | `synonyms`: two or more terms | Each term also finds the others. `sofa`, `couch`, `settee`. |
| `one_way` | `input`, `synonyms` | `input` also finds the synonyms, never the reverse. `phone` finds `iphone`, but `iphone` does not find every phone. |
| `alt_correction_1` | `word`, `corrections` | `word` also finds the corrections, ranked like a one-typo match. |
| `alt_correction_2` | `word`, `corrections` | The same, ranked like a two-typo match. |

Terms can have several words. `tv <=> television` and `hd <=> high definition` work, and the
query words still match on their own, so a product that has `high` and `definition` apart is
not lost. A synonym does not change how strongly a word counts in the ranking.

Store synonyms one at a time or in a batch:

```json
PUT /v1/collections/products/synonyms
[
  {"objectID": "sofa", "type": "synonym", "synonyms": ["sofa", "couch", "settee"]},
  {"objectID": "phone", "type": "one_way", "input": "phone", "synonyms": ["iphone", "smartphone"]},
  {"objectID": "tshirt", "type": "alt_correction_1", "word": "tshirt", "corrections": ["t-shirt"]}
]
```

`{"objects": [...], "replace": true}` replaces every stored synonym in one call. In the console,
**Relevance > Synonyms** also imports a Solr or Elasticsearch `synonyms.txt` file
(`a, b, c` and `a => b` lines), JSON or NDJSON.

## Rules

A rule has conditions, which decide which queries it applies to, and instructions, which say
what to do. This one pins a product to the top for `iphone case` and boosts one brand:

```json
PUT /v1/collections/products/rules/iphone-case
{
  "objectID": "iphone-case",
  "conditions": [{"pattern": "iphone case", "anchoring": "contains"}],
  "instructions": [
    {"type": "pin", "ids": ["sku-8812"], "position": 0},
    {"type": "boost", "expr": "brand:\"Acme\"", "weight": 2}
  ]
}
```

**Conditions.** A rule applies when any of its conditions matches. A rule with no conditions
applies to every query.

| `anchoring` | Matches when the pattern |
|---|---|
| `is` | is the whole query |
| `starts_with`, `ends_with` | is the first or last words |
| `contains` (default) | appears anywhere, on word boundaries |
| `regex` | matches the raw query text, case insensitive unless `case_sensitive` |

Patterns are matched on normalized words, so case and accents do not matter. A condition can
also require `contexts` sent with the request, or an exact request `filters` string, so a rule
can apply only on one category page. `{facet:brand}` in a pattern matches one to three words that
name a value of the `brand` field: `{facet:brand} shoes` matches `nike shoes` and `new balance
shoes`.

**Instructions.**

| `type` | What it does |
|---|---|
| `pin` | Puts `ids` at `position` (0 is first). |
| `hide` | Removes `ids` from the results. |
| `bury` | Moves `ids` to the end. |
| `boost` | Raises hits matching `term` or `expr` by `weight`. A negative weight lowers them. |
| `filter` | Adds a filter (`term` or `expr`). `"include": false` excludes the matches instead. |
| `facet_filter` | Filters on `field` = `value`. A `score` makes it rank matches first instead. |
| `auto_facet_filters` | Turns the values a `{facet:field}` placeholder matched into filters, and takes those words out of the query. `nike shoes` searches `shoes` filtered to Nike. |
| `synonym` | Adds `terms` as alternatives, only for queries this rule matches. |
| `delete`, `replace` | Removes words, or replaces `from` with `to`. |
| `replace_query` | Replaces the whole query with `query`. |
| `params` | Overrides search parameters, such as `fields` or `typo_tolerance`, for these queries. |
| `user_data` | Returns `data` with the results, for a banner or a message. |
| `redirect` | Returns `url`, for example `returns policy` to `/help/returns`. |

`expr` uses the filter syntax, such as `on_sale:true` or `category:"shoes"`.

**Order and scheduling.** Rules apply highest `priority` first, then by id. Set
`"enabled": false` to keep a rule without applying it. `validity` is a list of
`{"from", "until"}` windows in Unix seconds, so a campaign rule can start and stop by itself.

**What comes back.** The response lists `applied_rules`, any `user_data` and a `redirect` URL.
Pinned and buried hits carry `rule` with the rule's id. Following a redirect is up to your
application. Send `"redirect_only": true` to skip the search when a redirect matches. A request can
turn rules off with `"enable_rules": false`.

**Curating from the console.** In the console's search tab, run a query and pin, hide or bury a
hit to create a rule for that query. Unsaved rules and synonyms can be previewed on live data
before you save them.

## Ranking settings

Ranking settings are the defaults for every `text` search on a collection. They take the keys of
the text query, except `text` itself:

```json
PUT /v1/search/products-settings
{
  "fields": ["title^3", "brand^2", "sku", "description"],
  "exact_fields": ["sku"],
  "typo_tolerance": true,
  "query_type": "prefix_last",
  "fuzziness": {"disable_on_words": ["nike", "adidas"]}
}
```

`{}` clears them. When the same key is set in more than one place, this order wins: a rule's
`params`, then the request, then the ranking settings, then the default. The console edits these
under **Relevance > Ranking settings**.

## Permissions and limits

Reading synonyms, rules and settings needs read access to the collection. Changing them needs
the manage role (the console's editor role).

| Limit | Value |
|---|---|
| Synonyms per collection | 10,000 |
| Rules per collection | 1,000 |
| One synonym or rule | 32 KiB |
| Conditions and instructions per rule | 25 and 50 |
| Pinned ids per rule | 100 |
| Words in a pattern or term | 32 |

## Endpoints

| Method | Path | Purpose |
|---|---|---|
| `GET`, `PUT`, `DELETE` | `/v1/collections/{c}/synonyms` | List, store a batch, remove all |
| `GET`, `PUT`, `DELETE` | `/v1/collections/{c}/synonyms/{id}` | One synonym |
| `POST` | `/v1/collections/{c}/synonyms/_search` | Find synonyms by text (`query`) and `type` |
| `GET`, `PUT`, `DELETE` | `/v1/collections/{c}/rules` | List, store a batch, remove all |
| `GET`, `PUT`, `DELETE` | `/v1/collections/{c}/rules/{id}` | One rule |
| `POST` | `/v1/collections/{c}/rules/_search` | Find rules by text |
| `GET`, `PUT` | `/v1/search/{c}-settings` | Ranking settings |

## Where to go next

1. [Tuning relevance](tuning-relevance.md) for BM25 settings, field weights and function scores.
2. [Facets and aggregations](facets-and-aggregations.md) for filter menus.
3. [Highlighting](highlighting.md) for marked-up matches in results.
