Skip to content

Elasticsearch and Search Systems

Intermediate 50 min read Part 15 of 18

Elasticsearch in practice: inverted index, analyzers, BM25, shards and replicas, near-real-time refresh, queries and aggregations, CDC sync, pitfalls.

Summary#

Elasticsearch is a distributed search and analytics engine built on Apache Lucene. You send it JSON documents. It runs their text through analyzers (tokenising, lowercasing, stemming) and builds an inverted index, a map from every term to the documents containing it. A query like "taylor swift tickets" then finds matching documents in milliseconds, without scanning anything.

Results are ranked by relevance, using BM25 (a refinement of TF-IDF). Search also combines with:

  • structured filters (price under 50, date in December);
  • aggregations (facet counts, histograms, percentiles);
  • geo queries (within 5 km);
  • vector search.

An index is split into primary shards (each one a Lucene index), spread across data nodes, each with replica copies for availability and read throughput. Writes become searchable after a refresh, every 1 second by default, which makes Elasticsearch near-real-time, not immediately consistent.

In system design, Elasticsearch almost always plays one role: a secondary, derived read model. The source of truth is a database such as PostgreSQL or DynamoDB, and change data capture streams its changes into Elasticsearch. It's not your primary store: it has no multi-document transactions, writes are eventually visible, and rebuilds come from the source.

This page covers:

  • the data model and mappings;
  • analyzers and the inverted index;
  • relevance scoring with the maths;
  • cluster architecture and the write and read paths;
  • refresh, flush and merges;
  • the query DSL (full-text, filters, aggregations, geo, sorting, pagination);
  • syncing from the database;
  • why it's not a primary store;
  • scaling pitfalls (deep pagination, mapping explosion, oversharding, hot shards);
  • when to use Elasticsearch, OpenSearch, Postgres full-text search, or something else.

Why It Exists#

Most applications eventually need search: find the events, products, posts, logs or businesses matching what a user typed. Ideally the search is typo-tolerant, ranked by relevance, filterable, sortable, faceted and fast.

A relational database struggles with this. Take SELECT * FROM events WHERE name LIKE '%Taylor%' OR description LIKE '%Taylor%':

  • A leading wildcard can't use a B-tree index, so it scans the whole table: seconds at 10 million rows.
  • It has no notion of relevance (which match is best?).
  • It doesn't handle word forms ("concerts" vs "concert"), typos ("Tayler"), synonyms or multiple languages.
  • Every search competes with transactional traffic on the primary.

Ordinary index tuning (indexing name, date and venue, rewriting OR as UNION, avoiding SELECT *) helps exact and prefix lookups, but not "contains this word anywhere".

There are two tiers of answers:

  1. Full-text indexes in the database. PostgreSQL's tsvector with GIN indexes, or MySQL's FULLTEXT, turn word search into an index lookup. Neither uses Lucene. For many products, with up to roughly a few million documents, moderate query rates and basic ranking, this is enough, with no extra system to sync. The costs are extra storage, slower writes, a less flexible query language, and limited relevance tuning.
  2. A dedicated search engine. When you need serious relevance (BM25, field boosts, function scoring), fuzzy matching, autocomplete, facets over millions of documents, geo plus text plus filters in one query, very high query throughput, or horizontal scale to billions of documents, you add a search engine.

Lucene, created by Doug Cutting in 1999, became the standard open-source search library. Elasticsearch, released by Shay Banon in 2010, wrapped Lucene in a distributed system: a JSON REST API, automatic sharding and replication, cluster management, and aggregations. It became the default search engine for applications, and with Logstash and Kibana (the "ELK stack") for log analytics.

After Elastic changed its licence in 2021, AWS forked Elasticsearch 7.10 as OpenSearch. The two remain largely compatible at the concept and API level. Elastic later added an AGPL option (2024). Everything on this page applies to both, unless noted.

Common uses of Elasticsearch:

  • application search: e-commerce, marketplaces, events, documentation;
  • log and event analytics: observability, with ELK or OpenSearch Dashboards;
  • security analytics (SIEM);
  • metrics and APM (application performance monitoring);
  • geo search: "restaurants near me";
  • autocomplete and suggestions;
  • increasingly, vector and hybrid semantic search.

How It Works#

We'll build the picture in layers. First the data model (documents, indices and mappings). Then what happens to text on the way in (analysis) and the structure it lands in (the inverted index). Then how results are ranked (BM25), how the cluster spreads data across machines (shards and replicas), and how writes become searchable (refresh, translog, segments and merges). Queries, aggregations, pagination and syncing come in the sections after.

Documents, indices and mappings#

A document is a JSON object, the unit you index and get back. Think of one product, one event listing or one log line. Every document has an _id, unique within its index. You can supply the id yourself (best when the document mirrors a database row, because you then use the row's primary key) or let Elasticsearch generate one.

{
  "id": "evt_8812",
  "title": "Taylor Swift | The Eras Tour",
  "venue": { "name": "Wembley Stadium", "city": "London" },
  "location": { "lat": 51.556, "lon": -0.2796 },
  "starts_at": "2026-06-21T19:00:00Z",
  "price_min": 89.0,
  "genres": ["pop"],
  "tickets_left": 1520
}

An index is a named collection of documents that share a shape, such as events or logs-2026.12.02. Conceptually it's closer to a database table than to a B-tree "index". Physically it's split into shards, which we come to shortly.

A mapping is the index's schema. It declares each field's type, and that type decides which data structures Elasticsearch builds for the field. The key types are:

TypeBuilt structuresUse for
textanalysed inverted index (tokens, positions, norms)prose you search by words: titles, descriptions, bodies
keywordun-analysed inverted index + doc valuesexact values: ids, tags, status, emails, for filters, sorts and aggregations
long, integer, double, dateBKD tree (points) + doc valuesranges, sorting, histograms
booleaninverted index + doc valuesflags
geo_point / geo_shapeBKD tree on encoded coordinates / shapesdistance, bounding box, polygon queries
nestedeach array object stored as a hidden separate documentarrays of objects queried with "same element" semantics
dense_vectorHNSW graph (Lucene 9+)k-nearest-neighbour semantic search
flattenedone field holding all leaf values as keywordsarbitrary key-value bags without mapping explosion

The text vs keyword distinction is the most important mapping decision. A text field is broken into words, so "Taylor Swift | The Eras Tour" becomes the searchable words taylor, swift, eras and tour. A keyword field is stored as the whole exact string, so it can match status = "ON_SALE" exactly and be sorted and aggregated. You often want both. A multi-field indexes the same source value twice: title as text for search, and title.keyword as keyword for sorting and exact matching.

Dynamic mapping lets Elasticsearch guess types the first time it sees a new field. A string becomes text with a .keyword sub-field, a number becomes long or float, and an ISO string becomes date. It's convenient in development and dangerous in production. A guess can be wrong (a zip code becomes long, losing its leading zeros), and every new key becomes a permanent field. That leads to the mapping explosion covered later. Production indices should declare mappings explicitly, and usually set "dynamic": "strict" (reject unknown fields) or false (store them in _source but don't index them).

Every mapped field costs memory and disk, even if no query ever uses it. It adds terms to the dictionary, structures to every segment, and entries to the cluster state. So you map what you search, filter, sort or aggregate on, and leave the rest unindexed ("index": false, or "enabled": false for an object). The rest still comes back in _source.

Modelling relationships: nested, denormalised or separate

Elasticsearch has no joins worth relying on. So the modelling question is where related data lives. Take events with reviews:

  • Denormalise into the parent. Copy the venue's name and city into each event document. Reads need one query. The cost is that a venue rename must re-index every event at that venue. That's acceptable when the copied data changes rarely.
  • nested objects. Store reviews as a nested array, so a query like "reviews where rating ≥ 4 AND author = 'sam'" matches within the same review. A plain object array would flatten the fields and match across different reviews. Each nested object is a hidden Lucene document stored next to its parent. Queries are fast, but updating any review re-indexes the whole parent and all its nested children. Use nested only for bounded, slowly changing child lists. Indices default to a limit of 10,000 nested objects per document.
  • A separate index. Reviews get their own index with an event_id field. Searching events and reviews becomes two queries, joined in the application. Use this when children are numerous, change often, or are queried independently.
  • join field (parent-child). Parent and child live in the same shard, linked by routing. It avoids re-indexing parents, but queries are much slower. It's a niche tool.

The rule of thumb: design documents around the queries. Most search use cases are best served by one denormalised document per thing users search for, built from several database tables at index time.

Analysis: from text to terms#

When a text field is indexed, its value passes through an analyzer, a three-stage pipeline:

  1. Character filters clean the raw string before it's split, for example by stripping HTML tags or mapping "&" to "and".
  2. A tokenizer splits the string into tokens. The standard tokenizer follows the Unicode text-segmentation rules, so "Wembley-Stadium's" becomes Wembley, Stadium's. Others split on whitespace, produce character n-grams, or handle Chinese, Japanese and Korean (CJK) scripts, which have no spaces between words.
  3. Token filters transform the token stream:
    • lowercase: so "Taylor" matches "taylor";
    • asciifolding: "café" becomes "cafe";
    • stop words: remove "the", "a" and "of";
    • stemming: "running" becomes "run" (Porter or Snowball stemmers, per language);
    • synonyms: "nyc" also indexes "new york";
    • edge n-grams: "swift" becomes s, sw, swi, swif, swift, for search-as-you-type.

The same analysis must happen at query time. A search for "Running Shoes" is analysed into run and shoe, and then looked up. If indexing stemmed but searching didn't, "running" would never match "run". Elasticsearch applies the field's analyzer to match queries automatically. You can set a separate search_analyzer for asymmetric cases, for example edge n-grams at index time but not at query time, so a query for "swi" doesn't also expand into s and sw.

The _analyze API shows exactly which tokens a string becomes. It's the first tool to reach for when "why doesn't this match?" comes up.

