Sub topic 15
How the index feeds search results
The previous chapters followed a page from discovery to an index entry. This chapter covers the last step, where the index answers a query. It assumes you have read the chapter on building an inverted index. You should also be comfortable reading short Python snippets and know what a posting list is (the set of document IDs stored under one token).
What serving does
Serving starts when a user submits a query. The system must return a ranked list of pages within a few hundred milliseconds. It cannot crawl, fetch, or parse anything at that point. All of that work was done earlier and stored in the index.
This split explains several behaviors you will see in practice:
- A page you just published is not searchable until the crawler fetches it and the indexer writes it. The search box only reads what the index already holds.
- A page you changed can show an old title or snippet, because serving reads the stored copy, not the live page.
- Removing a page from your site does not remove it from results at once. It disappears when the index is updated.
The query path
A query goes through the same text processing as documents, then touches the index, then is ranked and formatted.
Step 1: process the query like a document
The query must be tokenized the same way the documents were. If the indexer lowercased text and split on non-alphanumeric characters, the query must do the same. Otherwise Pages would never match the stored token pages.
A mismatch between index-time and query-time processing is a common cause of "the word is on the page but the search does not find it". Real systems also apply steps such as stemming (reducing crawling to crawl) or synonym expansion. Whatever the pipeline does at index time, the query side has to mirror.
Step 2: retrieve candidates from posting lists
For each query token, the system reads its posting list. For a multi-word query, it combines the lists:
- AND keeps only documents that appear in every list. This is the intersection from the earlier chapter.
- OR keeps documents that appear in any list. This returns more candidates, and ranking has to sort out the weak ones.
Posting lists are usually stored sorted by document ID. Two sorted lists can then be intersected by walking both at once, without building sets in memory. This matters at scale, where a common word's list can contain millions of IDs.
The index is also split into shards, each holding a subset of documents. The frontend sends the query to all shards at once and merges their top results. A slow shard slows the whole query, so serving systems set time limits and sometimes return partial results.
Step 3: rank the candidates
Retrieval answers "which documents contain these words". Ranking answers "which of those should come first". The index can store extra data to support this, such as how often a term appears in a document and where it appears.
A simple signal is term frequency (TF), the number of times a token occurs in a document. The example below stores counts in each posting and sorts by their sum.
import re
from collections import Counter, defaultdict
docs = {
1: "Search engines crawl web pages",
2: "Crawlers follow links to find web pages. Good web pages link to other web pages.",
3: "An index maps words to pages",
}
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
# token -> {doc_id: number of times the token occurs in that document}
index = defaultdict(dict)
for doc_id, text in docs.items():
for token, count in Counter(tokenize(text)).items():
index[token][doc_id] = count
def search(query, top_k=10):
tokens = tokenize(query)
if not tokens:
return []
postings = [index.get(t, {}) for t in tokens]
matching = set(postings[0]).intersection(*postings[1:])
scored = [(sum(p[d] for p in postings), d) for d in matching]
scored.sort(key=lambda pair: (-pair[0], pair[1]))
return [(d, score) for score, d in scored[:top_k]]
print(search("web pages"))This prints [(2, 6), (1, 2)]. Document 2 ranks first because "web" and "pages" each occur three times. Document 3 is not a candidate because it lacks "web".
Raw term frequency is a weak ranking signal on its own. A page can repeat a word to inflate its score, and common words such as "the" would dominate. Real engines weight rare terms more heavily (inverse document frequency, or IDF). They also combine hundreds of other signals, such as link-based authority, page quality, and freshness. The exact formula is a design choice of each engine and is not public for the large ones.
Step 4: build the results page
The index usually stores only IDs and positions, not full page text. To show a result, the frontend fetches stored data for the top documents:
- the title and URL, using the canonical URL chosen during canonicalization
- a snippet, which is a short excerpt of the stored text around the query terms
- extra fields such as a last-crawled date
Because this data is a stored copy, it reflects the page as of the last crawl. Snippets may also be generated from the page's meta description, depending on the engine.
How earlier stages shape what users see
Each earlier decision has a visible effect at serving time.
| Earlier stage | Effect on results |
|---|---|
| Canonicalization | Duplicate URLs are folded into one result, and the canonical URL is the one displayed. |
| `noindex` | The page is never written to the index, so it cannot be retrieved. |
| robots.txt block | The page cannot be fetched, so its content is not indexed. The bare URL can still appear if other pages link to it. |
| Rendering | Text added by JavaScript is searchable only if the page was rendered before indexing. |
| Recrawl schedule | Snippets and rankings lag behind the live page by the time since the last crawl. |
Index updates and visibility
Large indexes are not rebuilt from scratch for every change. A common design keeps a large, mostly static main index and a small, frequently updated one for new and changed documents. Queries read both and merge the results. Periodically the small index is merged into the main one.
Deleted pages work through a similar route. The system marks the document ID as deleted, and serving filters it out of candidates. The space is reclaimed during a later merge. This is why there is often a gap between a page returning a 404 or 410 status and its disappearance from results.
Practical consequences
When results look wrong, work out which side of the handoff the problem is on:
- If the page is missing from results, check whether it was indexed at all. Use the diagnosis steps from the final chapter.
- If the page is indexed but ranks poorly, the issue is in ranking, not crawling. Re-crawling will not fix it.
- If the page appears with an old title or snippet, the stored copy is stale. The fix is a recrawl, not a change to ranking.
- If the wrong URL appears, check canonical signals, because serving shows the URL chosen during duplicate handling.
Limits of the simple model
The code above is a teaching model. It differs from production serving in several ways:
- It holds everything in memory on one machine, while real indexes are sharded and compressed on disk.
- It supports only AND queries. Real engines handle phrases, which need word positions in the postings, and handle misspellings.
- Its ranking is raw term counts. It has no IDF weighting, no link signals, and no quality signals.
- It has no snippet generation, no personalization, and no filtering for language or location.
Still, the core idea holds. Crawling and indexing prepare data in advance so that serving only has to look up and sort.
Exercise
A page was crawled yesterday and is in the index. Today you edit its title. A search shows the old title. Which stage explains this, and what will change it? Also, would adding the word "pages" a hundred times to the page body reliably raise its rank, and why or why not?
Show answer
Serving reads the title from the stored copy made at the last crawl, so the old title shows until the page is recrawled and reindexed. Repeating "pages" would raise a raw term-frequency score in a simple model like the one above. It would not reliably help in a real engine, which weights rare terms more heavily through IDF, combines many other signals, and can discount stuffed text.
Exercise
In the Python example, change the query to "web index". What does search return, and why?
Show answer
It returns an empty list, []. No document contains both "web" and "index", so the intersection of the two posting lists is empty. Document 3 has "index" but not "web", and documents 1 and 2 have "web" but not "index".