SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Relational Databases
  • Document Databases
  • Key-Value Databases
  • Full-Text Search Engines
  • Wide Column Databases
  • Time Series Databases
  • Graph Databases
  • Vector Databases
  • NewSQL Databases
  • Columnar Databases
  • In-Memory Databases
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Types (Deep Dive)

Full-Text Search Engines

Search words inside text, with ranking, using an inverted index (Elasticsearch).

⏱ 14 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A full-text search engine finds documents that contain the words you type, and puts the best matches first. It does this with an inverted index.

  • An inverted index is a map from word to the list of documents that contain it, like the index at the back of a book.
  • Text is first cut into tokens (words) and cleaned. This step is called analysis.
  • Results get a relevance score. Elasticsearch, OpenSearch, Solr and Lucene are the usual tools.

02Concept: What is it?

A normal database index helps you find a row by an exact value. But what if the user types "quick dog" and you want every article that mentions both words, anywhere in the text, even as "dogs" or "Quickly"? A SQL LIKE '%dog%' would have to read every row. That is slow and has no idea which result is better.

A search engine flips the problem. When a document arrives, it analyzes the text: split into words, lowercase, remove tiny words like "the" (stop words), and reduce words to a root (stemming, so "dogs" becomes "dog"). Then it writes each word into the inverted index, with the documents where it appears. A query is analyzed the same way, and the engine looks up each word's list and combines them. Finally it scores each document.

Document to inverted index
Documents
📄D1quick brown fox
📄D2quick dog runs
📄D3lazy dog sleeps
→↓analyze + index
Inverted index
quick → D1, D2
dog → D2, D3
fox → D1
lazy → D3
The index is built once, at write time. A search only reads the short lists for the query words.
🧠Why it is called inverted
A normal (forward) index says: document → words it contains. The inverted index says: word → documents. That is the direction a search needs.

03Real-Life Example

🍵The Index at the Back of a Book
You want every page that mentions "monsoon". You could read the whole book. Or you open the index at the back: monsoon: 12, 45, 201. Three page numbers, no reading needed. If a word appears on 30 pages, you start with the pages where it appears most often, or where it is the main topic. A search engine does exactly this, for millions of pages.
Book index
Search engine
A page of the book
A document
The word in the index
A term (token)
The list of page numbers
A posting list
Ignoring words like "the"
Stop words
Listing "run" for "running" too
Stemming
Pages where the word is used a lot
High term frequency (TF)
A rare word tells you more than a common one
IDF (inverse document frequency)
Combining two words: pages in both lists
Intersecting posting lists (AND)
A search request
🔎Queryquick dogs
→↓analyze
✂️Tokensquick, dog
→↓look up lists
📚Inverted index
→↓score
🏆Ranked results

04Why Do We Need It?

⚡Fast text search
The index jumps straight to the right lists. No scanning of all documents.
🏆Relevance ranking
Best matches come first, not just any match.
🌍Language smarts
Case, plurals, accents, synonyms and typos can be handled.
🧮Filters and facets
Narrow by price, brand or date, and show counts per category.
✨Search-as-you-type
Autocomplete and "did you mean" suggestions.
📊Log and event analysis
Search and aggregate huge piles of logs quickly.
Databases answer "give me this exact row". Search engines answer "what is most relevant to these words?".

05Where Do We Use It?

🛍️Shop search
Search products by words, with filters for size and price.
📰Site and document search
Articles, help centres, wikis, code search.
📜Log search
Find an error across millions of log lines (the ELK stack).
💬Message and email search
Find old chats and mails by words.
🗺️Places and geo search
"Coffee near me", combining text and location.
🛡️Security analytics
Hunt for patterns in events.

06Types / Parts / How It Works

Steps of analysis

StepWhat it doesExample
TokenizeSplit the text into words."Quick dogs!" → Quick, dogs
LowercaseIgnore capital letters.Quick → quick
Stop wordsDrop very common, low-value words.the, and, is (often removed, or kept in modern setups)
Stem / lemmatizeReduce to a root form.dogs → dog, running → run
SynonymsTreat some words as equal.tv = television
N-gramsCut words into pieces for partial matches and autocomplete.sea, ear, arc, rch

How results are ranked

