Full-text search
medium 28 minFull-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
| document | words |
|---|---|
| 1 | quick brown fox |
| 2 | lazy brown dog |
| 3 | quick 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
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
criticalStored tokens and searched tokens differ, so good documents are never found.
Wrongindex.add(doc, stem(text))index.search(query.lower())Rightindex.add(doc, analyze(text))index.search(analyze(query))Writing to two stores from the app
criticalOne of the two writes will fail one day and the copies drift apart.
Wrongdb.save(p)search.index(p)Rightdb.save(p) # committed change# change stream -> queue -> indexerScoring a yes or no condition
minorMust 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
majorThe 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.