# Highlighting and Autocomplete — Elasticsearch

Source: https://www.skillbyai.com/en/elasticsearch/s-autocomplete

> Show why it matched; suggest as they type.

## Snippets and suggestions

**Highlighting** returns fragments of matching fields with the matched terms wrapped in tags (`<em>` by default, configurable with `pre_tags`/`post_tags`); the default `unified` highlighter works for most cases. For **autocomplete** there are three main approaches. The `search_as_you_type` field type creates shingle and prefix sub-fields and is queried with `multi_match` of type `bool_prefix`; it matches words anywhere in the text. The **completion suggester** uses a `completion` field backed by an in-memory structure; it is very fast for prefix matching from the start of the input but has limited filtering (contexts). An **edge n-gram** analyzer at index time ("jac" -> j, ja, jac) with a plain analyzer at search time gives the most control at the cost of a larger index.

## search_as_you_type plus highlighting

Kibana Dev Tools console syntax; send the same requests with curl or a client library.

```http
PUT /titles
{
  "mappings": {
    "properties": {
      "title": { "type": "search_as_you_type" }
    }
  }
}

GET /titles/_search
{
  "query": {
    "multi_match": {
      "query": "wat jack",
      "type": "bool_prefix",
      "fields": [ "title", "title._2gram", "title._3gram" ]
    }
  },
  "highlight": {
    "fields": { "title": {} },
    "pre_tags": [ "<mark>" ],
    "post_tags": [ "</mark>" ]
  }
}
```

## Debounce and keep it small

Send autocomplete requests after a short pause in typing, ask for a handful of results, and return only the fields you display (_source filtering). Escape highlight output before rendering it as HTML.

**Quiz:** How is a search_as_you_type field usually queried?

- [ ] A cardinality aggregation
- [ ] A term query on the root field
- [x] multi_match with type bool_prefix over the field and its n-gram sub-fields
- [ ] A match_phrase with slop 100

*Answer:* multi_match with type bool_prefix over the field and its n-gram sub-fields. bool_prefix treats the last term as a prefix.
