Search Indexes
The inverted index.
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: 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.
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"))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.
| key | value |
|---|---|
| Ranking | best matches first |
| Typos, plurals | mug ≈ mugs |
| Sharded | huge indexes |
| Copy of the DB | not 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