POST _analyze
{ "analyzer": "english", "text": "The Running Shoes" }
// tokens: ["run", "shoe"]   ("the" removed as a stop word, both stemmed)

Analyzer changes need a re-index. The tokens are baked into the index, so you can't change how existing documents were analysed. You create a new index with the new analyzer and re-index into it, swapping an alias (see the CDC section).

The inverted index and Lucene's data structures#

The analysed tokens become terms in an inverted index, a map from each term to the list of documents containing it. That list is called the postings list. It's the same idea as the index at the back of a book, and it's covered conceptually in Database Indexing. Here's what Lucene actually builds:

Per field, per segment (an immutable mini-index; more below), Lucene stores:

  • Term dictionary. All distinct terms, sorted, in blocks on disk. In memory sits a finite state transducer (FST), a compact automaton that shares prefixes and suffixes between terms. It maps a term prefix to the on-disk block that holds it. It's what makes term lookup fast without loading the whole dictionary. It also lets prefix, fuzzy and regex queries walk only the matching part of the term space.
  • Postings lists. For each term, the sorted doc IDs that contain it. They're stored as deltas (gaps between consecutive IDs, which are small numbers) and bit-packed in blocks of 128 using frame-of-reference encoding. So a list of millions of IDs costs about 1–2 bytes per entry, and it decodes with SIMD-friendly loops. Skip data lets an intersection jump ahead, from doc 1,000 to doc 1,000,000, without decoding everything in between. That's essential when you AND a common term with a rare one.
  • Term frequencies and positions. How often the term appears in each doc (for scoring) and where (for phrase and proximity queries, "eras tour"). Offsets are optional and support highlighting.
  • Norms. One byte per document per field, encoding field length for scoring. A match in a 3-word title counts more than one in a 300-word body.
  • Doc values. A column-oriented, on-disk store per field: document → value. The inverted index answers "which docs contain X?". Doc values answer the opposite question, "what is the value of field F for doc 17?". Sorting, aggregations and scripts need that. Doc values are on by default for keyword, numeric, date and geo fields, and they're served from the OS page cache. (Before doc values became the default in ES 2.0, this was done with heap-resident "fielddata", a frequent cause of out-of-memory errors. Fielddata still exists for text fields and should stay off.)
  • Points (BKD trees). Numbers, dates and geo points are indexed in a block k-d tree, added in Lucene 6. It's a balanced tree that recursively splits the value space, so range and bounding-box queries visit only the cells that overlap the query. That replaced the older approach of indexing numbers as many prefix terms.
  • Stored fields (_source). The original JSON is compressed in blocks with LZ4 (default) or DEFLATE (best_compression). The fetch phase reads it and returns it to you. It's separate from everything above: searching never reads _source, only showing results does.
  • Vectors. dense_vector fields build an HNSW graph per segment for approximate nearest-neighbour search (Lucene 9+), so text, filters and vectors can be combined in one engine.

Because each structure is specialised, Elasticsearch can answer "full-text match AND price range AND within 5 km, sorted by date, with a genre histogram" in tens of milliseconds over hundreds of millions of documents. Each part of that query uses the structure built for it.

Relevance: from TF-IDF to BM25#

A database returns rows that match. A search engine returns them ranked by how relevant they are. The classic intuition has three parts:

  1. Term frequency (TF): a document that mentions "swift" five times is more likely to be about Swift than one that mentions it once.
  2. Inverse document frequency (IDF): a match on a rare term ("eras") tells you more than a match on a common one ("tour"). Karen Spärck Jones introduced this idea, term specificity, in 1972.
  3. Field-length normalisation: a match in a short field is more significant than in a long one.

TF-IDF multiplies TF by IDF, and Lucene's classic similarity used a version of it. Its weakness is that TF grows without bound: a page that repeats "swift" 100 times scores far above one that says it 5 times, which rewards keyword stuffing. BM25 ("Best Matching 25") comes from Stephen Robertson and colleagues' probabilistic relevance framework (Okapi, 1990s), summarised in Robertson and Zaragoza, "The Probabilistic Relevance Framework: BM25 and Beyond" (2009). It saturates TF and normalises length more carefully. It has been Elasticsearch's default similarity since version 5.0.

For a query term t and document d:

score(t, d) = IDF(t) * ( tf * (k1 + 1) ) / ( tf + k1 * (1 - b + b * len(d) / avg_len) )
 
IDF(t)  = ln( 1 + (N - n + 0.5) / (n + 0.5) )   N = docs in shard, n = docs containing t
k1 = 1.2  (how fast TF saturates)     b = 0.75  (how strongly length normalises)
score(query, d) = sum of score(t, d) over the query terms  (times boosts)

Worked example. Take a shard of N = 1,000,000 event documents. "taylor" appears in n = 2,000 of them and "tour" in n = 200,000.

  • IDF(taylor) = ln(1 + 999,998.5 / 2,000.5) ≈ ln(500.9) ≈ 6.22.
  • IDF(tour) = ln(1 + 800,000.5 / 200,000.5) ≈ ln(5.0) ≈ 1.61.

So "taylor" is worth almost four times as much as "tour". Now take a title of average length (len = avg_len, so the length factor is 1) with tf = 1. The TF part is 1 × 2.2 / (1 + 1.2) = 1.0. With tf = 3 it's 3 × 2.2 / (3 + 1.2) = 1.57, and with tf = 10 it's 10 × 2.2 / 11.2 = 1.96. That's the saturation: the curve flattens toward k1 + 1 = 2.2, so repeating a word ten times buys less than double the credit of saying it once. A title half the average length with tf = 1 gets 2.2 / (1 + 1.2 × 0.625) = 1.26, because shorter fields score higher.

