Data · L2Search systems and inverted indexes

Search systems and inverted indexes

A search engine does not scan your text. It looks words up in an inverted index, ranks the matches, and must be kept in step with your database.

L2 SeniorData17 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 21 Oct 2026 · How we check content
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

This story is made up, but it is common. A small shop has a search box. The code runs SELECT * FROM products WHERE title ILIKE '%shoe%'. With 5,000 products, it answers fast.

Two years later there are 3 million products. Each search now reads every row, because no normal index can help with a pattern that starts with %. During a sale, searches use most of the database CPU, and checkout slows down too.

The results are also poor. A search for "running shoes" does not find "Shoe for runners". The results come back in no useful order.

So the team adds Elasticsearch. The code saves each product to Postgres and then to Elasticsearch. One night the Elasticsearch call times out for some saves. The prices in search no longer match the real prices, and nobody notices for a week.

Both problems have known fixes. This lesson explains them.

Section 2 of 8

The idea in simple words

The Postgres docs list three problems with LIKE search. It has no language support, so satisfies does not match satisfy. It does not rank results. And it tends to be slow, because there is no index support, so it must process every document for every search. 1

A search engine fixes this in two steps.

  1. When you add a document, it splits the text into words, cleans each word, and records which documents contain it.
  2. When you search, it cleans the query words the same way, looks them up, and ranks the matching documents.

The record from step 1 is an inverted index. A book index is a good picture: "replication, pages 40, 112, 305". You do not read the whole book to find a word.

The key idea. Search is fast because the work happens when you write. Each document is broken into terms once, and each term points to its documents. A query reads only a few short lists.

Section 3 of 8

How it works

Step through three product titles, the index built from them, and one query. Use Next and Back, or the ← and → keys.

Three documents become an inverted index, and a query joins two listsProduct titles 1 · Red Running Shoes2 · Blue Shoes for Kids3 · Red Kids Jacket analyze: lowercase, stem, drop “for”1 → red, run, shoe2 → blue, shoe, kid3 → red, kid, jacket inverted index: term → documentsred → 1, 3run → 1shoe → 1, 2blue → 2kid → 2, 3jacket → 3 query “RED kids” → red, kidred: 1, 3kid: 2, 3 ✓ both lists share document 3 SeniorPath
  1. Three product titles are sent to the search engine. Each one gets a document ID: 1, 2 and 3.
  2. An analyzer turns each title into terms. It makes words lowercase, cuts them to a root form (running → run, kids → kid), and drops the common word “for”.
  3. The engine builds an inverted index. For each term, it keeps the list of documents that contain it. It does not scan the titles again.
  4. A user searches for “RED kids”. The query goes through the same analyzer, so it becomes the terms red and kid. The engine reads just these two lists.
  5. For an AND search, the engine keeps the IDs that appear in both lists: only document 3. If many documents match, a score such as BM25 decides their order.
Step 1 of 5

Step 1: analysis (tokenize and normalize)

Elasticsearch calls this text analysis. Tokenization breaks text into small pieces called tokens. Normalization makes near matches equal. It can lowercase Quick to quick, stem foxes to fox, and index the synonyms jump and leap as one word. 4

Postgres does the same work with dictionaries. Its normalized words are called lexemes. Very common words, like "the", are stop words and are usually dropped. 1

Elasticsearch can apply the same rules to the query text. 4 Always do this. If the index holds shoe but the query asks for Shoes, nothing matches.

Step 2: the inverted index

Each Elasticsearch shard is a Lucene index. 11 Lucene's docs call the inverted index its core. It is made of postings, which let you look up the documents for a given term. 5 It can also store the positions of a term inside each document. 5 Positions make phrase search possible, like "red shoes" as two words side by side.

Postgres has an inverted index too. Its GIN index has one entry for each lexeme, with a compressed list of where it appears. The docs call GIN the preferred index type for text search. 2

Step 3: ranking

A query for "red shoes" may match 40,000 products. Which come first? The engine gives each match a score.

The classic idea is TF-IDF. Lucene's docs explain its parts. A document that contains a term more often scores higher. Rarer terms add more to the score. And a match in a shorter field counts for more. 6

