Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Mini Search Engine

Build the machinery behind every search box: an inverted index, boolean matching, and TF-IDF ranking that puts the most relevant document first — the core of Elasticsearch in about forty lines.

Advanced 4 steps 140 XP ~50 min

How it works in the real world

Searching by scanning every document is hopeless at scale. Real engines invert the problem:

  1. Index — map each term to the set of documents containing it. Lookup becomes a dictionary hit instead of a scan.
  2. Match — intersect those sets to find documents containing every query word.
  3. Weight — a word in every document tells you nothing; a rare word is a strong signal. That is inverse document frequency.
  4. Rank — score each match by term frequency times IDF and sort.

This is genuinely how Lucene, Elasticsearch and Postgres full-text search begin. You'll build all four stages against a tiny corpus.

Build progress0 / 4 steps
1

Build the inverted index

Map every word to the set of document ids containing it. Print the number of distinct terms, then the sorted posting list for python, data and language.

Blank · autosaved
PYstep_1.py
Run your code to check this step…
2

Boolean AND search

Write search_all(query) returning the sorted ids of documents containing every query word. Print the result for four queries, including one that matches nothing.

Blank · autosaved
PYstep_2.py
Run your code to check this step…
3

Score terms with IDF

Document frequency is how many docs contain a term; IDF is log(N / df). Print df and idf (3 decimals) for python, data and the — note the rare word scores highest.

Blank · autosaved
PYstep_3.py
Run your code to check this step…
4

Rank with TF-IDF

Score each matching document as the sum over query words of tf * idf, where tf is the word's share of that document's words. Print results for data python, best first.

Blank · autosaved
PYstep_4.py
Run your code to check this step…
Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path