What you'll learn: By the end of this lesson you will be able to describe search and recommendation as one retrieve-then-rank pattern, design the indexing and query paths of a search service, combine keyword and vector results with rank fusion, measure relevance with judged queries, build a candidate-generation, scoring and re-ranking pipeline, and spot the feedback loops that make a recommender worse over time.
Ask a good librarian for "something like the book I returned yesterday". She does two things. First she narrows ten thousand books to a trolley of thirty, using the catalogue and a quick memory of what you liked. Then she picks the best three from the trolley, using what she knows about you and what is actually on the shelf today. She never reads all ten thousand books to answer you.
Search and recommendation systems work the same way. This is an educational reference design, not the verified internal architecture of any company. The inverted index, analysis and BM25 are in search engines and the inverted index, and the ShopStream stage on search, notifications and media built a first version. This lesson covers the system around them: index freshness, combining retrieval modes, measuring quality, and producing and auditing recommendations.
Verified on 2026-12-02 against the Elasticsearch documentation, the Google Machine Learning recommendation course pages and the YouTube recommendations paper. No code on this page was run.
The core idea
Search and recommendation are both retrieve-then-rank systems: a cheap stage cuts a huge catalogue to a few hundred candidates, a costlier stage orders them, and hard rules have the last word. Both live or die by the data loop that feeds them. The difference is the query. In search the shopper types it. In recommendation the "query" is the shopper and their context: the cart, the page, the time of day.
Three illustrations run through the lesson, each labelled:
- Minimal example: a search for "oat milk" and a fusion of two ranked lists.
- Realistic example: ShopStream product search and the "goes well with" strip on the cart page.
- Failure example: a stalled indexer that keeps showing sold-out products.
The search service has two paths
Treat search as two pipelines that meet in the index.
Figure 1. The two paths of a search service. How to read this: the top row feeds the index in the background and is allowed to lag. The bottom row answers a shopper and must be fast. The green box is the escape hatch for facts that change too quickly to trust the index with: stock and price.
The indexing path: how fresh is "fresh"?
Documents reach the index through change events from the source of truth, so the index is a projection that can always be rebuilt. Elasticsearch, a Lucene-based engine, is a good concrete example. Its documentation describes search as near real-time: a document becomes searchable about one second after it is indexed, because a refresh writes the in-memory buffer to a new segment and opens it for search, which is much cheaper than a full commit to disk. By default it refreshes every second, but only for indices that received a search request in the previous 30 seconds. So the engine's own delay is about a second; the delay that hurts is upstream, in the events and the indexer.
Track freshness (the age of the newest event applied) and alert on it, not on the indexer's CPU. For fields that change often, such as stock or a promotional price, use the index for finding products, then verify those fields against a live source for the few results you return: the green box in Figure 1.
The query path: analyze, retrieve, score, filter
A query goes through the same steps as a document. Elasticsearch's text analysis documentation describes analysis as converting unstructured text into a structured form optimised for search: changing text before it is split, splitting into tokens, then normalising tokens by lowercasing, stemming or mapping synonyms. The rules run at index time and at search time, and the documentation stresses applying the same rules in both so query terms match indexed terms. A search for "Oat Milks" becomes oat and milk and matches a document that was indexed the same way.
Matching documents are then scored. In Elasticsearch the default similarity is BM25, which has two settings: k1 (default 1.2) controls how quickly repeated occurrences of a term stop adding to the score, and b (default 0.75) controls how strongly document length normalises the score. The ranked retrieval returns, say, the top few hundred. Filters such as dietary tags, store or price range apply alongside scoring and do not change the score.
Minimal example (illustrative). A shopper searches "oat milk". The API analyses it into two terms, the index returns 40 products containing them, BM25 orders them, a filter drops products the shopper's stores do not carry, and the top 20 go to the page. If a product's stock changed ten seconds ago, the live check corrects the badge.
Deep paging
Page 500 is far costlier than page 1. Elasticsearch's pagination documentation says that by default you cannot use from and size to page past 10,000 hits, and recommends search_after, ideally with a point in time so a refresh between requests cannot reorder results. The design answer is usually better ranking and filters, not deeper pages; see pagination: offset, cursor and keyset.
Hybrid retrieval: keywords plus meaning
Keyword retrieval is exact and explainable but misses paraphrase. Vector retrieval matches meaning but can miss exact identifiers. Many services run both and merge the lists, which raises the question of how to merge, because BM25 scores and vector similarities live on different scales.
Reciprocal rank fusion (RRF) avoids the problem by ignoring scores and using only ranks. Elasticsearch documents it as a method of combining multiple result sets with different relevance indicators: each document's score is the sum, over the lists where it appears, of 1 divided by (rank_constant plus its rank), with ranks starting at 1 and a default constant of 60. Its documentation notes that it needs no tuning and removes the need to find a weighting for a linear combination.
Worked example (illustrative ranks). Product A is rank 1 in the keyword list and rank 3 in the vector list. Product B is rank 2 and rank 1.
- A: 1/(60+1) + 1/(60+3) = 0.01639 + 0.01587 = 0.03227
- B: 1/(60+2) + 1/(60+1) = 0.01613 + 0.01639 = 0.03252
B wins: being near the top of both lists beats being first in one. The same arithmetic works for any number of lists.
On the vector side, exact nearest-neighbour search compares the query to every stored vector. Elasticsearch's documentation says exact search guarantees accurate results but does not scale well to large datasets, and that approximate kNN is best for most production workloads where low latency and scale matter more than perfect recall. Approximation is a deliberate trade: sometimes a true neighbour is missed.
identifier or code?"} A -->|yes| K["Keyword only"] A -->|no| B{"Short product name
the catalogue contains?"} B -->|yes| K2["Keyword first,
vector as backup"] B -->|no| C{"Descriptive or
natural language?"} C -->|yes| H["Hybrid: keyword and
vector, fuse ranks"] C -->|no| K2
Figure 2. A first-pass choice of retrieval mode. How to read this: it is a starting heuristic, not a rule. A real service decides from its own judged queries, which is the next section.
Knowing whether results are good
Without measurement, a relevance change is an opinion. The standard practice is a judged query set: a collection of typical queries, each with documents a person has rated. Elasticsearch's ranking evaluation API expects exactly that and computes standard metrics over it:
- Precision at k: the fraction of the top k results that are relevant.
- Recall at k: how many of all relevant documents appear in the top k.
- Mean reciprocal rank (MRR): the average, over queries, of 1 divided by the rank of the first relevant result.
- Discounted cumulative gain (DCG): takes both rank and rating into account, so highly relevant results near the top count more.
Choose by the query's job: for "find my usual item" the first result matters, so MRR fits; for browsing a category, DCG fits. Precision and recall ignore order within the top k.
Offline metrics say a change is not worse on the judged queries; they cannot say whether shoppers buy more. So follow with an online experiment comparing add-to-cart and purchase rates against a control group, and watch zero-result queries and quick reformulations, which point at gaps.
Recommendation: candidates, scoring, re-ranking
Google's recommendation course describes a three-stage architecture, and the YouTube recommendations paper describes its system as a "classic two-stage" design of candidate generation followed by ranking. The reason is cost. Scoring every item for every request is too slow, so:
- Candidate generation narrows a very large corpus to a small set, and must be fast. Several generators may each propose a different subset.
- Scoring ranks the candidates and picks roughly the ten to show. Because it sees only a small set, it can use a more precise model and more features.
- Re-ranking applies final constraints: remove items the user explicitly disliked, boost fresher content, and enforce diversity and fairness.
Where candidates come from
The course separates two families. Content-based filtering uses similarity between items: "more like this". Collaborative filtering uses similarities between users and items together, so a user can be recommended something unlike anything they have viewed because a similar user liked it. Collaborative methods work from a user-by-item feedback matrix, where feedback can be explicit (a rating) or implicit (a purchase or a view), and learn embeddings: lists of numbers placing users and items in one shared space, so that items liked by similar users end up close together.
A real system runs several generators at once, such as items often bought with the cart contents, similar products and regional favourites; each covers the others' blind spots.
Figure 3. Recommendation serving. How to read this: the top row runs offline and may be hours old; the bottom row runs per request and must finish in a small share of the page's time budget. The dashed return arrow is the data loop: what is shown, clicked and bought becomes tomorrow's training data.
Realistic example (illustrative). On ShopStream's cart page, generators propose a few hundred items: frequent companions of the cart contents, similar products, and regional favourites. The scorer ranks them using features such as the shopper's history and the item's recent conversion. The re-ranker removes anything out of stock, already in the cart or against a dietary filter, limits one brand to two slots, and returns ten.
Cold start and popularity
Two limits appear in every recommender. The course's matrix factorisation page notes that the model can only be queried with a user or item present in its training data, and that popular items tend to be recommended to everyone when dot product is the similarity measure. It adds that neural models can take side features such as age or country. In practice:
- A new product or shopper has no feedback. Fall back to content-based candidates (category, brand, dietary tags) or regional popularity until feedback accumulates.
- Popularity is easy to measure and self-reinforcing: what is shown gets clicked, and what is clicked gets shown. Reserve a small slice of impressions for lesser-known candidates, and log which slot an item was shown in, because a top slot earns clicks partly by being on top.
What gets logged
Both systems need the same events: the query or context, the list shown with positions, what was clicked, added and bought, and the version of the index or model that produced the list. Without the shown list you cannot compute click rates; without the version you cannot tell whether a change helped. This belongs to the analytics pipeline (stream processing basics) and follows privacy rules.
Trade-offs
| Decision | Gain | Cost | Wrong when |
|---|---|---|---|
| Keyword only | Simple, explainable, exact matches | Misses paraphrase | Queries are mostly descriptive |
| Hybrid with rank fusion | Covers both kinds of query | Two retrieval paths, embedding upkeep | The catalogue is small and names are clean |
| Approximate vector search | Low latency at scale | Some true neighbours missed | Every result must be exact |
| Precompute candidates | Fast requests, cheap | Hours-old lists | Context changes every request |
| Compute candidates per request | Fresh, contextual | Latency and cost | The corpus is huge and latency is tight |
| Index volatile fields | One query does everything | Stale stock or price in results | Fields change faster than the index refreshes |
| Verify volatile fields live | Correct badges | An extra lookup per page | The live store cannot take the extra load |
In practice: sold-out items in search results
This is an educational scenario on ShopStream with illustrative numbers.
This is a realistic scenario, not a case history.
The situation
ShopStream's catalogue holds 100,000 products per region (the shared illustrative figure). Shoppers filter by "in stock at my store". One evening, search lists products that cannot be added to the cart.
Starting architecture
Figure 1 without the green box: stock events update each product document, the index evaluates the "in stock" filter, and results trust the index fully.
Options considered
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| A. Shorter refresh interval | Index shows changes sooner | More segment churn; does not help when the indexer lags | The lag is upstream of the engine |
| B. Keep the index for finding; verify stock live for the returned page; alert on freshness | Correct badges even when the index lags | A batched stock lookup per page | The stock service cannot take the extra reads |
| C. Write stock to the index and the database in one request | Looks simple | Two systems can disagree after a partial failure | Either write can fail on its own |
The decision
Option B. The "in stock" filter stays in the index as a cheap first cut, but the page's 20 results are checked against live stock in one batched call; unavailable items are dimmed and moved down, never silently removed. A freshness alert fires when the newest applied event is older than a few minutes (illustrative).
Rollout and verification
Enable the live check for 5 percent of searches (illustrative) and compare the share of results that fail add-to-cart. Practise a rebuild into a second index and an alias switch. Track freshness, zero-result rate and live-check errors.
The 2 a.m. failure
The alert reads: "index freshness 40 minutes". A bad deploy stopped the stock consumer, so the index keeps old stock while the live check is healthy.
First checks: consumer lag and the last applied event time. Mitigation: restart or roll back the consumer; lag clears as it replays. Follow-up: fail a deploy whose consumer is not progressing, and show freshness beside query latency.
Architect's notes
- Separate "find" from "be right". The index finds; the source of truth supplies volatile facts.
- Judge before you tune. A judged query set makes every later change measurable.
- Design a fallback for each ranker. If scoring times out, return candidate order or regional popularity, not an error.
- Keep rules out of models. Stock, age restrictions and dietary filters belong in the re-ranker.
Common mistakes
- Trusting the index for stock and price.
- Changing analysis or weights without a judged set, and arguing from single examples.
- Mixing scores from different scorers with a made-up weighting; use ranks, or fuse deliberately.
- Recommending the most popular items to everyone, then reading the clicks as proof they were wanted.
- Not logging positions, so top-slot clicks look like relevance.
- Scoring the whole catalogue per request instead of generating candidates first.
Key takeaways
- Search and recommendation are retrieve-then-rank systems with hard rules applied last.
- The index is a rebuildable projection; measure its freshness, and verify fast-changing fields live.
- Hybrid retrieval combines keyword and vector lists; rank fusion merges them using ranks, not incompatible scores.
- Measure with a judged query set (precision, recall, MRR, DCG) and then with online experiments.
- Recommenders use candidate generation, scoring and re-ranking, and need fallbacks for cold start and popularity bias.
- Log queries, shown lists with positions, outcomes and the version that produced them.
Practice exercises
Exercise 1 (30 min). Fuse these two ranked lists with RRF at the default constant of 60: keyword (A, B, C, D) and vector (C, A, E, B). Show the scores and the final order.
Exercise 2 (1 hour). Write a judged set of ten ShopStream queries, with at least one exact code, two descriptive requests and one that should return nothing. State which metric you would track for each.
Related reading
- Search engines and the inverted index: analysis, BM25 and sharded clusters in depth.
- ShopStream: search, notifications and media: the first version of this system in the running project.
- Pagination: offset, cursor and keyset.
- Stream processing basics: how the feedback events are processed.
- Cache strategies: the precomputed candidate store is a cache with a refresh policy.
Official documentation
- Elastic, Near real-time search and Text analysis.
- Elastic, Similarity settings and Reciprocal rank fusion.
- Elastic, k-nearest neighbor search, Ranking evaluation API and Paginate search results.
- Google for Developers, Recommendation systems overview and Collaborative filtering.
- Covington, Adams and Sargin, Deep Neural Networks for YouTube Recommendations (RecSys 2016).