AlgoViz

Full-text search

medium 28 min

Full-text search finds documents by the words in them and puts the best ones first.

See it run

Turn text into tokens, tokens into an index, and an index into a ranked answer.

Operations

Run a search

The query quick fox on three documents, from the search box to the result.

Step 1 of 6

Input

documentwords
1quick brown fox
2lazy brown dog
3quick lazy cat

Query: Quick fox

Somebody types Quick fox into the search box.

Step 1: Input

def search(index, query):    tokens = analyze(query)    lists = [index[t] for t in tokens]    docs = intersect(lists)    scored = [(bm25(d, tokens), d) for d in docs]    return sorted(scored, reverse=True)[:10]
Work
Two short lists
Needs
The index
LIKE
every row

Documents: 1 is quick brown fox, 2 is lazy brown dog, 3 is quick lazy cat.

In the real world

The same full-text search doing real jobs. Pick one and step through it.

A price change, an outage and the way back.

Step 1 of 5

Save once

Shop APIPostgreSQLprice 20KafkaIndexerElasticsearchprice 30

Index is behind

The API writes the new price to PostgreSQL only.

Step 1: Save once

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Different analysis for text and query

    critical

    Stored tokens and searched tokens differ, so good documents are never found.

    Wrong
    index.add(doc, stem(text))index.search(query.lower())
    Right
    index.add(doc, analyze(text))index.search(analyze(query))
  • Writing to two stores from the app

    critical

    One of the two writes will fail one day and the copies drift apart.

    Wrong
    db.save(p)search.index(p)
    Right
    db.save(p)         # committed change# change stream -> queue -> indexer
  • Scoring a yes or no condition

    minor

    Must computes a score that means nothing here and is harder to cache.

    Wrong
    {"must": [{"term": {"status": "active"}}]}
    Right
    {"filter": [{"term": {"status": "active"}}]}
  • A leading wildcard on a big field

    major

    The engine must look at every term of the field.

    Wrong
    {"wildcard": {"email": "*@example.com"}}
    Right
    # store the domain as its own field{"term": {"email_domain": "example.com"}}

Interview tips

  • How to explain it

    • Word to documents, like the index of a book.
    • Analyze text and query in the same way.
    • Score, sort, return the top.
  • Memory trick: FAST

    • Find: inverted index lookup
    • Analyze: tokenize, stem, filter
    • Score: relevance
    • Top: best matches
  • Reach for it when

    • Words are inside long text.
    • Typing errors and synonyms matter.
    • The best result must be first.
  • Be careful

    • It is a second copy of the data.
    • It is a moment behind.
    • Changing analyzers means indexing again.