So "jacket" in 10 products tells you more than "red" in 50,000 products.

BM25 is a newer formula built on the same TF-IDF ideas, with built-in term frequency normalization. 8 Lucene's BM25 class traces it to the Okapi system at TREC-3, in 1994. 7 It is the default similarity in Elasticsearch. 8 Its two main settings are:

  • k1 (default 1.2) controls saturation: how fast extra repeats of a word stop adding score.
  • b (default 0.75) controls how much document length affects the score. 8

You rarely change these. Most relevance work is in the analyzer, the fields you search and the boosts you add.

Near real-time: refresh

New documents are not searchable the moment you write them. Elasticsearch collects them and, on a refresh, writes them to a new segment and opens it for search. A segment is similar to an inverted index. 9

By default, Elasticsearch refreshes every second. It only does this for indices that got at least one search request in the last 30 seconds. 9

You can ask a write to wait. refresh=true makes the change visible at once, but it creates tiny segments that cost more at index, search and merge time. refresh=wait_for waits for the next refresh instead. The docs say to use the default, refresh=false, unless you have a good reason. 10

Shards and replicas

An Elasticsearch index is split into shards. Each shard is a self-contained Lucene index with part of the documents. Each document belongs to one primary shard. A replica shard is a copy of a primary, for failover and for more read capacity. 11

You choose the number of primary shards when you create the index, and you cannot change it later. You can change the number of replicas at any time. 11

Each shard runs a search on one CPU thread. Too many small shards slow search and can make the cluster unstable. Elastic suggests shards between 10 GB and 50 GB. 12

Keeping the index in sync

The search index is a copy. Your database is the source of truth. The dangerous design is the one from the story: write to the database, then write to the search engine in the same request. If the second write fails, the copy is wrong, and nothing repairs it.

Safer designs read changes from the database itself:

  • Outbox. In the same transaction as the product change, insert a row into an outbox table. A worker reads it and updates the index.
  • CDC (change data capture). A tool reads the database's change log and sends each change to the indexer.

Both are explained in Sagas, outbox and CDC. Make index updates idempotent: send the full document with its ID, so a retry is harmless. Keep a script that rebuilds the whole index from the database, because you will need it after mapping changes.

When Postgres is enough

You may not need a second system. Postgres gives you tsvector, tsquery, stemming dictionaries and a GIN index. 1 2 It can rank with ts_rank and ts_rank_cd. But ranking must read the tsvector of each matching document, so it can be slow when a query matches many rows. 3

Start with Postgres when the data fits in one database and the search needs are simple. Move to a search engine when you need better relevance, typo tolerance, facets, or search load that would hurt your main database.

Section 4 of 8

Trade-offs

OptionFast on big data?Good ranking?Extra cost
LIKE '%x%'No Every row is checked.No None at first.
Postgres full-text search + GINYes , for many workloads.Basic: ts_rank. Slow with many matches.Little. Same database and same transaction.
Elasticsearch or OpenSearchYes Shards spread the load.Yes BM25, analyzers, boosts.A second cluster to run and an index to keep in sync.
Managed search serviceYes Yes , with less tuning.Money and less control. Still needs sync.

Simple rule: start with Postgres full-text search. Add a search engine when relevance or load needs it, and feed it from an outbox or CDC.

Section 5 of 8

At work: how a senior uses this

  • When you see LIKE '%...%' on a growing table, ask: "How many rows will this read in a year?"
  • Write down the analyzer for each field. Test it with real queries from your users, including plurals, accents and typos.
  • Treat the search index as derived data. Ask in design review: "How do we rebuild it from scratch, and how long does that take?"
  • Monitor sync lag: the time between a database change and when search shows it. Alert on it.
  • Do not set refresh=true on every write to fix "I can't see my change". Use wait_for only where a user must see their own write. 10
  • Pick shard counts from expected data size, not from a guess. The primary count is fixed, so changing it means building a new index. 11
  • Keep a small set of test queries with the results you expect. Run it after each analyzer or scoring change.
Section 6 of 8

