What You'll Learn
- 1Assemble a search request path from query understanding through re-ranking with a latency budget
- 2Compute a BM25 score for a query-document pair by hand
- 3Compute NDCG at K for a ranking and interpret what a drop means
- 4Size an inverted index into shards for a target corpus
Why This Matters
Search ranking is critical for user experience and business outcomes:
- Google: Handles 8.5 billion searches daily
- E-commerce: 30% of revenue comes from site search
- Content Platforms: Good search increases engagement by 40%
- Enterprise: Internal search improves productivity by 25%
âšī¸
Search ranking is one of the most impactful ML systems, directly affecting user satisfaction and business metrics.
Search Ranking Architecture
Query Understanding
Query understanding processes raw user queries into structured representations:
- Cleaning: Lowercase, remove special characters, normalize whitespace
- Spell Correction: Fix misspelled words using a spell checker
- Tokenization: Split query into individual tokens
- Intent Classification: Classify query intent (navigational, informational, transactional) using a transformer model
- Entity Extraction: Extract named entities (prices, locations, products) using regex patterns or NER models
Document Retrieval
Document retrieval combines multiple search strategies:
BM25 Retrieval
BM25 is a lexical search algorithm that scores documents based on term frequency and inverse document frequency. It uses field-level boosting (e.g., title matches weighted 2x) and boolean query construction for precise retrieval.
Semantic Search
Semantic search uses dense embeddings to find semantically similar documents. Query and document embeddings are compared using cosine similarity via Elasticsearch's script_score query.
Hybrid Retrieval
Hybrid retrieval combines BM25 (lexical) and semantic search results, weighting results from each approach (e.g., 60% BM25, 40% semantic) and deduplicating to produce a combined result set.
Learning to Rank
Learning to rank uses LambdaMART (a gradient-boosted tree variant) to optimize ranking metrics like NDCG:
- Feature Engineering: Query features (length, type), document features (length, age), query-document features (BM25 score, semantic similarity), and click features (CTR, click count)
- Training: Train LambdaMART with group-based training data for listwise optimization
- Ranking: Score query-document pairs and sort by predicted relevance
Click-Through Rate Prediction
CTR prediction estimates the probability of a user clicking on a search result:
- Feature Preparation: Query length, document length, word overlap, position features
- Model: Gradient Boosting Classifier for binary click prediction
- Evaluation: AUC-ROC on held-out validation data
Evaluation Metrics
Search evaluation uses information retrieval metrics:
| Metric | Description |
|---|---|
| Precision@K | Fraction of retrieved documents that are relevant |
| Recall@K | Fraction of relevant documents that are retrieved |
| NDCG@K | Normalized Discounted Cumulative Gain considering position |
| MRR | Mean Reciprocal Rank of the first relevant result |
| MAP@K | Mean Average Precision across queries |
The Retrieval Score: BM25
BM25 scores a document for a query as a sum over query terms, weighting term frequency with saturation and normalizing for document length:
With the standard and , a term appearing 5 times in a document of average length scores frequency units, while the same term appearing 20 times scores only . The saturation is deliberate: the tenth occurrence of a query term adds almost nothing, which is what keeps keyword stuffing from working. Raise toward 1.0 when short documents should win and lower it toward 0 when length should not matter.
The Request Latency Budget
Every search request pays for five stages, and only the ranking stage is elastic:
A budget for a 100 ms interactive target might be 10 ms to parse and understand the query, 40 ms to hit the inverted index and the vector index in parallel, 15 ms to fetch features, 30 ms to score 500 candidates with the LambdaMART model, and 5 ms to apply freshness and business rules. That is exactly 100 ms, so any growth in candidates has to be paid for by cutting the retrieve term, for example by routing rare queries to a smaller shard set. Measure per-stage p99 on real traffic: the retrieve term is the one that degrades first when an index grows past its shard plan.
Measuring Ranking Quality with NDCG
NDCG rewards putting the most relevant documents first, with logarithmic discounting by position:
Take a 4-document result with graded relevance . Its discounted gain is . The ideal order gives , so NDCG is , while the near-ideal order scores . That sensitivity is the point: a 0.02 drop in NDCG means valuable results are sliding down the page, which click-through metrics will confirm days later.
Sharding the Index
Index capacity decides your cluster shape. A billion-document corpus with about 3 KB of postings per document is:
That is 3 TB of postings. On 64 GB nodes held at 70 percent utilization for headroom during merges, it takes data shards, plus replicas. Route each query to a subset of shards when the corpus allows it: a query fanned out to all 67 shards at 50,000 queries per second becomes 3.35 million shard-queries per second, which is the number that actually drives node count. Rebalance on shard-size skew rather than document count, because document lengths vary by more than 10x.
Interview Q&A
âšī¸
Q: How do you handle query understanding for ambiguous queries?
Answer:
- Intent Classification: Classify query intent (navigational, informational, transactional)
- Entity Extraction: Extract key entities from query
- Query Expansion: Expand query with synonyms
- Personalization: Use user history to disambiguate
- A/B Testing: Test different interpretations
A query disambiguator generates multiple interpretations, scores each based on user context, and selects the highest-scoring interpretation.
âšī¸
Q: How do you balance relevance and diversity in search results?
Answer:
| Strategy | Implementation | Trade-off |
|---|---|---|
| MMR | Maximal Marginal Relevance | Relevance vs Diversity |
| Intent Coverage | Cover multiple intents | Precision vs Recall |
| Freshness | Boost recent content | Quality vs Recency |
| Category Balance | Ensure category diversity | Relevance vs Breadth |
âšī¸
Q: How do you handle large-scale indexing for billions of documents?
Answer:
- Distributed Indexing: Use Elasticsearch/Solr clusters
- Incremental Updates: Index new documents without full rebuild
- Sharding: Partition index across multiple nodes
- Replication: Create replicas for high availability
- Compression: Reduce index size
Common Mistakes
Optimizing the ranker while retrieval recall is low
Fix: Measure recall of the combined BM25 and vector retrieval first; documents the retriever drops can never be ranked.
Evaluating with precision alone on a graded relevance problem
Fix: Use NDCG at K, which discounts by position and handles graded judgments instead of a binary hit or miss.
Sharding by document count
Fix: Shard by index bytes and query load, since document length varies more than 10x and drives both.
Best Practices
- Budget the five stages explicitly and re-measure p99 per stage after every index or corpus change
- Keep a lexical and a vector retriever in parallel and blend their scores, because each covers the other's blind spot
- Log the winning score and the runner-up gap per request, since near-ties are where bad re-ranking shows up first
Key Takeaways
- BM25 saturates term frequency: with k1 = 1.2 and average length, 5 occurrences score 1.77 and 20 occurrences only 2.08
- A 100 ms request budget splits 10 + 40 + 15 + 30 + 5 across parse, retrieve, features, rank, and re-rank
- For graded relevance [1, 3, 0, 2], NDCG at 4 is 6.709 / 9.393 = 0.714, so position matters as much as relevance
- A billion documents at 3 KB of postings is 3 TB, which is 67 shards on 64 GB nodes at 70 percent utilization
Frequently Asked Questions
How do BM25 and vector retrieval differ in what they find?
BM25 matches exact terms and is unbeatable for identifiers, part numbers, and rare words, but it misses paraphrases entirely. Vector retrieval matches meaning and finds paraphrases, but it blurs rare tokens that look similar in embedding space. Running both in parallel and blending the scores covers queries where either alone fails, which is why hybrid retrieval is now the default rather than an experiment.
When should I retrain the ranking model?
When the click distribution moves or features change, not on a fixed calendar. Track NDCG and click-through on a held-out window weekly; a steady decline signals drift from new content, interface changes, or seasonality. Retrain with fresh implicit labels, and always validate that the new model beats the current one on the same eval set before promotion, otherwise a stale model quietly outlives its data.
Why does my offline NDCG improve while online CTR does not?
Usually the labels are wrong. Implicit clicks carry position bias, so the model learns that top results are good because they were seen, and offline evaluation on the same biased labels confirms the loop. Correct it with interleaving experiments or inverse-propensity scoring, or run online A/B tests as the source of truth and use offline NDCG only as a fast filter between candidate models.
Interview Questions
Q1: Walk me through where the time goes in a 100 ms search request.
10 ms to parse and classify intent, 40 ms of parallel inverted-index and vector retrieval, 15 ms to fetch features, 30 ms to LambdaMART-score 500 candidates, and 5 ms of re-ranking. The retrieve term dominates and degrades first as the corpus outgrows its shard plan, so per-stage p99, not end-to-end average, is what you watch.
Q2: How do you size a search cluster for a billion documents?
Estimate index bytes: 1e9 documents at 3 KB of postings is 3 TB. Divide by usable node memory, 64 GB at 70 percent, to get 67 shards plus replicas, then check fan-out: 50,000 QPS against all 67 shards is 3.35 million shard-queries per second, which sets the node count that actually carries the load.
Q3: Explain NDCG and how you would use it to compare two rankers.
NDCG divides the discounted cumulative gain of your ranking by the ideal one, with each document's gain discounted logarithmically by position. For graded relevance [1, 3, 0, 2] the score is 0.714 versus 0.993 for a near-ideal order, so it is sensitive to placement, not just relevance. Compare two rankers on the same judged query set per query, then test significance before shipping.
Quiz
Next Steps
- Module 9: Fraud Detection System - Apply ML to fraud detection
- Module 10: NLP System Design - Learn text processing and NLP
- Practice: Design a search ranking system for an e-commerce platform
Continue to Fraud Detection System ->