← All lessons

Key technologies

Elasticsearch

A search engine that people keep trying to use as a database. It is extraordinary at relevance and aggregations over text, and it is a derived copy of your data — never the source of truth.

19 min readUpdated November 2026Free

Search appears in a surprising number of interview questions: product search for an e-commerce site, searching messages in a chat app, finding a restaurant “near me that does biryani”, log search in an observability system. The usual answer is “Elasticsearch”, and the usual follow-ups are how does the data get there, how fresh is it, and what happens when the index needs to change.

The one sentence to carry in: Elasticsearch is a search index you feed from your database, not a database you search. (OpenSearch, the AWS fork, behaves the same for everything here.)

What it actually is

Elasticsearch is a distributed layer over Apache Lucene, a library that builds and queries inverted indexes. An index in Elasticsearch is split into shards; each shard is one Lucene index, and each shard has replicas on other nodes for availability and read throughput.

A query fans out to one copy of every shard, each shard returns its best matches, and a coordinating node merges them — the scatter-gather from the partitioning lesson, done for you.

The inverted index

A database index maps a row to its values. An inverted index maps each term to the list of documents that contain it — like the index at the back of a book.

Three documents: 1, wireless headphones noise cancelling; 2, wired headphones for studio use; 3, wireless charging pad. The inverted index maps each term to document ids: headphones to 1 and 2, wireless to 1 and 3. A query for wireless headphones intersects the two lists and returns document 1. DOCUMENTS1Wireless headphones, noise cancelling2Wired headphones for studio use3Wireless charging padanalyzeINVERTED INDEX (some of its terms → doc ids)charging[3]headphones[1, 2]noise[1]wired[2]wireless[1, 3]query: "Wireless Headphones" → analyzed to [wireless, headphones][1, 3] ∩ [1, 2] = [1]— no document was scanned, only two short sorted lists.
An inverted index answers "which documents contain these words" without reading the documents.

To find documents containing both “wireless” and “headphones”, Lucene intersects two sorted lists of document ids, which is fast regardless of how long the documents are. A relational LIKE '%wireless%' has to scan every row; this never does.

Analysis: where the terms come from

Before indexing, text goes through an analyzer: a tokenizer splits it into words, and filters lowercase them, strip punctuation, drop stop words and reduce words to stems (“running” → “run”). The same analyzer runs on the query, so “Running Shoes” matches a document saying “run shoe”.

Where candidates lose it

Mapping a field as text makes it analyzed and searchable by word; mapping it as keyword keeps the exact value for filtering, sorting and aggregations. Get it wrong and either status: "Shipped" doesn’t match "shipped", or you can’t sort by a field because it was tokenised. Most string fields want both: text with a .keyword sub-field. Mappings can’t be changed in place for existing fields — fixing one means a reindex.

Relevance: why the right result comes first

Matching is the easy part; ranking is the product. By default Elasticsearch scores with BM25:

Then you shape it: boost the title field over description, add a function_score for popularity or recency, filter by location with geo_distance. Put hard constraints (in stock, category, price range) in a filter clause — they don’t affect scoring and are cached — and only the fuzzy matching in must/should.

Near-real-time, not real-time

New documents go into an in-memory buffer and become searchable only after a refresh, which writes a new Lucene segment. The default refresh interval is 1 second. Durability is separate: the translog records each write so it survives a crash before the segment is committed to disk.

So a product updated now appears in search about a second later. That is fine for search; it is wrong for “check stock before checkout”. Read stock from the database.

The point

Segments are immutable, like Cassandra’s SSTables. An update is a delete-mark plus a new document, and background merging combines small segments and drops deleted documents. Heavy update rates cost merge work — which is why bulk loads often set refresh_interval: -1 and turn it back on after.

Getting data in: the sync problem

The database is the source of truth, and Elasticsearch has to follow it. Three ways, from worst to best:

  1. Dual writes from the application. Write Postgres, then write Elasticsearch. If the second write fails or the process crashes between them, the index silently disagrees with the database forever.
  2. Outbox + worker. Write an “index this” row in the same transaction as the change; a worker reads the outbox and updates Elasticsearch, retrying until it succeeds.
  3. Change data capture. Debezium reads the database’s WAL, publishes every change to Kafka, and a consumer indexes it. It catches every write path, including migrations and admin edits. See the CDC lesson.

Either way, keep a full reindex path: a job that rebuilds the index from the database. You will need it for every mapping change, and it is the recovery plan when the index drifts.

Reindexing without downtime

Because mappings and shard counts can’t be changed in place:

  1. Create products_v2 with the new mapping.
  2. Backfill it from the database (or _reindex from products_v1), while the change stream writes to both indexes.
  3. When caught up, atomically switch the alias products from v1 to v2.
  4. Delete v1 later.

The application always queries the alias, so it never knows. Use aliases from day one.

Shards: picking the number

The primary shard count is fixed at index creation. Aim for shards of roughly 10–50 GB, and remember every shard costs memory and file handles on its node — a cluster with tens of thousands of tiny shards is slow and unstable. For time-based data (logs, events), use one index per day or week with an alias or data stream over them, so old data is dropped by deleting an index, not by deleting documents.

Where it hurts in production

Elasticsearch versus the alternatives

Reach for it when Avoid when
Elasticsearch / OpenSearch Relevance-ranked text search, faceting, log analytics It would be your only copy of the data
Postgres full-text Up to a few million rows, simple ranking, one less system Typo tolerance, complex relevance, high query volume
Typesense / Meilisearch Instant, typo-tolerant site search with little tuning Huge datasets or heavy aggregations
ClickHouse Aggregations over billions of structured events Relevance ranking on text
Vector DB / pgvector Semantic similarity on embeddings Exact keyword matching and filters alone

When to propose it in an interview

Any time the question says “search”: products, messages, documents, places, logs. Say how it is fed and what freshness that gives.

Say it like this

“Products live in Postgres. Debezium streams changes to Kafka and a consumer indexes them into an Elasticsearch alias, so search is about a second behind and every write path is covered. Title and brand are text with a .keyword sub-field for facets, filters for category, price and stock go in filter so they’re cached, and I boost by sales rank. If we change the mapping, we build v2 behind the alias and flip it. Checkout never reads Elasticsearch.”

Sizing it on the whiteboard

Say 50 million products at ~5 KB indexed each:

The follow-ups, and the one-line answers

  1. “How is the data kept in sync?” CDC or an outbox, never dual writes, plus a full reindex job.
  2. “How fresh is search?” About a second, the refresh interval.
  3. “You need to change a field’s type.” New index, backfill, flip the alias.
  4. “text or keyword?” text to search words, keyword to filter, sort and aggregate — usually both.
  5. “Page 500 of results?” search_after, not from/size.
  6. “Why not just Postgres?” For a few million rows, do. For typo tolerance, relevance tuning and heavy query load, this.