Search systems

Topic 7 of 8 in Week 6: Production concerns10 min readIntermediateFree course

Overview

WHERE title LIKE '%running shoes%' works on a thousand rows and collapses on ten million: it scans every row, can’t rank results and misses “run shoe”. Search engines use a different data structure, the inverted index, to find and rank matching documents in milliseconds. Search appears in many design problems, from e-commerce to the autocomplete case study.

The inverted index

How a search index works. Three documents, doc 1 Red running shoes, doc 2 Blue running jacket and doc 3 Red rain jacket, go through an analyser that lowercases and stems the text. The resulting inverted index maps each term to a posting list: red to documents 1 and 3, running to 1 and 2, shoes to 1, blue to 2, jacket to 2 and 3, and rain to 3. The query red jacket intersects red’s documents 1 and 3 with jacket’s documents 2 and 3, giving document 3, which is then ranked by relevance with BM25, freshness and popularity. Engines include Elasticsearch, OpenSearch and Solr, or a database’s own full-text search for small data. The index is a derived copy fed from the source of truth by change events and rebuilt when needed.

Like the index at the back of a book, an inverted index maps each term to a posting list of documents (and often positions) where it appears. A query looks up each term’s list and combines them: intersection for AND, union for OR. Because posting lists are sorted and compressed, this is fast even over billions of documents.

Text analysis

Before indexing, text goes through an analyser:

  • tokenising: split into words,
  • normalising: lowercase, remove accents,
  • stemming or lemmatising: “running”, “runs” → “run”,
  • stop words: optionally drop “the”, “a”,
  • synonyms: “cycle” ↔ “bicycle”, “tv” ↔ “television”.

The same analysis is applied to queries so they match. Different languages need different analysers.

Typo tolerance uses fuzzy matching (terms within an edit distance of 1–2), and autocomplete uses prefix-optimised structures (edge n-grams or tries, covered in the autocomplete case study).

Ranking

Matching documents must be ordered:

  • Text relevance: BM25, the standard scoring function, rewards terms that are frequent in the document but rare overall, and adjusts for document length. Matches in the title can be boosted over the description.
  • Business signals: freshness, popularity, ratings, sales, personalisation, availability.
  • Learning to rank: large systems train models on click and purchase data to combine hundreds of signals.

Filters (category, price range, location) don’t affect the score; they just include or exclude documents and are cached efficiently.

Search at scale

Engines such as Elasticsearch and OpenSearch (built on Lucene) distribute the index:

  • the index is split into shards spread across nodes; each shard has replicas for availability and read throughput,
  • a query is sent to every shard in parallel (scatter-gather); each returns its top results, and a coordinator merges them,
  • new documents become searchable after a short refresh interval (typically about a second): near-real-time, not instant.

Deep pagination is expensive (every shard must return many results to merge), so use cursor-style search_after and cap the page depth.

Keeping the index in sync

The search index is derived data, not the source of truth:

  1. Writes go to the primary database.
  2. Changes flow to the indexer through events (outbox) or change data capture from the database log.
  3. The indexer upserts or deletes documents.

Plan for drift and change: periodically rebuild the index from the database into a new index and switch an alias to it, which also lets you change mappings or analysers without downtime.

When you don’t need a search engine

For small datasets or simple needs, the database may be enough: PostgreSQL has full-text search with ranking and trigram indexes for fuzzy matching. Add a dedicated engine when you need advanced relevance, facets, scale or high query volume.

In an interview

“Listings are indexed in OpenSearch, fed from PostgreSQL via CDC and Kafka within a few seconds. Queries combine full-text match on title and description with filters on city, category and price, ranked by BM25 with boosts for recency; the index has 12 shards with one replica each.”

Recap

Search engines use inverted indexes that map terms to documents, with analysers that normalise text at index and query time. Results are ranked by BM25 plus business signals, filters narrow results cheaply, and clusters shard and replicate the index and query shards in parallel. Treat the index as derived data, synchronised from the source of truth and rebuilt when needed.

Exercise

Add search to a marketplace

A second-hand marketplace has 20 million listings stored in PostgreSQL. Users want to search by keywords ('blue cycle 26 inch'), filter by city, price range and category, and sort by relevance or newest. New listings should be searchable within a few seconds; sold listings should disappear. Design the search system: storage, how the index stays updated, how queries run, and how to handle typos.

Text
Index and storage:

Keeping it updated:

Query handling:

Typos and relevance:

Summary

  • Full-text search uses an inverted index that maps each term to the documents containing it.
  • Text analysis (tokenising, lowercasing, stemming, synonyms) happens at index time and query time.
  • Results are ranked by relevance (BM25) combined with business signals such as freshness and popularity.
  • Search engines like Elasticsearch/OpenSearch shard and replicate the index across nodes and query all shards in parallel.
  • The index is derived data: keep it in sync from the source of truth with events or CDC, and rebuild it when needed.