AI Hints
Home›System Design Tutorial›Storing More Kinds of Data
System Design · Lesson 51 of 120

Search Indexes

The inverted index.

⏱ 2 min read▶ Video at 1:00:09🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

A customer types blue mug into Shoply's search box. Scanning every product description for those words would be slow. Search engines use a structure called an inverted index.

Search Indexes
From the video: Search Indexes
  • Search: blue mug
  • Scanning is slow
  • An inverted index

Building an inverted index

An inverted index maps each word to the products that contain it. Like the index at the back of a book, but for every word. To search, we look up each word, and keep the products that appear in every list. Run it. Blue mug finds products one and three, without scanning any descriptions.

search.pypython
products = {
    1: "blue ceramic mug",
    2: "red tea pot",
    3: "large blue coffee mug",
    4: "blue tea towel",
}

index = {}
for pid, text in products.items():
    for word in text.split():
        index.setdefault(word, set()).add(pid)

def search(query):
    lists = [index.get(w, set()) for w in query.split()]
    return sorted(set.intersection(*lists))

print("blue ->", sorted(index["blue"]))
print("blue mug ->", search("blue mug"))
Output
blue -> [1, 3, 4]
blue mug -> [1, 3]

Search in practice

Real search engines, like Elasticsearch, add much more. They rank results by relevance. They handle typos, and word forms like mug and mugs. And they shard the index across many machines. Usually, the database stays the source of truth, and changes are copied into the search index.

keyvalue
Rankingbest matches first
Typos, pluralsmug ≈ mugs
Shardedhuge indexes
Copy of the DBnot the source of truth

Summary

An inverted index maps words to the items that contain them, so searches skip scanning. Tools like Elasticsearch build on this. Next, how to choose the right database.

Key takeaways
  • Word to items
  • Intersect the lists
  • Elasticsearch in practice
Next up: Choosing a Database — a decision guide