AI Hints
Home›Elasticsearch Tutorial›Normalizers and Autocomplete
Elasticsearch · Lesson 59 of 120

Autocomplete with Edge N-grams

Results as you type.

⏱ 2 min read▶ Video at 55:43🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Type b, a, s, and the search box already suggests Basecamp tents. To match the start of words, we index every beginning of every word. These are called edge n grams.

  • Type bas…
  • Suggest Basecamp
  • Edge n-grams

What edge n-grams look like

An edge n gram filter, from two to five letters, turns basecamp into ba, bas, base and basec. Run it. These prefixes go into the index, so typing bas matches.

Dev Tools Consoletext
GET _analyze?filter_path=tokens.token
{
  "tokenizer": "standard",
  "filter": ["lowercase",
    { "type": "edge_ngram", "min_gram": 2, "max_gram": 5 }],
  "text": "Basecamp"
}
Output
{
  "tokens": [
    {"token": "ba"},
    {"token": "bas"},
    {"token": "base"},
    {"token": "basec"}
  ]
}

An autocomplete field

The index time analyzer makes the prefixes. At search time, we use the plain standard analyzer, so bas stays bas. Then we search for bas. Run it. All the Basecamp tents come back, after just three letters.

Dev Tools Consoletext
PUT products
{ "settings": { "analysis": {
    "filter": { "starts": { "type": "edge_ngram", "min_gram": 2, "max_gram": 10 } },
    "analyzer": { "prefixes": { "tokenizer": "standard", "filter": ["lowercase", "starts"] } } } },
  "mappings": { "properties": { "name": { "type": "text",
    "analyzer": "prefixes", "search_analyzer": "standard" } } } }

POST _bulk?refresh=true&filter_path=errors
{ "index": { "_index": "products" } }
{ "name": "Basecamp 2-Person Tent" }
{ "index": { "_index": "products" } }
{ "name": "Basecamp Family Tent" }

GET products/_search?filter_path=hits.hits._source.name
{ "query": { "match": { "name": "bas" } } }
Output
# PUT products 200 OK
{
  "acknowledged": true,
  "shards_acknowledged": true,
  "index": "products"
}

# POST _bulk 200 OK
{"errors": false}

# GET products/_search 200 OK
{
  "hits": {
    "hits": [
      {"_source": {"name": "Basecamp 2-Person Tent"}},
      {"_source": {"name": "Basecamp Family Tent"}}
    ]
  }
}

Summary

Edge n grams index the start of every word, so a few typed letters can match. Use a normal analyzer at search time. Next, a field type that does this for you.

Key takeaways
  • edge_ngram
  • Index prefixes
  • search_analyzer
Next up: search_as_you_type — autocomplete, built in