IdeaMeaning
Term frequency (TF)How often the word appears in this document. More is better.
Inverse document frequency (IDF)How rare the word is across all documents. A rare word counts for more than a common one.
Length normalisationA hit in a short title beats the same hit in a very long text.
BM25The modern default in Lucene, Elasticsearch and Solr. A tuned relative of TF-IDF that stops very frequent words from scoring without limit.
BoostsYou can give extra weight to fields (title above body) or to fresh and popular items.
SQL LIKE or full scan
Scan rows
  • Reads every row
  • No relevance order
  • No stemming or typos
  • Fine for tiny tables
Inverted index
Look up words
  • Reads only the word lists
  • Ranked by relevance
  • Language-aware analysis
  • Index must be built and updated
A search cluster
🧑‍💻Client
→↓query
🧭Coordinating node
↔ask all shards
🧱Shard 1+ replica
🧱Shard 2+ replica
🧱Shard 3+ replica
Merge the top results Each shard has its own index
The index is split into shards, and each shard has copies (replicas). A query asks every shard, then merges the best results.
VisualizerBuild an inverted index and rank a queryType a query and read the index lines that light up. Turn lowercase, stop words and stemming on and off. Switch between plain match counting and a TF-IDF style score.
Lowercase
Remove stop words
Stemming
Ranking
The query goes through the same analyzer as the documents: quick dogs becomes [quick][dog]
Inverted index (23 terms)
animal→ D2
brown→ D1
cat→ D3, D4
clever→ D2
contain→ D6
day→ D3
document→ D5, D6
dog→ D1, D3, D4
engine→ D5
fast→ D5
fox→ D1, D2
friendly→ D4
index→ D5, D6
jump→ D1
lazy→ D1, D3
map→ D6
pet→ D4
quick→ D1, D2, D3
run→ D3
search→ D5×2
sleep→ D3
them→ D6
word→ D6
Results, best first
D10.90
The quick brown fox jumps over the lazy dog
D30.83
A lazy cat sleeps all day while a quick dog runs
D20.55
Foxes are quick and clever animals
D40.55
Dogs and cats are friendly pets
Documents
6
Terms in index
23
Documents scanned
0
the index jumps straight to the lists
Matches
4
4 of 6 documents match. Documents that contain rare query words, often, in a short text, rank higher. A common word such as "quick" adds less than a rare one.
Show the documents
  1. D1 The quick brown fox jumps over the lazy dog
  2. D2 Foxes are quick and clever animals
  3. D3 A lazy cat sleeps all day while a quick dog runs
  4. D4 Dogs and cats are friendly pets
  5. D5 Search engines index documents so searching is fast
  6. D6 An index maps words to the documents that contain them

A teaching model: the score is (term frequency divided by the square root of document length) times log(1 + N / documents with the word), added over the query words. Real engines such as Elasticsearch default to BM25, a close and better-tuned relative of TF-IDF, and use proper stemmers and language rules.

07How to Use It / Steps / Implementation

Adding search to a system

  1. 1
    Keep the main database as the source of truth
    Treat the search index as a copy that can be rebuilt.
  2. 2
    Define the mapping
    Say which fields are text (analyzed), which are exact (keyword), numbers or dates.
  3. 3
    Pick the analyzers
    Choose language, stemming, synonyms. Use the same analysis for indexing and for queries.
  4. 4
    Feed the index
    Send changes by a queue or change data capture (CDC), so the index follows the database. Bulk load for the first time.
  5. 5
    Write queries with scoring and filters
    Match on text for relevance, filter on exact fields for speed (filters can be cached and need no score).
  6. 6
    Plan shards and replicas
    Shard count is hard to change later. Replicas give availability and more read capacity.
  7. 7
    Tune relevance with real queries
    Collect searches that fail, add boosts or synonyms, and test changes.
An Elasticsearch style query
PUT /products/_doc/1
{ "title": "Quick brown fox toy", "price": 12, "brand": "Acme" }

GET /products/_search
{
  "query": {
    "bool": {
      "must":   { "match": { "title": "quick fox" } },
      "filter": { "range": { "price": { "lte": 20 } } }
    }
  }
}
⚠️Near real time, not instant
In Elasticsearch a new document becomes searchable after the next refresh (about one second by default). So a search right after a write may not show it. Do not use a search engine as your only store.

08Key Terms to Know

