Elasticsearch
Elasticsearch is a distributed search and analytics engine. You send it JSON documents, it indexes every field, and you can then run full-text queries ("blue running shoes"), structured filters (price < 100), geo queries and aggregations over billions of documents with response times in the tens of milliseconds. Under the hood, each shard of an Elasticsearch index is an Apache Lucene index, and Elasticsearch adds the distribution: sharding, replication, routing and a cluster coordinator on top.
A few properties are worth separating:
- Inverted index first: Elasticsearch is built around the data structure that makes text search fast: a map from each term to the list of documents that contain it. Relational databases are built around B-trees on rows. That difference explains almost everything Elasticsearch is good and bad at.
- Near real-time, not real-time: A document you index becomes searchable after the next refresh, which happens every second by default. A read by ID sees it immediately; a search may not.
- Distributed by shards: An index is split into a fixed number of primary shards, each copied to replica shards on other nodes. Searches fan out to every shard and merge the results.
- Schema on write, flexible documents: Documents are JSON, but every field has a type in the index's mapping, and the type decides how it's indexed. Getting the mapping right is most of the work.
- Not a system of record: Elasticsearch has no multi-document transactions, no joins in the relational sense and a history of being the place where data quietly drifts. It's almost always a secondary index fed from a primary database.
In interviews, Elasticsearch shows up whenever a design needs search: product search on an e-commerce site, post search on a social network, log search, typeahead, "restaurants near me with good ratings." Interviewers rarely want internals for their own sake. They want to see that you know why a search engine beats LIKE '%shoe%', how data gets from your database into the index, and what happens to freshness, consistency and cost at scale. That's what we'll cover.
The Data Model
Elasticsearch organizes data into indices (roughly a table), which hold documents (roughly a row, as JSON), which have fields. Each document has an _id, and the original JSON is stored in a _source field so it can be returned in results.
The mapping defines each field's type. Here's a mapping for a product catalog:
PUT /products
{
"settings": {
"number_of_shards": 6,
"number_of_replicas": 1,
"analysis": {
"analyzer": {
"english_text": {
"type": "custom",
"tokenizer": "standard",
"filter": ["lowercase", "english_stop", "english_stemmer"]
}
},
"filter": {
"english_stop": { "type": "stop", "stopwords": "_english_" },
"english_stemmer": { "type": "stemmer", "language": "english" }
}
}
},
"mappings": {
"properties": {
"title": { "type": "text", "analyzer": "english_text",
"fields": { "raw": { "type": "keyword" } } },
"brand": { "type": "keyword" },
"category": { "type": "keyword" },
"price_cents": { "type": "long" },
"rating": { "type": "float" },
"in_stock": { "type": "boolean" },
"created_at": { "type": "date" },
"location": { "type": "geo_point" }
}
}
}
The most important distinction is between text and keyword:
- A
textfield is run through an analyzer and broken into terms. "Men's Running Shoes" becomesmen,run,shoeafter tokenizing, lowercasing and stemming. Use it for anything people search with words. - A
keywordfield is indexed as one exact value."Nike"is the termNike. Use it for IDs, enums, tags, and anything you filter, sort or aggregate on exactly.
The title.raw sub-field above is a common pattern: index the same value both ways, so you can search the title by words and also sort or aggregate on the exact string.
Analyzers run at index time and again at query time on the query string, so both sides are normalized the same way. An analyzer is a pipeline: character filters (strip HTML), a tokenizer (split on word boundaries), and token filters (lowercase, remove stop words, stem, add synonyms). Swapping the analyzer changes what "matches," which is why "why didn't my search find X?" is so often a mapping question.
If you leave mappings to dynamic mapping, Elasticsearch guesses types from the first document it sees. A field that first arrives as
"42"becomes text plus keyword, a field that should be a date might be a string, and every new key in a free-form JSON blob becomes a new field. In an interview, say you'd define explicit mappings and disable dynamic mapping for user-supplied objects. It avoids mapping explosion, where an index grows tens of thousands of fields and cluster state balloons.
There are no joins across indices at query time in the relational sense. You denormalize instead: a product document carries its brand name, category path and average rating, even though those live in separate tables in your primary database. Elasticsearch offers nested fields (arrays of objects queried as units) and a join field type for parent/child documents within one shard, but both cost query speed. The usual answer is to flatten the data at index time and accept that a brand rename means reindexing that brand's products.
How Search Works: The Inverted Index
But what is actually happening under the hood? For each text or keyword field, Lucene builds an inverted index: a sorted dictionary of every term, and for each term a postings list of the document IDs that contain it, often with term frequencies and positions.
term postings (doc ids)
----- ------------------
blue [2, 7, 19, 40, 41]
run [7, 8, 19, 33]
shoe [3, 7, 19, 22, 40]
The query blue running shoes is analyzed to blue, run, shoe. Lucene looks each term up in the dictionary (a compact finite-state structure that mostly fits in memory), then walks the three postings lists in parallel. Documents 7 and 19 contain all three. Because postings lists are sorted and compressed, and Lucene can skip ahead in them, intersecting lists with millions of entries takes milliseconds.
Compare that with WHERE title LIKE '%shoe%' in Postgres. A leading wildcard can't use a B-tree index, so the database scans every row. Even with Postgres's own full-text search (a tsvector column with a GIN index, which is also an inverted index), you get matching but limited relevance tuning, and the work runs on your primary database's CPU.
Matching is only half the job. Elasticsearch also scores each match, by default with BM25: a document scores higher when the query terms appear often in it (term frequency, with diminishing returns), when those terms are rare across the index (inverse document frequency), and when the field is short. A product titled "Blue Running Shoe" beats a 2,000-word review that mentions "blue" once.
Inverted indexes aren't the only structure in a shard. Lucene also keeps:
- Doc values: a column-oriented copy of each
keyword, numeric and date field, on disk. Sorting by price or computing "count per brand" reads one column for the matching documents instead of parsing JSON. This is what makes aggregations fast. - BKD trees: a tree for numeric, date and geo fields, so range queries (
price between 50 and 100) and bounding-box queries don't scan. - Stored
_source: the original JSON, compressed, fetched only for the documents you actually return. - HNSW graphs for
dense_vectorfields, used for approximate k-nearest-neighbor vector search.
Segments: Why Writes Are Different
A Lucene index is made of segments, and segments are immutable. Each segment is a complete mini-index with its own dictionary, postings and doc values. New documents are buffered in memory and periodically written out as a new segment. A search queries every segment in the shard and merges the results.
Immutability has consequences you should be able to explain:
- Updates are delete + insert. Changing one field of a document marks the old copy as deleted (a bit in a per-segment bitmap) and indexes a whole new copy. Elasticsearch has an update API, but it's a convenience: it fetches
_source, applies your change and reindexes the full document. - Deletes are tombstones. Deleted documents still occupy space and are filtered out at search time until a merge removes them.
- Background merges combine small segments into larger ones, dropping deleted documents. Merging is I/O-heavy, and an index with a high update rate spends real disk bandwidth on it.
That's why Elasticsearch is great for data that's mostly appended (logs, events, catalogs that change a few times a day) and a poor fit for a counter that's incremented 1,000 times a second. Every increment would reindex the whole document.
Architecture
An Elasticsearch cluster is a set of nodes (JVM processes, usually one per machine). Each node takes one or more roles.
- Master-eligible nodes manage the cluster state: which indices exist, their mappings, and which shard lives on which node. One is elected master. Production clusters run three dedicated master-eligible nodes so the cluster tolerates one failure while keeping a majority.
- Data nodes hold shards and do the heavy lifting: indexing, searching and aggregating. In larger clusters they're split into tiers (hot, warm, cold) on different hardware.
- Ingest nodes run pipelines that transform documents before indexing (parse a log line, enrich with a GeoIP lookup).
- Coordinating is something every node does: whichever node receives a request routes it to the right shards and merges the results. Big clusters sometimes add coordinating-only nodes so heavy result merging doesn't land on data nodes.
Shards and Replicas
An index is split into primary shards when it's created. Each document is assigned to one shard by its routing value, which is its _id unless you specify otherwise:
shard = hash(_routing) % number_of_primary_shards
Each primary has zero or more replica shards, full copies placed on different nodes from the primary. Replicas serve two purposes: if a node dies, a replica is promoted to primary, and searches can run on any copy, so more replicas means more read throughput.
Because the formula uses the primary shard count, you can't change the number of primary shards of an existing index without rewriting it. There are split and shrink APIs that multiply or divide the count by a whole factor, and a reindex API that copies everything into a new index, but none of these are instant. You can change the number of replicas at any time.
Picking shard counts is the kind of thing interviewers probe on. A common guideline is to keep shards somewhere in the range of roughly 10 to 50 GB each. Too few shards and one shard becomes too large to move or recover quickly. Too many and each search fans out to hundreds of tiny shards, and the master spends its time tracking them. For a 600 GB catalog, 12 to 20 primaries is a reasonable starting point.
The Write Path
Here's what happens when you index a document:
- The client sends
PUT /products/_doc/123to any node. That node becomes the coordinating node. - It computes the shard from the routing value and forwards the request to the node holding that shard's primary.
- The primary validates the document against the mapping, adds it to an in-memory indexing buffer, and appends the operation to the shard's translog (a write-ahead log on disk).
- The primary forwards the operation to all in-sync replicas, which do the same.
- Once the replicas acknowledge, the primary acknowledges to the coordinating node, which responds to the client.
At this point the document is durable (it's in the translog on every in-sync copy, fsynced by default before acknowledging), and it's readable by ID: a GET /products/_doc/123 checks the translog. But it isn't searchable yet, because it's still in the buffer, not in a segment. Two background operations finish the job:
- Refresh (every 1 second by default, on shards that have received a search recently): turns the in-memory buffer into a new searchable segment in the filesystem cache. This is why Elasticsearch is called near real-time. You can raise
refresh_intervalto 30 seconds or disable it during a bulk load to index much faster, at the cost of freshness. - Flush: runs a Lucene commit, fsyncing segments to disk, and trims the translog. If a node crashes, it recovers by loading the last commit and replaying the translog.
For throughput, use the bulk API. Sending 1,000 documents in one request amortizes the network round trip and per-request overhead, and indexing tens of thousands of documents per second per node is routine with bulk requests and a relaxed refresh interval.
If a requirement says "a user must see their own post in search results immediately," don't promise it from Elasticsearch's default refresh. Options: pass
refresh=wait_foron that write (the request waits until the next refresh makes it visible, which adds up to a second of latency), or show the user's own new content from the primary database and merge it into the results client-side. Forcing a refresh on every write (refresh=true) creates tiny segments and hurts the whole cluster.
The Query Path
A search goes to every shard in the index (one copy each, primary or replica), in two phases:
- Query phase: The coordinating node sends the query to one copy of every shard. Each shard finds its matching documents, scores them, and returns just the IDs and scores of its top
from + sizehits. - Fetch phase: The coordinating node merges those lists into a global top
size, then asks only the shards that own the winners for their_source.
A typical product-search query mixes full-text matching with filters:
GET /products/_search
{
"query": {
"bool": {
"must": [
{ "multi_match": { "query": "blue running shoes",
"fields": ["title^3", "description"] } }
],
"filter": [
{ "term": { "in_stock": true } },
{ "range": { "price_cents": { "lte": 10000 } } },
{ "terms": { "brand": ["nike", "adidas"] } }
]
}
},
"aggs": {
"by_brand": { "terms": { "field": "brand", "size": 20 } },
"price_ranges": { "range": { "field": "price_cents",
"ranges": [{ "to": 5000 }, { "from": 5000, "to": 10000 }, { "from": 10000 }] } }
},
"sort": ["_score", { "rating": "desc" }],
"size": 20
}
The bool query separates query context (must, should: affects the score) from filter context (filter, must_not: yes or no, no scoring). Filters are cheaper, and Elasticsearch caches frequently used filter results as bitsets, so put every clause that doesn't need relevance (stock status, price, brand) in filter. The title^3 boost makes a match in the title count three times as much as one in the description.
The aggs block computes the facet counts you see in a sidebar ("Nike (412), Adidas (380)") over all matching documents, in the same request, using doc values.
Pagination and Its Limits
Because every shard must return its top from + size hits, deep pages get expensive. Page 500 with 20 results per page means every shard returns 10,000 candidates and the coordinator sorts them all. By default Elasticsearch refuses from + size beyond 10,000 (index.max_result_window).
- For user-facing paging, cap the depth. No one reads page 500 of search results.
- For "infinite scroll" or exporting everything, use
search_afterwith a sort key and a tiebreaker (the last result's sort values become the cursor), ideally with a point in time (PIT) so the results don't shift while you page.
Accuracy of Distributed Aggregations
Some aggregations are approximate by design, and it's worth knowing which:
- A
termsaggregation asks each shard for its own top N (actually a bit more,shard_size) and merges them. A brand that's 21st on every shard but 15th overall can be missed, and counts can be slightly low. The response reports an error bound. cardinality(count distinct) uses HyperLogLog++, so it's an estimate with a small error, not an exact count. Exact distinct counts over billions of values would need enormous memory.- Percentiles use sketches (TDigest), which are approximate but accurate at the tails.
For search facets, this is fine. For billing or financial reporting, compute exact numbers in a database or warehouse.
Scaling
Scaling Reads
Each search runs on one copy of every shard, so adding replicas (and nodes to hold them) increases how many searches per second the cluster can serve. Going from 1 to 2 replicas gives each shard three copies and roughly 1.5x the read capacity, if you add the hardware. Replicas also cost disk and indexing work, since every copy indexes every document itself.
Latency is dominated by the slowest shard in the fan-out. Common levers:
- Keep the working set in memory. Elasticsearch relies heavily on the OS filesystem cache. The usual advice is to give the JVM heap about half of RAM (and no more than roughly 30 GB, so compressed object pointers stay on) and leave the rest to the OS for caching segments.
- Custom routing to avoid fan-out. In a multi-tenant system, routing by
tenant_idputs each tenant's documents on one shard, so a tenant's search hits one shard instead of all of them. The risk is a giant tenant creating a hot shard. - Cache at the application layer for popular queries. Elasticsearch has a shard-level request cache for aggregation-heavy queries, but a Redis cache in front of the top few thousand queries is often simpler.
Scaling Writes
Writes scale with the number of primary shards and the nodes they're spread over. Each primary indexes independently, so 20 primaries on 10 nodes can absorb roughly 10x the write rate of 2 primaries on 1 node. Bulk requests, a longer refresh interval, and fewer replicas during an initial load all help.
Time-Based Indices
For append-only data like logs, metrics and events, you don't put everything in one index. You write to a new index per day (or per size threshold) behind an alias:
logs-2026.11.29receives today's writes. Searches over "last 7 days" hit only seven indices.- Rollover creates a new index when the current one reaches a size or age, so shard sizes stay healthy even when traffic changes.
- Index Lifecycle Management (ILM) moves older indices to cheaper warm and cold nodes, shrinks or force-merges them, and finally deletes them. Deleting a whole index is instant, while deleting millions of documents from a big index is expensive.
This is the standard pattern behind the "ELK" logging stack (Elasticsearch, Logstash and Kibana), and it's a good thing to describe if you're designing a logging or metrics system that needs full-text search over recent data.
Reindexing Without Downtime
Because mappings and primary shard counts are fixed, changing an analyzer or adding a sub-field to existing data means building a new index. The pattern: create products_v2 with the new mapping, backfill it from the source of truth while dual-writing new changes, then atomically switch the products alias from v1 to v2. Applications only ever query the alias. Mention aliases whenever you put Elasticsearch in a design; it's the answer to "what happens when you need to change the schema?"
Consistency and Fault Tolerance
Cluster Coordination
The elected master owns the cluster state, and changes to it require a quorum of master-eligible nodes. Since version 7, Elasticsearch manages the voting configuration itself, which removed the old misconfiguration (a manually set minimum_master_nodes) that caused split-brain clusters in earlier versions. With three master-eligible nodes, losing one is fine. Losing two stops the cluster from accepting changes.
When a data node fails, the master promotes an in-sync replica of each affected shard to primary and starts building new replicas elsewhere. The master tracks which copies are in-sync (they've received every acknowledged write), and only those can be promoted, so acknowledged writes aren't lost to a stale replica being promoted. Recovery of a replica copies segments from the primary and replays recent operations, which for a 50 GB shard can take minutes, which is another reason not to make shards huge.
What You Don't Get
- No multi-document transactions. Each document write is atomic on its own. There's no way to update a product and its inventory document together.
- Optimistic concurrency only. Each document has a
_seq_noand_primary_term. You can make a write conditional (if_seq_no=42&if_primary_term=3) so it fails if someone else changed the document first, or use external versioning (version_type=external) so an out-of-order update with a lower version is rejected. That second form is useful when syncing from a database: pass the row's version, and Elasticsearch ignores stale updates. - Searches are eventually consistent. Different replicas may refresh at slightly different moments, so two identical searches in a row can return slightly different results. A
preferenceparameter (for example, the user's session ID) keeps a user on the same copies so results don't flicker.
Keeping Elasticsearch in Sync with the Source of Truth
Because of those limits, the standard architecture keeps your data in a primary database (Postgres, MySQL, DynamoDB) and treats Elasticsearch as a derived, rebuildable index. The question becomes how to keep the two in sync.
- Dual writes from the application (write to the database, then to Elasticsearch) are simple but fragile. If the second write fails or the process crashes between them, the two diverge, and nothing notices.
- Change data capture (CDC) reads the database's replication log (Postgres's WAL, MySQL's binlog, DynamoDB Streams) with a tool like Debezium, publishes changes to Kafka, and an indexer consumes them and bulk-writes to Elasticsearch. Every committed change gets indexed eventually, in order per key, and the indexer can be replayed from Kafka after a bug. Use the row's version or the log position as an external version so retries and replays are harmless. See change data capture for the details.
- Periodic full rebuilds from a snapshot of the database catch any drift and let you change mappings. Because it's a derived store, you can always rebuild it, which is the main reason to keep it derived.
End-to-end lag with CDC is usually a second or a few, dominated by the refresh interval and the indexer's batching. That's what you'd quote if asked "how fresh is search?"
Saying "Elasticsearch is our secondary index, fed by CDC from Postgres, and we can rebuild it from scratch" answers three follow-ups at once: where the truth lives, how they stay consistent, and how you recover from corruption or a mapping change.
Notable Features
- Autocomplete: The completion suggester keeps an in-memory finite-state structure for prefix lookups with very low latency.
search_as_you_typefields and edge n-gram analyzers (indexsho,shoe,shoesas terms) handle prefix matching inside normal queries. For a large-scale typeahead with popularity ranking, many designs precompute suggestions instead; see typeahead. - Fuzzy matching:
fuzziness: "AUTO"matches terms within an edit distance of 1 or 2, so "runnign" still finds "running." - Geo queries:
geo_distance, bounding-box and polygon queries ongeo_pointandgeo_shapefields, combined with text and filters in one query ("open coffee shops within 2 km, sorted by rating"). - Vector search:
dense_vectorfields with HNSW indexes support approximate kNN search, and you can combine it with keyword search (hybrid search) in one request. - Percolator: inverts search. You index queries, then ask which stored queries match a new document. It's a neat fit for alerting ("notify me when a listing under $500 in Seattle appears").
- OpenSearch: an Apache-licensed fork of Elasticsearch maintained by AWS and others. The concepts here apply to both, and in an interview you can treat them as the same thing.
Here's how Elasticsearch compares with the alternatives you're likely to weigh:
Postgres full-text (tsvector + GIN) |
Elasticsearch / OpenSearch | |
|---|---|---|
| Best for | Search over a modest dataset already in Postgres | Search as a major feature, at large scale |
| Relevance tuning | Basic ranking functions | BM25, boosts, synonyms, function scores, learning-to-rank plugins |
| Freshness | Transactional: visible on commit | Near real-time (about 1 s refresh) |
| Consistency with data | Same database, same transaction | Separate system kept in sync by CDC |
| Scaling | Bound to the primary's resources | Horizontal via shards and replicas |
| Facets and analytics | GROUP BY queries, slower at scale |
Aggregations over doc values, fast |
| Operational cost | Nothing new to run | A whole cluster to size, tune and monitor |
Elasticsearch in an Interview
When to Use It
- Full-text search with relevance ranking. Product search, post search, document search, job search. Anything where users type words and expect the best matches first.
- Search with many optional filters and facets. E-commerce category pages filter on a dozen attributes at once, in any combination. A relational database would need an index for every combination; Elasticsearch indexes every field and intersects them.
- Log and event search. Time-based indices with ILM make "search the last 7 days of logs for this request ID" fast and keep storage under control.
- Geo plus text. Proximity search with text and ratings in one query, when you also need relevance ranking. (For pure "nearest drivers" lookups, a geospatial index in Redis or Postgres is simpler.)
When you add it, say three things: it's a secondary index, it's fed by CDC through Kafka, and it's eventually consistent with roughly second-level lag.
Knowing Its Limitations
- It's not your database. No transactions, eventually consistent search, and a long history of clusters losing or diverging data under misconfiguration. Keep the source of truth elsewhere.
- Updates are expensive. Every update rewrites the whole document and creates merge work. High-frequency counters (view counts, likes) don't belong in documents you update on every event. Batch them, or update the search document every few minutes.
- Freshness is bounded by refresh. Read-your-own-writes in search needs extra work.
- Fan-out cost. Every search touches every shard of the indices involved. Too many shards, or one slow node, drags down every query.
- Deep pagination and exact analytics are weak spots. Cap paging, use
search_after, and send exact reporting to a warehouse. - Operational weight. JVM heap tuning, shard sizing, mapping changes and upgrades are real work. A managed service (Elastic Cloud, Amazon OpenSearch Service) removes some of it but not the design decisions.
Questions You Might Get
- "Why not just use
LIKEqueries in Postgres?" A leading wildcard scans every row, there's no relevance ranking, and no stemming or synonyms. An inverted index turns the query into a few postings-list intersections. - "How does a new product become searchable?" It's committed to the database, captured by CDC into Kafka, bulk-indexed by a consumer, and becomes visible after the next refresh, usually within a few seconds.
- "How do you change the mapping on a live index?" Create a new index, backfill and dual-write, then swap the alias.
- "How would you scale search QPS by 5x?" Add replicas and nodes for read capacity, cache hot queries, and make sure shards are sized so no single one is the bottleneck. If writes also grow, you need more primaries, which means a reindex into a new index.
- "What happens when a data node dies?" The master promotes in-sync replicas to primaries, the cluster goes yellow while new replicas are built on other nodes, and searches keep working off the remaining copies.
Summary
Elasticsearch is a distributed layer over Lucene that turns JSON documents into inverted indexes, doc values and BKD trees, split across primary and replica shards. Mappings and analyzers decide what matches. Writes go to the primary, get logged and replicated, and become searchable after a refresh about a second later. Searches scatter to every shard, gather the top hits and fetch the winners, with filters and aggregations running over columnar doc values.
In an interview, bring it in whenever users search with words or many filters, and always pair it with a source of truth and a CDC pipeline that keeps it in sync. Know its weak spots (updates, freshness, transactions, deep paging), size shards sensibly, and put an alias in front so you can reindex without downtime.