Practical relevance tuning happens above BM25:

  • Field boosts. title^3 weighs title matches three times as much as description matches.
  • multi_match across fields, with best_fields (take the best field's score), most_fields (sum them) or cross_fields (treat the fields as one big field, good for names split across first and last).
  • function_score mixes in business signals, such as popularity, recency decay (gauss on starts_at), distance decay, or "in stock". This is how "relevance" becomes "useful". A perfect text match for a sold-out event from 2019 shouldn't be first.
  • Rescoring. Run a cheap query over all docs, then an expensive one (phrase proximity, a learning-to-rank model) on the top few hundred per shard.

IDF is computed per shard by default. The default search type, query_then_fetch, scores each shard with its own N and n. With many shards and few documents, a term that is rare overall but happens to cluster in one shard gets inconsistent scores. That shows up in small test indices as "why does the same document score differently?". dfs_query_then_fetch adds a round trip that first collects global term statistics. It's more accurate and slower, and it's rarely needed at production scale, where random routing makes per-shard statistics converge.

The cluster: nodes, shards and replicas#

Elasticsearch is a distributed system that orchestrates many Lucene indexes. A cluster is a set of nodes (JVM processes, usually one per machine or container). Each node takes one or more roles:

  • Master-eligible nodes maintain the cluster state: which indices exist, their mappings and settings, and which shard copies live on which node. One of them is elected the active master. Production clusters run three dedicated master-eligible nodes (small machines), so a majority survives one failure, and data-node load never starves the master.
  • Data nodes hold shards and do the indexing and search work. With data tiers, they're split into hot (fast SSDs, recent data, all writes), warm (older, read-mostly data on cheaper disks), cold (rarely queried, possibly backed by snapshots) and frozen (searchable snapshots in object storage, fetched on demand).
  • Coordinating nodes take client requests, fan them out to the shards, and merge the results. Every node can coordinate. Large clusters sometimes add dedicated "coordinating-only" nodes to absorb heavy aggregation merges.
  • Ingest nodes run pre-processing pipelines before indexing (grok parsing, enrichment, date parsing).
  • ML and transform nodes run machine-learning jobs and transforms (X-Pack features).

When a node starts, it contacts the configured seed hosts to discover the cluster. The master-eligible nodes elect a master using a quorum-based coordination protocol. Since 7.0 it's a Raft-like algorithm that Elastic designed and formally modelled. It replaced the older "Zen" discovery and its error-prone minimum_master_nodes setting.

An index is split into primary shards. Each primary is a complete, independent Lucene index holding a subset of the documents. Each primary has zero or more replica shards, full copies kept on different nodes. The hierarchy, top to bottom, is:

  • index (logical)
  • shards (primaries and replicas, spread across nodes)
  • one Lucene index per shard copy
  • many immutable segments per Lucene index

Routing. A document's shard is chosen by shard = hash(_routing) % number_of_primary_shards. _routing defaults to the _id, and the hash is Murmur3. That's why the number of primary shards is fixed when you create the index: change it, and every document's computed shard changes. You can multiply or divide the count with the _split and _shrink APIs (they rewrite the index with hard links), or re-index into a new index. A custom routing key (for example tenant_id) puts all of one tenant's documents on one shard. A query that passes the routing value then hits one shard instead of all of them. The price is skew, because a giant tenant becomes a hot shard. routing_partition_size spreads each routing key over a few shards as a compromise.

Replicas do two jobs.

  1. Availability. If a node dies, the master promotes a replica of each lost primary to primary, and allocates new replicas elsewhere to restore the copy count. The health colours report this. Green means all copies are allocated. Yellow means all primaries are allocated but some replicas aren't, so the data is all there with reduced redundancy. Red means at least one primary is unassigned, so part of the data can't be searched or written.
  2. Read throughput. A search needs only one copy of each shard, so replicas multiply read capacity. With 3 primaries and 2 replicas there are 9 shard copies. Spread over 9 nodes, three searches can be served fully in parallel. Replicas don't help write throughput: every write goes to every copy.

Sizing rules of thumb, from Elastic's guidance:

  • Keep shards at 10–50 GB (up to about 200 M documents). Tiny shards waste per-shard overhead. Each one carries its own segments, file handles and heap structures, and the master tracks each one, so 10,000 shards of 100 MB is a classic cluster-state and heap disaster. Huge shards make recovery and relocation slow.
  • Give the JVM heap at most about 50% of RAM, and at most about 31 GB. Under about 32 GB the JVM can use compressed object pointers. Above it, pointers double in size, and a 40 GB heap can hold less than a 31 GB one. The other half of RAM is deliberately left to the OS page cache, which is where Lucene's segment files, doc values and postings are actually served from.
  • Use local SSD or NVMe. Network disks work, but they add latency to merges and to searches that miss the page cache.

Writes: from index request to searchable document#

Here's the write path for one document:

  1. The coordinating node hashes the routing value to find the primary shard and forwards the request there.
  2. The primary validates the document against the mapping and analyses it. It adds the result to an in-memory indexing buffer and appends the operation to the translog, a write-ahead log on disk.
  3. The primary sends the operation to all in-sync replicas in parallel, and each repeats the work.
  4. Once the replicas acknowledge, the client gets success. wait_for_active_shards controls how many copies must be available before the write starts. The default is 1, the primary. Note that it's a pre-check, not a quorum write: once the operation starts, it's sent to every in-sync copy. A replica that fails to apply it is removed from the in-sync set by the master.
  5. Each operation gets a sequence number (_seq_no) and the primary term (a counter that increments every time a new primary is elected for the shard). Together they order operations, and they let a recovering replica replay only what it missed.

Durability: the translog. By default (index.translog.durability: request), the translog is fsynced before a write is acknowledged. So an acked write survives a process crash, even though it's still only in the memory buffer. Setting async fsyncs every 5 seconds, trading up to 5 s of acked writes for throughput. That's usually only acceptable for re-playable data like logs.

Searchability: refresh. A document in the indexing buffer isn't searchable. Every refresh_interval (default 1 second), each shard performs a refresh. It writes the buffer into a new segment in the filesystem cache, not necessarily fsynced to disk, and opens it for search. That's why Elasticsearch is called near-real-time (NRT): a write is durable once acked, but visible to search only up to about 1 s later. GET by _id is real-time, because it reads from the translog or buffer when needed. Shards that receive no searches for 30 s go "search idle" and skip scheduled refreshes until the next search arrives, which saves work on write-heavy indices.

You can tune this:

  • Set refresh_interval: 30s (or -1 during a bulk load) to cut segment churn and raise indexing throughput dramatically.
  • Pass ?refresh=wait_for on a write to block the response until the next refresh makes the document visible. That's useful for "user creates item, then immediately sees it in their list", without forcing extra refreshes.
  • Avoid ?refresh=true, which forces an immediate refresh on every write and creates a tiny segment each time. That's a common cause of poor indexing performance.

Persistence: flush. Periodically, when the translog passes a size threshold (512 MB by default for many versions; recent releases set it higher), a flush performs a Lucene commit. It fsyncs all segments to disk, writes a commit point, and trims the translog. After a crash, the shard opens the last commit and replays the translog from there.

Segment merging. Each refresh produces a small segment, so a busy shard creates one per second. Searching 1,000 tiny segments is slow, because each query has to visit every segment. A background merge policy (TieredMergePolicy by default) continually merges similar-sized segments into bigger ones. While doing so, it physically drops deleted documents. Merges use I/O and CPU, and they're throttled so they don't starve searches. _forcemerge to one segment is useful only on indices that will never be written again, such as yesterday's logs. On live indices it creates huge segments that then can't merge efficiently.

Why segments are immutable, and what that implies. A segment is never modified after it's written, and that's the source of most of Lucene's strengths:

  • No locks for readers. Searches read a point-in-time set of segments while writes create new ones.
  • Caching works. OS page cache and filter caches stay valid for the segment's life.
  • Compression is aggressive, because nothing needs updating in place.
  • Recovery is simple: you copy files.

The cost shows up in deletes and updates:

  • A delete doesn't remove anything. It sets a bit in the segment's live-docs bitset, a tombstone. The document is still read, and then skipped, until a merge purges it.
  • An update (full or partial _update) is a delete plus a new insert. Elasticsearch reads the old _source, applies the change, re-analyses the whole document, writes it to a new segment, and marks the old copy deleted.

So updates cost more than inserts. An index whose documents change constantly accumulates deleted docs and merge pressure. That's why the classic advice holds: don't use Elasticsearch for rapidly mutating values such as live view counters or stock levels that change on every purchase. Keep those in a database or cache, and either update the search index in batches ("tickets_left" rounded, refreshed every minute) or join the live value at display time.

Reads: query then fetch#

A search runs in two phases across the shards:

  1. Query phase. The coordinator sends the query to one copy of every shard. Adaptive replica selection picks the copy with the best recent response time and queue depth. Each shard runs the query against all its segments, scores the matches, and keeps a priority queue of its top from + size hits. It returns only doc IDs, scores and sort values, plus partial aggregation results.
  2. Merge. The coordinator merges the per-shard lists into the global top size.
  3. Fetch phase. It asks only the shards that own the winning documents for their _source, plus highlights and any requested fields.

The response carries hits.total (exact up to 10,000 by default, then reported as "gte"), and per hit _index, _id, _score and _source. It also reports took in ms and timed_out, plus _shards counts (successful, failed). Partial results are possible. If a shard fails or times out, you still get the others' hits, flagged in _shards.failed. Check it.

Two consequences follow. Every search touches every shard of the index (unless routed), so the shard count multiplies per-query work: more shards means more parallelism per query, but also more fan-out overhead and tail-latency exposure. And deep pages are expensive, because each shard must find its top from + size hits, as the pagination section shows.

The coordinator plans the query using statistics. Lucene doesn't evaluate a boolean query naively. For "bill AND nye", it iterates the rarer term's postings (say "nye", in 3,000 docs) and uses skip lists to probe the common term's list ("bill", in 4 million docs) only at those IDs. That's a cost of about 3,000 probes rather than a 4-million-entry scan. Filters are cost-ordered the same way. Cached filter bitsets are reused across queries. Scoring algorithms like block-max WAND (Lucene 8+) skip whole blocks of documents that can't possibly enter the top-k, which is why track_total_hits: false can make top-10 queries several times faster.

Queries: full text, exact filters, geo and more#

Searches use the JSON Query DSL. The single most important concept is the split between query context and filter context.

  • Query context asks how well a document matches, and computes a _score. Use it for match on text.
  • Filter context asks only whether it matches, yes or no. There's no scoring, so it's cheaper. Frequently used filters are cached as bitsets per segment. Use it for status, dates, price ranges, tenants and anything exact.

A typical search for "taylor swift in London next month, under £150, most relevant first":

GET events/_search
{
  "query": {
    "bool": {
      "must":   [ { "multi_match": { "query": "taylor swift", "fields": ["title^3", "performers^2", "description"] } } ],
      "filter": [
        { "term":  { "venue.city": "London" } },
        { "range": { "starts_at": { "gte": "now", "lte": "now+30d/d" } } },
        { "range": { "price_min": { "lte": 150 } } }
      ],
      "should": [ { "match_phrase": { "title": { "query": "taylor swift", "boost": 2 } } } ]
    }
  },
  "sort": [ "_score", { "starts_at": "asc" } ],
  "size": 20
}

The bool query combines clauses:

  • must clauses must match, and they score.
  • filter clauses must match, and they don't score.
  • should clauses add score when they match. If a bool has no must or filter, at least one should must match, which minimum_should_match tunes.
  • must_not excludes, in filter context.

Here the phrase bonus lifts exact "taylor swift" sequences above documents that merely contain both words somewhere.

The query types you'll actually use:

QueryWhat it doesNotes
matchanalyses the input, ORs the terms (or operator: and)the default full-text query
multi_matchmatch over several fields with boostsbest_fields, most_fields, cross_fields, phrase
match_phraseterms in order, within slop positionsuses positions; "eras tour"
match_bool_prefix / search_as_you_type fieldlast term as a prefixautocomplete-style
term / termsexact value(s), not analyseduse on keyword, numeric; term on a text field is a classic bug
rangenumeric/date ranges, date math like now-7d/dBKD trees; cacheable filters
existsfield has a value
fuzzy / match with fuzziness: AUTOmatches within an edit distancetypo tolerance
prefix, wildcard, regexppattern matching over termsleading wildcards (*swift) scan the term dictionary, slow
nestedruns a query inside nested objects with same-object semanticsreturns the parent
geo_distance, geo_bounding_box, geo_shapespatial filterssee below
function_score / script_scorecustom scoring from fields, decay or scriptspopularity, recency
knnapproximate nearest neighbours over dense_vectorcombine with filters; hybrid with BM25

Fuzzy matching is what lets "Tayler Swfit" find Taylor Swift. Lucene computes the Levenshtein distance (the number of single-character insertions, deletions or substitutions, plus transpositions in the Damerau variant used by default) up to a maximum of 2. It doesn't compare the query with every term. Instead it builds a Levenshtein automaton that accepts exactly the strings within distance k of the query, and intersects it with the FST term dictionary. That visits only plausible terms, and it's why fuzzy search over millions of terms runs in milliseconds. fuzziness: AUTO allows 0 edits for 1–2 character terms, 1 edit for 3–5 characters, and 2 for longer ones. prefix_length: 1 or 2 requires the first characters to match, which hugely shrinks the candidates. It's a sensible default for performance, because typos rarely hit the first letter.

Autocomplete has three common implementations, each a trade-off:

  • Edge n-gram analysed fields (or the search_as_you_type type) index every prefix of every word. Lookups are fast, but the index is larger.
  • The completion suggester keeps an in-memory FST of inputs with weights. It's very fast prefix lookup with weights but no filters, apart from simple contexts. It suits "top suggestions as you type".
  • Prefix queries on keyword fields need no index change, but they're slower.

The Search Autocomplete case study shows when a precomputed trie beats all three.

Highlighting ("highlight": { "fields": { "description": {} } }) returns snippets with the matched terms wrapped in tags. The unified highlighter uses stored offsets or re-analyses the text.

Geo queries

geo_point fields hold latitude and longitude pairs, indexed in a BKD tree, and support:

  • geo_distance: everything within r km of a point ("events within 10 km of me"). Under the hood, it uses a bounding box for coarse pruning and then exact distance checks.
  • geo_bounding_box: everything inside a map viewport. It's cheaper than distance, and ideal for "search this area" on a map UI.
  • geo_polygon / geo_shape queries: inside arbitrary polygons, such as delivery zones and city boundaries. geo_shape fields index whole shapes (polygons, lines) as triangles in a BKD tree, and support intersects, within and contains relations.
  • Distance sorting (_geo_distance sort), and distance decay in function_score (closer is better, but not only distance counts).
  • Geo aggregations: geohash_grid and geotile_grid buckets for map clustering, geo_bounds and geo_centroid.

The theory behind these spatial indexes (geohash, quadtree, S2, R-trees) is in Geospatial Indexing. The practical point is that combining "near me" + text + filters in one query is the main reason proximity products such as Yelp-style search use Elasticsearch rather than stitching a geo index and a text index together.

Sorting

  • By default, results are sorted by _score descending.
  • sort by any field with doc values (keyword, numeric, date, geo distance) is cheap, because doc values are columnar.
  • Multi-field sort, [{"starts_at":"asc"}, {"price_min":"asc"}], breaks ties in order.
  • Nested sort. Sort events by their best review rating with "sort": [{ "reviews.rating": { "order": "desc", "mode": "max", "nested": { "path": "reviews" } } }]. The mode (min, max, avg, sum, median) collapses each document's many nested values into one sort key.
  • Script sort (Painless, Elasticsearch's sandboxed scripting language) computes a sort key per document at query time, such as price * (1 - discount). It's flexible but evaluated per matching doc, so it's slow over large result sets. Prefer indexing the computed value.
  • Sorting on a text field doesn't work, because it has no doc values (only fielddata, which you shouldn't enable). Sort on its .keyword sub-field.

Aggregations: analytics over the matches#

Aggregations compute summaries over every document matching the query, in the same request. They power facets ("Genre: Pop (1,204) · Rock (877)"), dashboards (Kibana), and analytics.

  • Bucket aggregations group documents. Examples: terms (top values), range, date_histogram (per hour or per day), histogram, filters, geotile_grid, composite.
  • Metric aggregations compute numbers per bucket: avg, sum, min, max, stats, cardinality (distinct count), percentiles, top_hits.
  • Pipeline aggregations compute over other aggregations: derivatives, moving averages, bucket_sort, cumulative sums.
"aggs": {
  "by_genre": { "terms": { "field": "genres", "size": 10 },
    "aggs": { "avg_price": { "avg": { "field": "price_min" } } } },
  "per_day":  { "date_histogram": { "field": "starts_at", "calendar_interval": "day" } },
  "unique_venues": { "cardinality": { "field": "venue.id" } }
}

Each runs per shard on doc values, then merges at the coordinator. The distribution has consequences that interviewers like to probe:

  • terms is approximate across shards. Each shard returns its top shard_size terms (by default size × 1.5 + 10), and the coordinator merges them. A term that is #11 on every shard but #1 overall can be missed or under-counted. The response's doc_count_error_upper_bound bounds the error. Increase shard_size for accuracy. For exact, exhaustive bucket listing, page through a composite aggregation.
  • cardinality uses HyperLogLog++, a sketch with configurable precision (precision_threshold, up to 40,000). Below the threshold, counts are near-exact. Above it, the error is typically about 1–2%, in a few KB of memory. The theory is in Probabilistic Data Structures.
  • percentiles uses t-digest by default (with an HDR histogram option), which is accurate at the tails, where you care (p99), and approximate in the middle.
  • Memory. A high-cardinality terms aggregation (say on user_id with 50 million values) or deep nesting can allocate huge bucket structures. Elasticsearch caps the total buckets per request (search.max_buckets, 65,536 by default in recent versions) and uses circuit breakers to fail the request instead of the node.

Pagination: from/size, search_after and point in time#

from + size is simple: page 3 of 20 means from: 40, size: 20. But every shard must collect its top from + size hits, and the coordinator must merge shards × (from + size) of them. Page 500 of 20 results on a 10-shard index means 10 × 10,020 = 100,200 entries collected and sorted to return 20. That cost grows linearly with depth. So index.max_result_window defaults to 10,000: from + size beyond it is rejected. Most UIs never need more ("Page 501" is not a real user need). If you do, use one of the next two methods.

search_after is the bookmark, or cursor, approach. You sort by a deterministic key, such as [{ "starts_at": "asc" }, { "id": "asc" }] (always include a unique tie-breaker). Then you pass the sort values of the last hit to get the next page:

GET events/_search
{ "size": 20, "query": { ... },
  "sort": [ { "starts_at": "asc" }, { "id": "asc" } ],
  "search_after": [ "2026-06-21T19:00:00Z", "evt_8812" ] }

Each shard now only needs hits after the bookmark, so page 500 costs the same as page 2. The catch is that the index keeps changing between requests. A newly indexed document that sorts before your bookmark is never shown, and a deleted one shifts nothing visibly. For infinite scroll that's acceptable. For exports, it may not be.

Point in time (PIT) + search_after gives a consistent snapshot:

  1. Open a PIT on the index (POST events/_pit?keep_alive=1m). You get an id that pins the current set of segments, so later merges and deletes don't remove the files it needs.
  2. Search with "pit": { "id": "...", "keep_alive": "1m" } plus sort and search_after. Every page sees the same frozen view. _shard_doc is an efficient implicit tie-breaker.
  3. Close the PIT when done (DELETE _pit). Each open PIT holds segments, file handles and heap. Leaking thousands of them is a real outage cause.

The older scroll API did a similar job (a server-side cursor over a snapshot). It's now discouraged for deep pagination in favour of PIT + search_after, though internal tools still use it for bulk export and re-index. The general pattern is the cursor-based pagination described in API Design.

Caching inside and in front of Elasticsearch#

Elasticsearch has several caches, and knowing which one helps which query matters for performance work.

  • OS page cache. This is the big one. Lucene's files are memory-mapped, so hot postings, doc values and BKD blocks stay in RAM, managed by the kernel. That's why heap stays at 50% or less of RAM. The fastest clusters are the ones whose working set fits in page cache.
  • Node query cache (filter cache). It caches the bitset of documents matching a filter clause, per segment. Only filters that recur, on segments that are large enough, are cached, using a usage-frequency heuristic, in an LRU of about 10% of heap. Since segments are immutable, an entry stays valid for the segment's life. That's another payoff of immutability. Filters like "status": "on_sale" or "city": "London" become nearly free on repeat.
  • Shard request cache. It caches the whole per-shard response for requests with size: 0, i.e. aggregations-only, such as dashboards and facet counts. The cache key is the request body. Entries are invalidated on every refresh that changes the shard, so it's most valuable on indices that don't change, such as old time-based indices.
  • Fielddata cache. It's for text fields used in aggregations or sorting, and it lives on the heap. It's off by default for good reason. Use keyword or doc values instead.

In front of Elasticsearch, applications add their own caches for repeated searches. The Ticketmaster-style event search shows the layering well.

  • Basic: no cache. Every search hits the cluster. That's fine until a big on-sale, when 100k users search "Taylor Swift" in the same minute.
  • Good: cache search results in Redis or Memcached. The cache key must include every parameter that changes the result: normalised query text, filters, sort, page and locale, plus the user's segment if results are personalised. For example: search:v3:q=taylor swift|city=london|from=2026-06|sort=relevance|page=1. Set a short TTL (30–120 s), because results go stale as availability changes. Invalidation is the hard part. An event update should evict every cached search containing that event. Cache tags do this: store "event 8812 appears in keys K1, K2..." and evict those keys on change. Fuzzy and free-text queries make key reuse low ("taylor swift" vs "taylor swift tickets"). Normalising queries (lowercasing, trimming, ordering filters) improves the hit rate.
  • Great: combine Elasticsearch's own caches with a CDN. Let the node query cache and the shard request cache absorb repeated filters and aggregations. For non-personalised queries (the public event catalogue), also cache the search API response at a CDN edge with Cache-Control: public, max-age=60. Popular queries are then answered at the edge in about 10–30 ms without touching your servers. Personalised results (recommendations, "events near your saved location") must bypass the CDN, or be keyed so they never leak across users.

Syncing from the primary database via CDC#

In nearly every product design, Elasticsearch holds a derived copy of data whose source of truth is a database such as PostgreSQL, MySQL or DynamoDB. The design question is how to keep that copy correct. There are three approaches, from worst to best.

1. Dual writes from the application. The service writes the database row, then calls Elasticsearch. It's simple, and it's wrong under failure. If the process crashes between the two writes, or the ES call times out after succeeding, or two concurrent updates reach ES in the opposite order to the database, the index silently drifts from the database. Nothing will ever repair it. This is the classic dual-write problem from Change Data Capture and the Outbox Pattern.

2. Change data capture (CDC). Read the database's own commit log and stream every change to the indexer:

  • PostgreSQL logical replication, through Debezium;
  • MySQL binlog;
  • DynamoDB Streams;
  • MongoDB change streams.

The log is already ordered and durable, and it contains every committed change, including ones made by migrations, admin scripts and other services. A typical pipeline is: database → Debezium → Kafka topic, keyed by row id → indexer (a Kafka Connect Elasticsearch sink, or your own consumer) → _bulk requests to Elasticsearch.

3. Outbox + CDC, when the search document isn't a single row. The transaction that updates the event also writes an outbox row ("event 8812 changed"). CDC ships the outbox, and the indexer rebuilds the whole denormalised document (event + venue + performers + min price) by reading the current state from the database. That decouples the index shape from table shapes, and it makes every message idempotent: "re-index event 8812" is safe to run twice.

The details that make CDC sync correct:

  • Ordering and idempotency. Key the Kafka topic by document id, so all changes to one document arrive in order on one partition. Write with external versioning: PUT events/_doc/8812?version=<source LSN or updated_at micros>&version_type=external. Elasticsearch then rejects any write whose version isn't higher than the stored one. Replays, retries and out-of-order deliveries can't overwrite newer data with older. That's the modern form of the optimistic concurrency the reference describes. For updates within Elasticsearch itself (read, modify, write), use if_seq_no + if_primary_term: the write fails with 409 if someone else changed the document in between. That replaces the old _version check.
  • Deletes. A database delete must become an ES delete (Debezium emits a delete event, followed by a tombstone). With soft deletes in the DB, index deleted: true and filter on it, or delete the document.
  • Bulk, not single writes. Batch 5–15 MB per _bulk request. Each item succeeds or fails independently, so check per-item errors. A 200 response can contain failed items. Retry 429 (rejected: the write thread pool queue is full) with backoff.
  • Lag monitoring. Track consumer lag (seconds behind the DB) as an SLO, e.g. "p99 search freshness < 5 s". The index lags the database by CDC latency + indexer time + refresh interval, typically 1–5 s.
  • Reconciliation. Even with CDC, bugs happen: a mapping rejection dropped a document, or a consumer was skipped past an offset. A periodic job compares ids and versions (or per-range checksums) between the database and the index, and re-indexes the differences. Search-index drift is one of the most common sources of production bugs in systems like this. Plan to detect it, not only prevent it.

Re-indexing without downtime. Mappings and analyzers can't be changed in place, and shard counts are fixed. So every structural change means building a new index. The pattern:

  1. Applications always read and write through an alias (events points to events_v7).
  2. Create events_v8 with the new mapping. For a fast bulk load, set refresh_interval: -1 and number_of_replicas: 0.
  3. Backfill it. Use _reindex from v7 when the source data is sufficient. Otherwise scan the database: note the CDC offset first, then bulk-load a snapshot.
  4. Replay CDC from the noted offset into v8 until it catches up. External versions make the overlap safe.
  5. Restore replicas and the refresh interval, and verify: counts, sample queries, relevance spot checks.
  6. Swap the alias atomically in one _aliases call that removes v7 and adds v8. Keep v7 for a quick rollback, then delete it.

Why Elasticsearch is not your primary store#

Elasticsearch can store documents and return them by id, so teams are tempted to make it the database. Resist that for anything you can't rebuild:

  • Durability and safety history. Kyle Kingsbury's Jepsen analyses (2014–2015, ES 1.x) showed acknowledged writes being lost during network partitions, along with split-brain scenarios. Elastic fixed many of these in later versions: sequence numbers and primary terms (6.0), and the new cluster coordination (7.0). But the system was designed as a search engine, and its own documentation recommends snapshots and treating the index as rebuildable.
  • No multi-document transactions. There are no ACID transactions across documents, no foreign keys, no unique constraints except _id, and no "reserve the last seat atomically".
  • Near-real-time reads. A search may not see a write for about a second. A user who saves and immediately searches sees stale results unless you use refresh=wait_for.
  • Mappings are rigid. Changing a field's type means re-indexing everything. A database ALTER TABLE is often online.
  • Updates are expensive. Each update is a delete plus a re-insert, so high-churn data is a poor fit (see segments above).
  • Operational blast radius. Heap pressure, a mapping explosion or a runaway aggregation can make the cluster unstable. If the cluster is also your system of record, a search incident becomes a data incident.

The healthy architecture: the database owns truth; Elasticsearch owns finding. Search returns ids, and maybe display fields. Anything that must be exactly current, such as price at checkout or seat availability, is read from the database (or a cache) by id. Exceptions exist where the data is inherently rebuildable or loss-tolerant. Logs and metrics are the big case, where Elasticsearch is commonly the only store, with snapshots to object storage as the backup.

Scaling pitfalls#

These are the failure modes that hit real clusters, roughly in order of how often they show up.

1. Deep pagination. from = 50,000 forces every shard to sort 50,000+ hits, and it's rejected beyond max_result_window. Fix it by product design: show only the first 50 pages, and encourage filters. Use search_after (with PIT) for deep browsing and exports. Don't raise max_result_window to a million. That only moves the problem into heap and latency.

2. Mapping explosion. Dynamic mapping plus documents with unbounded keys creates thousands of fields. Examples: user-defined attributes as object keys, {"attr_8812": ...}, or logs whose JSON contains ids as keys. Every field lives in the cluster state, which every node holds and the master must publish on every change. So a huge mapping slows the entire cluster, not just one index. Elasticsearch guards with limits: index.mapping.total_fields.limit (default 1,000), depth.limit (20), nested_fields.limit (50) and nested_objects.limit (10,000). The fixes:

  • Use "dynamic": "strict" or false.
  • Model key-value attributes as arrays of {key, value} nested objects, or as one flattened field.
  • Use runtime fields to query rarely used values at search time without indexing them.

3. Oversharding. Too many small shards: one index per customer per day, five primaries each. Each shard carries heap and file-handle overhead and master bookkeeping. A common guideline is to stay under about 20 shards per GB of heap, and far below that is better. Fixes: fewer, bigger shards (10–50 GB); rollover by size instead of by day; shrink old indices; a shared index with routing for small tenants.

4. Undersharding and hot shards. A 2 TB index with 2 primaries can't use more than 2 nodes for writes, and recoveries move 1 TB at a time. Custom routing by tenant creates hot shards for big tenants. Plan the shard count for the data size 6–12 months ahead, or use rollover so new indices get new counts.

5. Update-heavy workloads. Frequently changing fields cause constant delete-plus-reinsert and merge storms. Examples: "views", "likes", "stock". Keep them out of the index, update them in coarse batches, or store slowly changing buckets ("popularity tier 1–5") instead of exact counters.

6. Expensive queries.

  • Leading wildcards such as *phone: scan terms; fix with an ngram field or the wildcard field type.
  • Large terms aggregations on high-cardinality fields: memory; fix with composite paging.
  • Scripts in sorts and filters.
  • Massive bool queries with thousands of clauses: indices.query.bool.max_clause_count.
  • regexp queries.

Protect yourself with query timeouts, search.allow_expensive_queries: false, circuit breakers and per-tenant rate limits.

7. Heap and GC trouble.

  • A heap over about 31 GB loses compressed pointers.
  • Fielddata on text fields.
  • Big bulk requests (100 MB+) and huge aggregations.

Watch for heap usage persistently above 75–85%, long old-generation GC pauses, and circuit breaker trips.

8. Refresh and merge pressure. refresh=true on every write, a 1 s refresh on an index taking 50k docs/s, and too many replicas during a bulk load all multiply work. Bulk-load with replicas at 0 and refresh off, then turn them back on.

9. Split brain (historic). Before 7.0, a misconfigured minimum_master_nodes could elect two masters during a partition, and data diverged. The 7.0+ quorum-based coordination prevents this automatically. Still run three dedicated master-eligible nodes in three zones.

Time-based data: rollover, ILM and data streams

For logs, metrics and events, the data is append-only and queried mostly by recent time range. The standard pattern:

  • Data streams are an append-only alias over a series of hidden backing indices.
  • Rollover starts a new backing index when the current one reaches a size (say 50 GB per primary) or an age (say 1 day).
  • Index Lifecycle Management (ILM) moves indices through tiers by age:
    • hot: writes and heavy queries, on NVMe;
    • warm: read-only, force-merged to 1 segment, shrunk, on HDD or cheaper SSD;
    • cold: rarely queried, with fewer replicas, or on a searchable snapshot;
    • frozen: searchable snapshots in S3, cached locally on demand;
    • delete: after the retention period.
  • Retention by dropping whole indices is nearly free, compared with delete_by_query, which marks millions of tombstones.

Snapshots are incremental, segment-level copies to object storage (S3, GCS, Azure Blob), the backup mechanism of record. Because segments are immutable, an incremental snapshot copies only new segment files. Multi-region setups use cross-cluster replication (CCR), which ships operations from a leader index to a follower index in another cluster, for DR or read locality. Cross-cluster search (CCS) queries several clusters in one request.

When to Use It#

Use Elasticsearch, or OpenSearch, when search is a feature in its own right rather than a lookup:

  • Full-text search with relevance. Users type words and expect ranked, typo-tolerant, stemmed, synonym-aware results. Examples are product search, event search, documentation, job listings, help centres and messages.
  • Search combined with filters, facets and geo in one fast query: "4-star Italian restaurants within 2 km, open now, sorted by relevance with category counts".
  • Autocomplete and search-as-you-type across many documents.
  • Log, event and security analytics over large append-only, time-based data, with aggregations and dashboards: ELK, OpenSearch, SIEM.
  • Hybrid lexical + vector search, when you want BM25 and kNN in one engine with shared filters, rather than a separate vector store.
  • Scale signals:
    • corpora beyond a few million documents, where database full-text indexes slow down or can't rank well;
    • hundreds to thousands of search queries per second;
    • the need to scale search independently of the transactional database.

Pick something else instead when:

  • PostgreSQL full-text or pg_trgm fits for under a few million rows, simple ranking and modest QPS, with no second system to sync (PostgreSQL in Practice).
  • A managed search service fits for small and medium product search where developer experience beats control: Algolia, Typesense, Meilisearch.
  • A dedicated vector database fits when the workload is mostly semantic similarity at very large scale, or needs specialised ANN indexes (Vector Databases and Similarity Search).
  • Columnar analytics engines fit for pure metrics and analytics that need no text search, with high-cardinality group-bys, joins and exact counts over billions of rows: ClickHouse, Druid, Pinot. They're often 5–10× more storage- and compute-efficient than Elasticsearch for that workload (Time-Series Databases).

When NOT to Use It#

  • As the system of record for orders, payments, bookings or user accounts. Elasticsearch has no transactions, refresh is near-real-time, and its durability history is mixed.
  • For exact-match lookups by key or simple filters that a database index already serves. "Find user by email" doesn't need a search cluster. Under about 100k documents, a database query is usually enough. A whole new cluster to operate and keep in sync is a big price for little gain.
  • For rapidly mutating values such as live counters, inventory per purchase or presence. Every update rewrites the document.
  • For exact deduplication or existence checks. In a web crawler, "have we seen this content hash?" belongs in a database unique index (or a Bloom filter for a fast negative), not in a search engine with eventual visibility (Web Crawler).
  • For strongly consistent reads after writes. If the UX requires it, read from the database for the item just written.
  • When there are relational joins across many entities at query time. Denormalise first, or keep that query in SQL.
  • For heavy exact aggregations across very high cardinality, such as billing totals. Approximate terms and cardinality aren't acceptable for money.

How to Implement It#

The steps for adding search to an existing product, using event search on PostgreSQL as the example:

  1. Write down the queries first. For example: free text over title and performers, filters on city, date and price, a "near me" radius, genre facets, sort by relevance or date, and autocomplete. The list decides the document shape and the mapping.
  2. Design one denormalised document per searchable thing, such as an event plus the copied venue name, city and location, the performer names, the min price and the genres. Leave out rapidly changing fields, or round them ("tickets_left" becomes "availability: high/low/sold_out").
  3. Write an explicit mapping with dynamic: strict:
    • text with a language analyzer for prose;
    • a .keyword multi-field where you need sorting or exact matching;
    • keyword for ids and enums;
    • date, scaled_float and geo_point where they fit;
    • a search_as_you_type field for autocomplete. Test the analyzers with _analyze.
  4. Size the index. Estimate the source size × about 1.1–1.5 for index overhead, × (1 + replicas). Choose primaries so that each shard is 10–50 GB: 30 GB of events means 1–3 primaries, not 20. Use 1 replica (2 for very read-heavy or critical search).
  5. Create the index behind an alias (events → events_v1), and make every client use the alias.
  6. Build the sync pipeline:
    • CDC (Debezium → Kafka) or outbox;
    • an idempotent indexer that rebuilds documents;
    • external versioning;
    • _bulk writes with per-item error handling;
    • a dead-letter topic for documents that fail mapping.
  7. Backfill from a database snapshot, with refresh off and replicas at 0. Replay CDC from the pre-snapshot offset, then restore the settings and swap the alias.
  8. Write the query layer in a search service. Use bool queries with filters in filter context, boosts, function_score for recency and popularity, search_after pagination, and timeouts.
  9. Add caching (a Redis result cache, plus a CDN for public queries) and rate limits per client.
  10. Operate it:
    • three dedicated master-eligible nodes across zones;
    • snapshots to S3 every 30–60 min;
    • alerts on heap, GC, rejected threads, unassigned shards, CDC lag and p99 latency;
    • a nightly reconciliation job;
    • relevance tests: a fixed set of queries with expected top results, run in CI.

An idempotent CDC indexer in TypeScript, using the official @elastic/elasticsearch client:

type Change = { eventId: string; op: "upsert" | "delete"; lsn: bigint };
 
async function indexBatch(changes: Change[]) {
  const ops: object[] = [];
  for (const c of changes) {
    // external version = source log position: older replays are rejected (409)
    const meta = { _index: "events", _id: c.eventId, version: Number(c.lsn), version_type: "external" };
    if (c.op === "delete") { ops.push({ delete: meta }); continue; }
    const doc = await buildEventDocument(c.eventId);   // joins event + venue + performers from Postgres
    if (!doc) { ops.push({ delete: meta }); continue; } // row gone since the change was emitted
    ops.push({ index: meta }, doc);
  }
  const res = await es.bulk({ operations: ops, refresh: false });
  if (!res.errors) return;
  for (const item of res.items) {
    const r = item.index ?? item.delete!;
    if (!r.error) continue;
    if (r.status === 409) continue;                    // newer version already indexed: safe to skip
    if (r.status === 429) throw new RetryableError(); // back off and retry the batch
    await deadLetter.publish({ id: r._id, error: r.error }); // mapping errors etc.
  }
}

Note that Number(c.lsn) loses precision above 2⁵³. Production code passes the version as a string, or uses a commit timestamp in microseconds.

The search query side is covered above, in the bool example. The rest of the page explains each setting.

TechnologyFits when
Elasticsearch (self-managed or Elastic Cloud)You want the full feature set (machine learning, the ES-QL piped query language, the latest Lucene features, vector search) and Elastic's ecosystem (Kibana, Beats, APM)
OpenSearch / Amazon OpenSearch ServiceYou are on AWS, want an Apache-2.0 licence, or a managed service with IAM integration; OpenSearch Serverless for spiky or small workloads
Apache SolrYou already run it, or want a mature Lucene server with strong faceting and a ZooKeeper-based SolrCloud
PostgreSQL full-text (tsvector + GIN) / pg_trgmFewer than a few million documents, modest QPS, simple ranking, and no appetite for a second system to sync
Algolia / Typesense / MeilisearchProduct search where instant typo-tolerant UX and developer speed matter more than control; Algolia is hosted SaaS, the other two are open source and lightweight
VespaLarge-scale search and recommendation needing custom ranking models, tensors and real-time updates in one engine
ClickHouse / Druid / PinotLog and event analytics dominated by aggregations rather than text relevance; columnar storage is far cheaper per GB
Dedicated vector DB (pgvector, Pinecone, Milvus, Qdrant)Mostly semantic similarity, very large embedding sets, or specialised ANN tuning

Trade-offs#

OptionProsConsPick when
Database LIKE '%x%'No extra system; trivially consistentFull scan per query; no ranking, stemming or typo tolerance; collapses beyond about 100k rowsAdmin tools, tiny tables
Database full-text index (tsvector/GIN, MySQL FULLTEXT)Transactionally consistent; one system; decent rankingLimited relevance tuning, fuzzy and facets; scales with the DB; slows writesUp to a few million docs, moderate search QPS
Elasticsearch + CDCRich relevance, fuzzy, facets, geo, aggregations; scales horizontally; isolates search loadSecond system to run and sync; near-real-time; drift risk; JVM opsSearch is a core feature; millions+ docs; high QPS
Elasticsearch as primary storeOne systemNo transactions; durability and consistency weaker than a DB; rebuilds are hard without a sourceOnly rebuildable or loss-tolerant data (logs, metrics)
Hosted search SaaS (Algolia etc.)Fastest to great UX; no opsPer-record and per-query pricing; less control; data leaves your infraSmall and medium catalogues; teams without search engineers
Many small shardsParallel queries; easy to spreadHeap and cluster-state overhead; fan-out tail latencyRarely; prefer fewer 10–50 GB shards
refresh_interval 1 s vs 30 s1 s: fresher results1 s: more segments, merges and CPU1 s for user-facing freshness; 30 s or more for logs and bulk loads

Common Pitfalls#

  • Running term queries on text fields. term: {title: "Taylor Swift"} finds nothing, because the index contains taylor and swift. Use match, or term on title.keyword.
  • Leaving dynamic mapping on in production. You get a mapping explosion and wrongly guessed types (zip codes as numbers).
  • Dual writing from the app without CDC or reconciliation. The index drifts silently.
  • Treating the 1 s refresh as instant. A user creates an item and doesn't see it in search. Use refresh=wait_for for that request, or show it from the database.
  • Using from/size for exports or deep pages. Use PIT + search_after.
  • Leaking PITs and scrolls. They pin segments and heap. Close them, and use short keep-alives.
  • Giving the JVM over about 31 GB of heap, or all the RAM. It starves the page cache, which Lucene depends on.
  • Oversharding. For example, 5 primaries for a 2 GB index, or a daily index per tenant.
  • Ignoring per-item errors in _bulk. A 200 response with errors: true means documents were dropped.
  • Indexing hot counters. Every like or view becomes a re-index plus a tombstone.
  • Trusting terms aggregation counts as exact across shards.
  • Having no relevance tests. An analyzer or boost change silently breaks the top results for important queries.
  • Running a 2-master or 1-master cluster. You lose the quorum, or you have no fault tolerance.

Real-World Examples#

  • Wikipedia. Wikimedia built its on-site search ("CirrusSearch") on Elasticsearch. It's a good public example of multilingual analysis and relevance tuning at scale, with a large public body of engineering notes.
  • GitHub. GitHub originally ran code search on Elasticsearch. In 2023 it launched a new code search built on a custom engine (Blackbird), designed specifically for code: n-gram indexes over source, and exact and regex matching. This shows where a general text engine stops fitting a specialised workload.
  • Twitter. Twitter's real-time search engine, Earlybird, was built on Lucene with heavy custom modifications for append-only tweets and immediate searchability (Busch et al., "Earlybird: Real-Time Search at Twitter", ICDE 2012). It's an example of taking Lucene's ideas and specialising the write path.
  • Yelp published a migration of its core business search to Elasticsearch, to gain horizontal scaling and faster iteration on ranking.
  • Uber, Netflix, Shopify and many others have described Elasticsearch-based systems in engineering talks and blogs, for log analytics, search and observability. The ELK stack is a common default for centralised logging.
  • AWS maintains OpenSearch, the Apache-2.0 fork, and it runs as the Amazon OpenSearch Service.

Case studies that use this pattern#

In the Interview#

Elasticsearch shows up whenever the prompt contains the word search: events, posts, products, restaurants, logs. Interviewers want to see three things:

  1. You know when it's needed.
  2. You attach it correctly, as a derived index fed by CDC.
  3. You can go one level deeper into how it works: inverted index, shards, refresh, relevance.

A good progression, using Ticketmaster-style event search:

  • Basic (and wrong at scale): SELECT * FROM events WHERE name LIKE '%Taylor%'. A leading wildcard can't use a B-tree index, so every search scans the table. That's fine at 1,000 events and fatal at 10 million. Partial improvements are an index on the searched columns, EXPLAIN to check plans, selecting only needed columns, LIMIT, and UNION of indexed lookups instead of OR across columns. These help prefix and exact search, but not word search.
  • Good: a full-text index in the database (Postgres tsvector + GIN, MySQL FULLTEXT). Word search uses an index, consistency is transactional, and there's no new system. It's often the right call at moderate scale. Say so, and say when you would outgrow it.
  • Great: Elasticsearch fed by CDC from the primary database. The DB stays the source of truth, and ES provides relevance, fuzzy matching ("Tayler Swift"), filters, facets and geo. Add caching: ES's node query and shard request caches, a Redis result cache keyed by all parameters, and a CDN for public queries. Mention near-real-time indexing (about 1 s), and that seat availability must be read from the DB, not from search.

Follow-up questions to expect:

  • "Why not just use Elasticsearch as the database?" There are no transactions and no unique constraints beyond _id, refresh is near-real-time, and its durability history is mixed (Jepsen 2014–15). Mappings are rigid, and an outage becomes a data incident. Keep the DB as truth, so the index can always be rebuilt.
  • "How do you keep the index in sync, and what if it drifts?" CDC or outbox, idempotent upserts with external versioning, per-item bulk error handling, a lag SLO, nightly reconciliation, and alias-based re-indexing.
  • "How many shards?" Size for 10–50 GB per shard and growth over 6–12 months. Explain that primaries are fixed, and that you change them with rollover, split or shrink, or a re-index. Replicas add read throughput and availability, not write capacity.
  • "Users complain new posts don't appear in search for a second. Why?" The refresh interval. The write is durable in the translog but not yet in a searchable segment. Explain refresh=wait_for for read-your-writes, and why refresh=true everywhere is harmful.
Deep Dive: Inside Lucene — FSTs, postings compression, BKD trees and top-k pruningShow

A search engine is fast because of how it encodes data, not because it has a clever top-level algorithm. This section walks through the main structures, with the numbers that make them work.

The term dictionary as a finite state transducer. A segment may hold tens of millions of distinct terms, so a hash table or sorted array in memory would cost gigabytes. Lucene stores terms on disk in sorted blocks of roughly 25–48 terms, and keeps in memory only an FST over the block prefixes. An FST is a minimal deterministic automaton in which each transition can also emit an output, here the block's file pointer. Two kinds of sharing make it small:

  • Common prefixes are shared, as in a trie: "swift", "swifty", "swiftly".
  • Common suffixes are shared too, unlike in a trie: "running", "jumping", "-ing".

So the FST index for a large dictionary is often a few percent of the dictionary's size. Lookup is O(length of term): walk the automaton, collect outputs, seek to one block, then scan it.

The same automaton also powers multi-term queries. Lucene compiles a prefix, wildcard, regex or Levenshtein pattern into its own automaton, and intersects the two automata. That enumerates only the dictionary terms the pattern accepts, without iterating every term. Fuzzy query support became practical when Lucene 4.0 (2012) switched to this approach using Levenshtein automata, based on Schulz and Mihov (2002), "Fast string correction with Levenshtein automata". Before that, fuzzy queries scanned the dictionary and were orders of magnitude slower.

Postings: delta + frame-of-reference + skip data. Doc IDs in a postings list are sorted, so Lucene stores the gaps between them. A common term in a 10 M-doc segment has gaps of about 1–10, which fit in 4 bits. Lucene's postings format groups them into blocks of 128 deltas, and stores each block with the minimum bit width that fits its largest delta. That's frame-of-reference, or FOR, bit-packing. A block whose largest gap is 13 uses 4 bits per entry, so 128 entries take 64 bytes. Decoding is a tight loop the CPU can vectorise. Leftover entries use variable-byte encoding.

On top of the blocks sit multi-level skip lists. Every 128 docs there's a pointer to the next block's offset and max doc ID, and each higher level skips 8× further. An intersection advance(target) call therefore jumps over whole blocks without decoding them. That's what makes "rare AND common" fast. A conjunction drives iteration from the rarest clause (lowest cost estimate) and calls advance on the others. With 3,000 and 4,000,000 postings, that's about 3,000 advances, each costing O(log) skips plus at most one block decode.

Roaring bitmaps for filters. Cached filter results are stored as roaring bitmaps, where Lucene uses its own RoaringDocIdSet. The doc space is split into chunks of 65,536 docs. Each chunk is stored as a sorted array when it's sparse (fewer than 4,096 hits), and as a 1-bit-per-doc bitmap when it's dense. That keeps memory at roughly min(2 bytes × hits, 8 KB) per chunk, and intersections fast.

BKD trees for numbers and geo. A block k-d tree (Procopiuc, Agarwal, Arge and Vitter, "Bkd-Tree: A Dynamic Scalable kd-Tree", 2003) recursively splits k-dimensional points along the dimension with the largest spread, until leaves hold about 512 points. Each inner node stores its split value and its cell's bounding box. A range or box query descends, and three cases arise per cell:

  • If a cell is entirely inside the query, all its leaf docs are collected without checking each point.
  • If it's entirely outside, it's skipped.
  • Only crossing cells inspect individual points.

For a 1-D price range, this touches O(log N + matches/512) blocks. Lucene builds the tree once per segment at flush (immutability again), and merges trees during segment merges. Geo shapes are tessellated into triangles, and each triangle is indexed as a 7-dimensional point, so the same tree answers intersects, within and contains queries.

Doc values encoding. Numeric doc values per segment are compressed with techniques chosen by the data:

  • the GCD of values ("all prices are multiples of 0.01");
  • delta from the minimum;
  • table encoding when there are few distinct values;
  • bit-packing per block.

Sorted (keyword) doc values store a per-segment ordinal per doc, plus a sorted terms dictionary. Sorting and terms aggregations work on small integer ordinals and look up the strings only at the end. Global ordinals map segment ordinals to index-wide ordinals, and they're built lazily (or eagerly, via eager_global_ordinals) after each refresh. That's why the first terms aggregation after a refresh on a high-cardinality field can be slow.

Top-k without scoring everything: WAND and block-max WAND. A query "taylor OR swift OR tour" might match 2 million docs, but you want only the top 10. WAND (Broder, Carmel, Herscovici, Soffer and Zien, CIKM 2003) keeps, for each term, an upper bound on the score it can contribute. A document can enter the top-k only if the sum of the bounds of the terms it contains exceeds the current k-th best score (the threshold). So whole stretches of doc IDs that contain only "tour" are skipped once the threshold rises above tour's maximum contribution. Block-max WAND (Ding and Suel, SIGIR 2011) stores the maximum score per postings block, which gives much tighter bounds. Lucene 8 (2019) implemented it, which is why Elasticsearch 7+ returns hits.total as "≥ 10,000" by default. Counting every match exactly would defeat the skipping. Elastic reported speedups of several times on disjunctive queries. Set track_total_hits: true only when you really need the exact count.

HNSW in segments. For dense_vector, each segment builds its own Hierarchical Navigable Small World graph (Malkov and Yashunin, 2016/2018), a multi-layer proximity graph searched greedily from the top layer down. Building HNSW is CPU-heavy, and segment merges must rebuild or merge graphs, so vector indexing throughput is much lower than for text. Quantisation (int8, int4 and binary or BBQ in recent versions) shrinks vector memory 4–32×. kNN results across segments and shards are merged like any top-k. Hybrid ranking with BM25 is typically done with reciprocal rank fusion (RRF), which scores each doc as Σ 1/(k + rank) across the result lists, with k = 60 by convention (Cormack, Clarke and Büttcher, SIGIR 2009). RRF avoids having to calibrate BM25 scores against cosine similarities, which aren't on comparable scales.

What this means in practice.

  • Low-cardinality, recurring filters are almost free. They're cached as roaring bitsets, and immutable segments keep the caches valid.
  • Rare terms make queries fast.
  • Leading wildcards are slow, because their automaton can't prune the dictionary from the front.
  • Exact total counts cost real performance.
  • Each new segment needs its own structures, which is why refresh frequency, merge policy and bulk loading settings matter as much as hardware.
Deep Dive: Replication, consistency and cluster coordinationShow

Elasticsearch's replication is primary-backup with leader-based ordering. It is not a quorum system like Cassandra, and it's worth knowing precisely what it guarantees.

The data replication model. Each shard has one primary, plus replicas in an in-sync set that the master tracks in the cluster state. The primary assigns every operation a sequence number, a monotonic counter per shard, tagged with the current primary term. The term increments on every primary promotion, so operations from a deposed primary can be recognised and rejected.

The primary forwards each operation to all in-sync replicas, and acknowledges once every in-sync copy has applied it, or has been removed from the in-sync set by the master. If a replica fails to apply an operation, the primary asks the master to mark it stale, and only then acknowledges. Two consequences follow:

  • The latency of a write is the latency of the slowest in-sync replica, not a quorum.
  • An acknowledged write is on every copy the master currently considers in-sync. So a promoted replica (which is always chosen from the in-sync set) has all acked writes.

Checkpoints and recovery. Each copy tracks a local checkpoint: the highest seq_no below which it has processed every operation. The primary computes the global checkpoint, the minimum of the in-sync copies' local checkpoints, and shares it. Everything at or below the global checkpoint is known to be on all in-sync copies. When a replica restarts or a new primary is promoted, recovery works like this:

  • Operations-based recovery. The primary replays operations above the replica's last global checkpoint, from its retained history, kept with retention leases and soft deletes. That's only the gap, not the whole shard. Before 6.0, recovery often meant copying whole segment files, and a node restart could cost hours of transfer per TB.
  • Resync after promotion. A newly promoted primary has operations above the global checkpoint that some replicas may lack, or replicas may have operations the new primary lacks from the old term. It resyncs: it sends its operations above the global checkpoint, and replicas roll back anything from older terms that the new primary doesn't have.

The dynamics resemble a Raft-like log at the shard level: terms, ordered sequence numbers and a commit watermark. Membership decisions, however, are delegated to the master's cluster state rather than to per-shard voting.

Reads are not linearisable. A search can go to any copy:

  • Two consecutive searches may hit different copies at slightly different refresh points, so a document can appear and then disappear.
  • A deposed primary, cut off by a partition but not yet aware of it, could serve stale reads briefly.

preference (for example a session id) pins a user to the same copies for consistent paging. GET by id is real-time on the copy it hits.

Cluster coordination since 7.0. The master-eligible nodes form a voting configuration, and decisions need a majority of it. Elections, and the publication of new cluster states, are two-phase: publish, then commit after a majority acks. Elastic designed the algorithm (it has been described as Raft-like with a different state-transfer model) and model-checked it with TLA+. Crucially, the voting configuration is managed automatically as master-eligible nodes join and leave, keeping an odd number. That ended the minimum_master_nodes misconfiguration, which was the root of most historical split-brain incidents. When more than half the master-eligible nodes are lost, the cluster stops electing a master and rejects writes, but searches on the data nodes may still run (no_master_block defaults to blocking writes only). That's a CP choice for metadata. See Consensus: Raft and Paxos for the general theory.

What the Jepsen analyses found, and what changed. Kyle Kingsbury's 2014 Jepsen tests of Elasticsearch 1.1–1.5 showed, under network partitions:

  • split-brain, with two masters accepting writes;
  • loss of acknowledged writes when the minority side's writes were later discarded;
  • dirty reads.

The underlying issues were the Zen discovery protocol and the lack of operation sequencing. Elastic's responses arrived over several major versions:

  • 5.0: an allocation-ID-based in-sync set;
  • 6.0: sequence numbers, primary terms and checkpoints;
  • 7.0: the new coordination layer.

The honest summary today: modern Elasticsearch is far more robust, but it's still not designed as a transactional system of record. The recommended durability posture is snapshots plus a rebuildable source of truth.

Write consistency knobs.

  • wait_for_active_shards makes a write fail fast when fewer than N copies are available.
  • refresh=wait_for provides read-your-writes on search.
  • if_seq_no / if_primary_term provide a compare-and-set on a single document.
  • External versioning provides an ordering that's monotonic with your database log.

There are no multi-document transactions, and none of these provide atomic visibility across documents. A search can see half of a bulk request.

Failure scenarios worth reasoning about.

  • A data node dies. Replicas are promoted for its primaries (seconds). The cluster goes yellow, then allocates new replicas elsewhere. index.unassigned.node_left.delayed_timeout (1 min default) delays re-replication, to avoid copying terabytes for a node that's merely rebooting.
  • A zone fails. With shard allocation awareness (cluster.routing.allocation.awareness.attributes: zone), a primary and its replica never sit in the same zone, so losing one zone loses no data. The master nodes must be spread across three zones to keep a quorum.
  • A long GC pause on a node. It's treated as failed by fault detection, its shards are reassigned, and then it rejoins. If this happens repeatedly, it's "shard flapping". Fix the heap pressure.
  • The disk fills up. At the watermarks (85% low, 90% high, 95% flood stage by default), shards stop being allocated to the node, are moved away, and finally indices get a read-only block. That's a common surprise outage for log clusters without ILM.
Deep Dive: Relevance engineering, evaluation and search architecture at scaleShow

Getting results back is easy. Getting the right results first is the hard, ongoing part of search. Mature search teams work in roughly this order.

1. Query understanding before retrieval:

  • Normalise the query: case, Unicode, whitespace.
  • Spell-correct with the term and phrase suggesters, or an n-gram language model.
  • Detect intent and entities. "taylor swift london" becomes performer = Taylor Swift and city = London.
  • Rewrite: synonyms, and drop "tickets", which every event matches.

Turning free text into structured filters is often the single largest relevance win, because a filter is exact where a fuzzy text match is noisy.

2. Retrieval (recall): get a candidate set of a few hundred to a few thousand per shard that probably contains the good results. Use BM25 over boosted fields, plus filters, plus optional kNN (hybrid). Retrieval must be cheap, because it touches every shard.

3. Ranking (precision) on the candidates:

  • function_score with recency and popularity decay;
  • rescore windows with phrase proximity;
  • learning to rank (LTR): a gradient-boosted tree model (LambdaMART is the classic choice) trained on click and purchase logs, run as a rescorer over the top window. Elasticsearch has native LTR support in recent versions, and OpenSearch has an LTR plugin.

A cross-encoder re-ranker (a transformer model scoring query–document pairs) is the modern top layer, affordable only for the top 50–100 results.

4. Business rules and diversity. Pin promoted results, demote sold-out items, and diversify, so the page isn't ten results from one seller. Personalise by blending user features.

Measuring relevance offline. Collect a judgement list: queries with graded relevance labels per result, from human raters or inferred from clicks. Compute:

  • Precision@k: the fraction of the top k that are relevant.
  • Recall@k.
  • MRR (mean reciprocal rank): good for navigational queries with one right answer.
  • NDCG@k (normalised discounted cumulative gain) (Järvelin and Kekäläinen, 2002): graded gains discounted by log₂(rank + 1), normalised by the ideal ordering. It's the standard metric for ranked lists with graded relevance.

Elasticsearch's _rank_eval API computes these over a judgement list. Run it in CI, so a mapping or boost change that drops NDCG@10 from 0.71 to 0.64 fails the build.

Measuring online. Run A/B tests on click-through rate, zero-result rate, query reformulation rate ("searched again within 10 s"), conversion and revenue per search. Click logs are biased by position: users click the top result partly because it's on top. So training an LTR model on raw clicks needs position-bias correction, such as randomised interleaving or inverse propensity weighting. Interleaving (mixing results from rankers A and B in one list) detects ranking differences with far less traffic than an A/B split.

Worked capacity example. A marketplace has 200 M listings, each about 2 KB of _source with indexed fields.

  • Raw data: about 400 GB. With index overhead at about 1.3×, that's about 520 GB per copy.
  • Shards: at about 40 GB each, that's 13, so round to 15 primaries. With 1 replica there are 30 shards, about 1.04 TB total.
  • Traffic: 3,000 searches/s at peak, a p99 target of 150 ms, and 2,000 updates/s from CDC.
  • Per-query cost: each search fans out to 15 shards. If a shard-level query costs about 10 ms of CPU, that's 3,000 × 15 × 10 ms = 450 CPU-seconds per second. At 60% target utilisation, that's about 750 cores, or about 24 nodes of 32 cores.
  • Memory: each node then holds about 43 GB of shards. Give each 128 GB of RAM: 31 GB heap and about 90 GB page cache, so the hot working set fits in memory.
  • Replicas: going to 2 replicas raises read capacity by 1.5× at the cost of more storage and indexing work. Indexing cost here is about 2,000 × 3 copies of document analysis per second, which is minor next to search.

This is the shape of the estimate an interviewer wants. The search-side compute dominates, and shard count × QPS is the key product.

Search architectures beyond one cluster.

  • Index per tenant vs shared index with routing. Large tenants get their own index for isolation. The long tail shares an index routed by tenant_id, which avoids millions of tiny shards.
  • Tiered serving. A small, hot "head" index of popular or recent documents is queried first, and the full index only when the head returns too few results. Web search engines use the same idea at vastly larger scale (Web Search Engine case study).
  • Separate read and write clusters. Index into one cluster and replicate (CCR) to read clusters in other regions. That keeps indexing load off the serving path and puts search close to users.
  • Real-time plus batch. Twitter's Earlybird is the classic description. A small in-memory real-time index takes new tweets and is searchable in seconds, while larger optimised indexes are built in batch and merged in. Lucene's own design (a write buffer plus immutable segments) is a miniature version of the same idea.
  • Document-partitioned vs term-partitioned indexes.
    • Elasticsearch partitions by document: each shard has a full inverted index for its subset of docs. Queries fan out to all shards, but each shard computes its own top-k.
    • Term partitioning puts each term's full postings list on one machine. A query touches only the machines holding its terms, but multi-term queries must ship large postings lists between machines to intersect them, and popular terms create hot machines.
    • Nearly every production engine partitions by document. Post Search walks through this choice.

The skills this teaches beyond search. Elasticsearch packs several broadly useful ideas:

  • Immutability as a performance tool: segments, caches and snapshots.
  • Separating the query path from storage: query then fetch, with _source stored separately from the index structures.
  • Choosing index structures per access pattern: inverted index, doc values, BKD trees, HNSW.
  • Living with eventual consistency explicitly: refresh, CDC lag and reconciliation.
  • Probabilistic structures at the edges: skip lists, FSTs, HyperLogLog++ and t-digest.

Each reappears across databases and streaming systems in this handbook.

Key Takeaways#

  • Elasticsearch is a distributed wrapper around Lucene. An index is split into fixed primary shards, plus replicas. Each shard copy is a Lucene index of immutable segments, holding an inverted index (FST term dictionary plus compressed postings), doc values, BKD trees and, optionally, HNSW vectors.
  • Analysis decides what can match. Character filters, a tokenizer and token filters run at index time and at query time. text is for words, keyword for exact values, sorting and aggregations. Use explicit mappings with dynamic: strict.
  • BM25 ranks by saturating term frequency, inverse document frequency and field length (k1 = 1.2, b = 0.75). Real relevance comes from boosts, function_score, rescoring and LTR, measured with NDCG.
  • Writes are durable on ack (translog) but searchable only after refresh (about 1 s). Updates are a delete plus a re-insert, so keep fast-changing counters out of the index.
  • It's a derived index, not a database. Feed it via CDC or outbox, with external versioning, bulk error handling, lag SLOs, reconciliation and alias-swap re-indexing. Read exact values from the source of truth.
  • The scaling pitfalls are predictable:
    • deep pagination: use PIT + search_after;
    • mapping explosion;
    • over- or undersharding: aim for 10–50 GB shards;
    • heap over 31 GB;
    • expensive queries;
    • update-heavy data.