TermMeaning in easy words
Inverted indexA map from each word to the documents (and positions) that contain it
DocumentOne searchable record, usually JSON
Token / termA word (or piece of a word) after analysis
AnalyzerThe pipeline that turns text into tokens: tokenizer plus filters
Posting listThe list of documents for one term
Stop wordsVery common words that are often dropped
StemmingCutting a word down to its root so forms match
TF-IDFA score: frequent in this document, rare in all documents is good
BM25The default ranking function in modern engines, a refined TF-IDF
Shard / replicaA slice of the index / a copy of that slice
SegmentAn immutable chunk of index files. Lucene merges small segments into big ones
RelevanceHow well a result matches what the user wants
Precision / recallShare of results that are right / share of right items that were found

09Pros, Cons and Trade-offs

✅ Pros
  • Fast keyword search over huge text
  • Ranked results
  • Language-aware matching, typos and synonyms
  • Filters, facets and aggregations
  • Scales out with shards
⚠️ Cons
  • Not a source of truth, can lose or lag behind
  • Near real time, not instant
  • No real transactions or joins
  • Index uses extra disk and memory
  • Relevance tuning is an ongoing job
  • Re-indexing is needed when mappings change

Trade-offs

ChoiceWe gainWe lose
More analysis (stemming, synonyms, n-grams)Finds more matchesBigger index, more noise, lower precision
More shardsParallel search and writesOverhead per shard, harder to change later
More replicasAvailability and read capacityDisk cost, slower indexing
Fast refreshNewer data is searchable soonerMore work, smaller segments
Rich scoringBetter relevanceSlower queries, harder to explain

10Common Problems and Mistakes

Common mistakes

  1. Using it as the primary database. It can lag and has weak guarantees. Keep a real source of truth.
  2. Different analysis at index and query time. Words stop matching in strange ways.
  3. Too many shards. Many tiny shards waste memory and slow queries.
  4. Deep paging. Asking for page 10,000 forces every shard to sort a huge list. Use search_after or a scroll style method.
  5. Mapping explosion. Letting every new field create a mapping makes the cluster slow.
  6. Ignoring relevance. Search that returns lots of results in a bad order feels broken.
  7. Forgetting to sync deletes. Removed products still appear in search.

Things to watch

🕰️Index lag
Watch the delay between a database change and its appearance in search.
🔁Re-indexing
Changing analyzers means building a new index. Use aliases to switch.
🧠Memory
Heap size, caches and segment counts all matter.
🔐Security
An open search port has leaked a lot of data. Use auth and private networks.

11Real-World Examples

🔍Elasticsearch and OpenSearch
Distributed search engines built on Lucene. Used for site search, logs and analytics.
📚Apache Lucene
The core library under Elasticsearch, OpenSearch and Solr.
☀️Apache Solr
A mature search server also built on Lucene.
⚡Lightweight engines
Meilisearch, Typesense and Algolia focus on fast, easy site search with typo tolerance.
🐘Built into databases
PostgreSQL full-text search and MySQL full-text indexes cover small to medium needs without a separate system.
📜ELK / Elastic Stack
Logstash or Beats feed logs into Elasticsearch, and Kibana shows them.
📝Note
These are general ideas. Defaults such as the refresh time or the scoring function depend on the version.
Mini case: shop search kept in sync
🗄️Product database
→↓change events
📬Queue
→↓
🔍Search index
←search
🧑‍💻Shop users
The database stays the truth. Changes flow to the search index through a queue.

12Related Topics to Read Next

Common Database Types→

Where search engines sit among the other stores.

Indexing→

The normal database index, and how it differs from an inverted index.

LSM Trees→

Lucene writes immutable segments and merges them, a similar idea.

Sharding→

How a big index is split over many machines.

Message Queues→

A common way to keep the index in sync with the database.

Vector Databases→

Search by meaning rather than by exact words.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: finds documents by words, ranked by relevance.
  • ✔Core: inverted index: word → list of documents.
  • ✔Analysis: tokenize, lowercase, stop words, stem. Same for index and query.
  • ✔Ranking: TF, IDF, field length. BM25 is the modern default.
  • ✔Scale: shards for size, replicas for safety and reads.
  • ✔Keep in sync: database is the truth, feed the index by CDC or a queue.
  • ✔Remember: near real time, no transactions, avoid deep paging.
  • ✔One line: “Index words to documents once, so every search is a quick lookup.”
← Previous
Key-Value Databases
Next →
Wide Column Databases