With AI

What to ask the agent

"Find every SQL query in this repo that uses LIKE or ILIKE with a leading %. For each, estimate the table size and suggest a full-text index or a search engine."

"Add a Postgres full-text search on products.title and products.description, with a GIN index on a generated tsvector column, and rank with ts_rank."

"Write an outbox worker that reads product changes and sends the full document to Elasticsearch by ID. It must be safe to run twice."

What to check yourself

  • The query uses the same language config or analyzer as the index. Otherwise matches are missed.
  • The agent did not add a direct database-then-search write in the request path.
  • Index writes use the document ID, so retries replace instead of adding duplicates.
  • No refresh=true on every write.
  • Test with real queries, not just the one the agent picked.
Section 7 of 8

Check yourself

1. Why is WHERE title LIKE '%shoe%' slow on a big table?

Show answer

A normal B-tree index cannot help with a leading %, so every row must be checked. The Postgres docs say LIKE searches have no index support, so they must process all documents for every search.

2. What does an inverted index store?

Show answer

For each term, the list of documents that contain it. An inverted index maps a term to its postings, the documents that contain the term.

3. In BM25 and TF-IDF scoring, which word adds the most to a document's score?

Show answer

A rare word that appears in only a few documents. Inverse document frequency gives rare terms a bigger weight, because they say more about which documents match.

4. You save a product, then search for it at once, and it is not found. What is the most likely reason in Elasticsearch?

Show answer

The index has not refreshed yet, so the new segment is not open for search. Search is near real-time. New documents become searchable after a refresh, by default within about a second for indices that are being searched.

5. Your service writes to Postgres and then to Elasticsearch. The second write sometimes fails. What is a safer design?

Show answer

Write an outbox row in the same database transaction, or use CDC, and let a worker update the index. The database stays the source of truth. A worker reads changes from it and updates the index, so no change is lost.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 12 sources and related lessons
  1. PostgreSQL documentation: Full Text Search, Introduction (opens in a new tab)
    Why LIKE is not enough, and how documents become normalized lexemes (tsvector) and queries become tsquery.
  2. PostgreSQL documentation: Preferred Index Types for Text Search (opens in a new tab)
    GIN is an inverted index and the preferred type for text search. GiST is lossy.
  3. PostgreSQL documentation: Controlling Text Search (ranking) (opens in a new tab)
    ts_rank and ts_rank_cd, and why ranking many matches can be slow.
  4. Elastic Docs, “Text analysis” (opens in a new tab)
    Tokenization, normalization (lowercase, stemming, synonyms) and analyzers, with examples.
  5. Apache Lucene 9.12 API: package org.apache.lucene.index (opens in a new tab)
    Lucene's own description of the inverted index as fields, terms and postings.
  6. Apache Lucene 9.12 API: TFIDFSimilarity (opens in a new tab)
    The ideas behind term frequency, inverse document frequency and length norms.
  7. Apache Lucene 9.12 API: BM25Similarity (opens in a new tab)
    Lucene's BM25 class, its origin in Okapi at TREC-3, and its defaults k1 = 1.2 and b = 0.75.
  8. Elastic Docs, “Similarity settings” (opens in a new tab)
    BM25 is the default similarity in Elasticsearch, and what k1 and b control.
  9. Elastic Docs, “Near real-time search” (opens in a new tab)
    Segments, refresh, and the default one-second refresh for indices that are being searched.
  10. Elastic Docs, “refresh parameter” (opens in a new tab)
    refresh=false, true and wait_for, and why forcing a refresh on each write is costly.
  11. Elastic Docs, “Clusters, nodes, and shards” (opens in a new tab)
    Primary and replica shards, and why the number of primary shards is fixed.
  12. Elastic Docs, “Size your shards” (opens in a new tab)
    Shard size targets, one search thread per shard, and the cost of too many shards.

Case studies: Anthropic: Contextual retrieval: add context to chunks before indexing

Related: Secondary, composite and special indexes · Sagas, outbox and CDC · Product search and discovery (coming soon) · Sharding and consistent hashing · PostgreSQL in depth

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper