PrepStack › Databases › Elasticsearch

Elasticsearch interview cheat sheet

Inverted index, analyzers, mappings, Query DSL, scoring, shards & scaling

Elasticsearch questions show up in backend, data and system design rounds. Interviewers check that you understand why search is fast (the inverted index and analysis), how data is distributed (shards, replicas, routing), why it is near real-time (refresh, segments, translog), and how to write correct queries (text vs keyword, query vs filter context, BM25). Senior rounds add mapping changes without downtime, deep pagination, ILM and vector search. REST examples use JSON; the small JS/Python programs rebuild the core ideas and are verified.

15-minute revision

  1. Elasticsearch is a distributed search and analytics engine built on Apache Lucene. Data is JSON documents in indices, queried over a REST API. It is usually a secondary store fed from a primary database.
  2. Cluster → nodes → indices → shards (each shard is a full Lucene index) → segments. A replica is a copy of a primary shard on a different node, used for failover and read throughput.
  3. Primary shard count is fixed at index creation (change it with reindex, split or shrink). Replica count can change any time. Aim for 10–50 GB per shard and under 200M docs.
  4. The inverted index maps each term to a posting list of doc IDs (plus frequencies and positions). Search = look up terms and combine posting lists, not scan documents.
  5. Writes go to an in-memory buffer and the translog. A refresh (default every 1s) writes a new searchable segment, which is why search is near real-time. A flush is a Lucene commit that lets the translog be trimmed. Merges combine small segments and purge deleted docs.
  6. An analyzer = 0+ char filters → exactly 1 tokenizer → 0+ token filters. The same analysis must apply at index time and query time, or terms won't match.
  7. text is analyzed for full-text search. keyword is stored as one exact term for filters, sorting and aggregations. Dynamic mapping maps a JSON string to text + a .keyword sub-field.
  8. term does no analysis (use it on keyword, numbers, dates). match analyzes the input (use it on text). term on a text field is a classic bug.
  9. bool: must (scores), should (optional, boosts), filter (must match, no scoring, cacheable), must_not (excludes, filter context). Put exact constraints in filter.
  10. Default similarity is BM25 (k1 = 1.2, b = 0.75): term frequency saturates and length normalization is tunable. Classic TF-IDF grew without limit.
  11. Aggregations: bucket (terms, date_histogram, range), metric (avg, sum, cardinality, percentiles), pipeline (work on other aggs' output, e.g. derivative, max_bucket).
  12. from + size is capped at 10,000 (index.max_result_window). For deep paging use search_after + a point in time (PIT). Scroll is no longer recommended for deep pagination.
  13. Search is query then fetch: every shard returns top doc IDs + scores, the coordinating node merges them, then fetches _source only for the final page.
  14. Change a mapping with reindex into a new index + atomic alias swap. Apps should always read and write through aliases.
  15. ILM moves time-series indices through hot → warm → cold → frozen → delete, with rollover by size/age. Data streams are the standard for logs and metrics.
  16. Vector search: dense_vector field + knn (approximate HNSW, k and num_candidates). Hybrid search combines BM25 and kNN, often with RRF. OpenSearch is the Apache-2.0 fork of ES 7.10.

Foundations & Architecture

What Elasticsearch is & when to use it

A distributed, Lucene-based search and analytics engine; great for search and logs, risky as the only source of truth.

  • Elasticsearch wraps Apache Lucene (a single-node search library) and adds distribution, replication, a JSON REST API, aggregations and cluster management.
  • Data is stored as JSON documents in indices. Each field is indexed with a structure suited to its type: inverted index for text, BKD trees for numbers/dates/geo, doc values for sorting and aggregations.
  • Common uses: full-text search (site, product, docs search), log and metrics analytics (ELK / observability), security analytics (SIEM), autocomplete, geo search, and now vector/semantic search.
  • It is eventually consistent for search (near real-time), has no multi-document transactions, no joins in the SQL sense, and mapping changes often need a reindex.
  • Typical design: a relational or document DB is the source of truth, and changes flow to ES via CDC (Debezium, Kafka), an outbox, or a sync job. ES is rebuildable from the primary store.

Interview questions

  • What is Elasticsearch?
  • Would you use Elasticsearch as your primary database?
  • Why is search in ES faster than LIKE '%term%' in SQL?
  • How do you keep Elasticsearch in sync with your main database?

Cluster, nodes, roles, indices & documents

A cluster is a set of nodes with roles; an index is a logical collection of documents split into shards spread over data nodes.

  • Cluster: one or more nodes sharing a cluster.name. One elected master manages cluster state (indices, mappings, shard allocation).
  • Node roles are set with node.roles. A node with an empty list is a coordinating-only node. Every node can coordinate (route requests and merge results).
  • Index: a logical namespace of documents with one mapping. Since 8.0 there are no mapping types (one index = one kind of document).
  • Document: a JSON object with a unique _id inside an index. It is the unit of indexing; updates are delete + reindex of the whole doc internally.
  • Run 3 master-eligible nodes in production so the cluster can elect a master after losing one (a voting quorum is a majority). Since 7.0 ES manages quorum itself; minimum_master_nodes is gone.
  • Data tiers are roles too: data_hot, data_warm, data_cold, data_frozen, plus data_content for non-time-series data.

Interview questions

  • What are the main components of an Elasticsearch cluster?
  • What is a coordinating node?
  • Why do you need 3 master-eligible nodes?

Primary vs replica shards & shard sizing

Primaries split the data for scale; replicas copy it for availability and read throughput; size shards at roughly 10–50 GB.

  • A primary shard owns a subset of documents; every write goes to the primary first. A replica shard is a full copy of one primary, kept on a different node.
  • number_of_shards (default 1 since 7.0) is fixed after creation because routing depends on it. number_of_replicas (default 1) can be changed live.
  • Replicas give high availability (promoted when a primary fails) and read scaling (searches can hit any copy). They do not speed up writes; each write is done on every copy.
  • Sizing guidance from Elastic: aim for 10–50 GB per shard and keep each shard under 200 million docs. Each search uses one thread per shard, and each shard/segment/field has heap overhead.
  • Oversharding (thousands of tiny shards) wastes heap and slows the master. Huge shards slow recovery and rebalancing.
  • To change primary count: _split (multiply), _shrink (divide), or reindex. For time-series data, rollover creates new indices so each one stays well sized.

Interview questions

  • What is the difference between a primary and a replica shard?
  • Why can't you change the number of primary shards after index creation?
  • How many shards should an index have?

Storage & Indexing Internals

The inverted index

A map from each term to the sorted list of documents (and positions) that contain it.

  • Built per field at index time: text → analyzer → terms → for each term a posting list of doc IDs, with term frequency and positions.
  • The term dictionary is sorted and has a compact prefix index (an FST) in memory, so finding a term is very fast.
  • A multi-word AND query intersects posting lists; OR unions them. Positions make phrase and proximity queries possible.
  • Exact-match fields (keyword) are indexed as one term per value. Numbers, dates and geo use BKD trees instead, which are good for ranges.
  • Doc values are the opposite, column-oriented structure (doc → value) stored on disk. They power sorting, aggregations and scripts.
  • Segments are immutable, so the inverted index is never edited in place; updates and deletes create new data plus a deletion marker.

Interview questions

  • What is an inverted index?
  • What are doc values and why do they exist?
  • How does a phrase query use the inverted index?

Segments, refresh, flush, merge & translog

Writes become searchable when a refresh creates a new segment (~1s), durable via the translog, and tidy via background merges.

  • A shard is a Lucene index made of immutable segments. New docs go to an in-memory indexing buffer and are appended to the translog.
  • Refresh (default every 1s) writes the buffer into a new segment (in the OS file cache) and opens it for search. That gap is why ES is near real-time (NRT).
  • If refresh_interval is not set explicitly, a shard that hasn't been searched for 30s (index.search.idle.after) goes search idle and skips scheduled refreshes until the next search.
  • Flush = a Lucene commit (fsync segments to disk) plus starting a new translog generation, so old translog can be trimmed. ES triggers it automatically based on translog size.
  • Translog (write-ahead log): by default (index.translog.durability: request) it is fsynced before the write is acknowledged, so acked writes survive a crash and are replayed on recovery.
  • Merge: background process that combines small segments into larger ones and physically removes deleted docs. Deletes and updates only mark old versions as deleted until then.

Interview questions

  • Why is Elasticsearch called near real-time?
  • What is the difference between refresh and flush?
  • What is the translog and why is it needed?
  • Why doesn't deleting documents free disk space immediately?

Write path & read path (query then fetch)

Writes go coordinator → primary → in-sync replicas; searches scatter to one copy of each shard, then gather and fetch.

  • Write: the coordinating node computes the shard from _routing, forwards to the primary; the primary validates and indexes, then forwards to all in-sync replicas in parallel and acks once they respond.
  • wait_for_active_shards (default 1) is only a pre-check before writing; it doesn't make the write quorum-based. Replicas that fail are removed from the in-sync set by the master.
  • Search – query phase: the coordinator sends the query to one copy of every shard (primary or replica, chosen by adaptive replica selection). Each shard returns only the top from + size doc IDs and sort values/scores.
  • Search – fetch phase: the coordinator merges all shard results into a global order, picks the requested page, and asks only the owning shards for those docs' _source.
  • Scores use shard-local term statistics. With few docs or uneven shards this skews ranking; search_type=dfs_query_then_fetch gathers global stats first at extra cost.
  • GET by ID skips the scatter: it goes straight to one copy of the shard that owns the routing value.

Interview questions

  • Walk me through what happens when you index a document.
  • Explain query then fetch.
  • Why might the same document get different scores in different shards, and how do you fix it?
  • Is an Elasticsearch write consistent across replicas?

Routing & custom routing

shard = hash(_routing) % primaries; custom routing co-locates related docs so queries hit one shard.

  • By default _routing = _id, hashed with Murmur3. This spreads docs evenly and is why primary count can't change freely.
  • Custom routing (?routing=tenant42) puts all docs with the same value on the same shard. Searches that pass the same routing value hit only that shard.
  • Use it for multi-tenant data, or to keep parent and child docs together (the join field requires it).
  • Risk: hot shards. A huge tenant makes one shard much bigger and busier. index.routing_partition_size spreads a routing value over a subset of shards.
  • With custom routing, _id is unique only per shard; you must pass the same routing for GET, update and delete. Set _routing: { required: true } to enforce it.

Interview questions

  • How does Elasticsearch decide which shard a document goes to?
  • When would you use custom routing?
  • What breaks if you forget the routing value on GET or delete?

Text Analysis & Mappings

Analyzers: char filters, tokenizers, token filters

Analysis turns raw text into the terms that are indexed and searched; the pipeline is char filters → 1 tokenizer → token filters.

  • Character filters edit the raw string first: html_strip, mapping (e.g. & → and), pattern_replace.
  • A tokenizer (exactly one) splits text into tokens with positions and offsets: standard (Unicode word boundaries), whitespace, keyword (whole input), pattern, ngram, edge_ngram, path_hierarchy.
  • Token filters change, remove or add tokens: lowercase, stop, stemmer/porter_stem, synonym/synonym_graph, asciifolding, edge_ngram.
  • Built-in analyzers: standard (default: standard tokenizer + lowercase), simple, whitespace, keyword, stop, pattern, and language analyzers like english.
  • Analysis runs at index time and at search time. Use search_analyzer when they should differ, e.g. edge n-grams at index time for autocomplete but not on the query.
  • Test with the _analyze API before you index real data.

Interview questions

  • What is an analyzer and what are its parts?
  • Why might a search for “Running” not find a document containing “runs”?
  • How would you implement search-as-you-type autocomplete?

text vs keyword fields

text is analyzed for full-text relevance; keyword is one exact term for filtering, sorting and aggregations.

  • text: run through an analyzer into many terms. Supports match, phrases, relevance. No doc values, so no sort/aggregate by default.
  • keyword: the whole value is one term, case-sensitive. Use for IDs, emails, status, tags, enums. Has doc values for sort and aggs.
  • Multi-fields index one JSON value both ways: title (text) and title.keyword (keyword). Dynamic mapping does this for strings with ignore_above: 256.
  • A normalizer is the keyword equivalent of an analyzer (no tokenizer): e.g. lowercase so term matches case-insensitively.
  • Other useful types: match_only_text (no positions/scoring stats, smaller — good for logs), wildcard (for grep-like matching on long strings), constant_keyword.

Interview questions

  • What is the difference between text and keyword?
  • Why does {"term": {"title": "Quick Fox"}} return nothing?
  • How do you do case-insensitive exact matching on a keyword field?

Mappings: dynamic vs explicit & mapping explosion

A mapping is the index schema; dynamic mapping is convenient, explicit mapping is safe for production.

  • Dynamic mapping guesses types from the first doc: string → text + .keyword, integer → long, decimal → float, true → boolean, date-looking string → date, object → object.
  • dynamic setting: true (add new fields), runtime (add as runtime fields, not indexed), false (ignore new fields, keep them in _source), strict (reject docs with unknown fields).
  • Explicit mapping: declare types yourself. You can add new fields to an existing mapping, but you can't change an existing field's type or analyzer — that needs a reindex.
  • Mapping explosion: unbounded keys (user IDs, timestamps as field names) create thousands of fields, bloating cluster state and heap. Limit: index.mapping.total_fields.limit (default 1000).
  • Fixes for arbitrary keys: flattened type (whole object as keywords), key/value nested arrays, dynamic: false, or dynamic templates to control types.
  • object flattens arrays of objects, losing which values belong together; nested indexes each array item as a hidden sub-document to keep them paired (costlier).

Interview questions

  • Dynamic vs explicit mapping — which do you use in production?
  • What is mapping explosion and how do you prevent it?
  • Can you change a field's type in an existing index?
  • Difference between object and nested types?

Searching & Relevance

Query DSL: match, term, range, multi_match, phrase, fuzzy

Full-text queries analyze the input; term-level queries match exact indexed terms.

  • Full-text: match (analyze, OR terms by default; operator: and or minimum_should_match to tighten), match_phrase (order + adjacency, slop allows gaps), multi_match (one query, many fields).
  • Term-level: term, terms, range, exists, prefix, wildcard, regexp, ids, fuzzy. No analysis of the input.
  • multi_match types: best_fields (default, best single field wins), most_fields (sum across fields), cross_fields (treat fields as one big field, good for first+last name), phrase, phrase_prefix, bool_prefix.
  • Boost fields with ^: "fields": ["title^3", "body"].
  • fuzziness: "AUTO" allows 0 edits for 1–2 chars, 1 edit for 3–5, 2 edits for longer terms (Damerau-Levenshtein, so a swap counts as 1).
  • range works on numbers, dates (with date math like now-7d/d) and keywords.

Interview questions

  • What is the difference between match and term queries?
  • match vs match_phrase?
  • What are the multi_match types and when do you use cross_fields?
  • How does fuzzy search work in Elasticsearch?

bool query, query vs filter context & caching

Use must/should for relevance, filter/must_not for yes/no constraints that skip scoring and can be cached.

  • bool combines clauses: must (must match, adds score), should (optional, adds score), filter (must match, no score), must_not (must not match, no score).
  • Query context answers “how well does it match?” and computes _score. Filter context answers “does it match?” — yes/no only.
  • Filter context is faster: no scoring, and frequently used filters on larger segments are kept in the node query cache as bitsets.
  • should alone (no must/filter) means at least one should clause must match. With must or filter present, should clauses are optional boosts unless you set minimum_should_match.
  • The shard request cache caches whole results of size: 0 requests (aggregations, counts) until the next refresh changes the shard.
  • constant_score wraps a filter and gives every hit the same score; boosting demotes (rather than excludes) matching docs.

Interview questions

  • What is the difference between query context and filter context?
  • What is the difference between must and filter?
  • How does should behave with and without must?
  • What caches does Elasticsearch use for search?

Relevance scoring: TF-IDF vs BM25

BM25 (default) rewards rare terms and repeated terms, but with saturation and tunable length normalization.

  • TF (term frequency): more occurrences in a doc → more relevant. IDF (inverse document frequency): rarer terms across the index matter more. Field length norm: a match in a short field counts more.
  • Classic Lucene TF-IDF used sqrt(tf), so score kept growing with repetition — easy to game with keyword stuffing.
  • BM25 (default since ES 5.0): idf × tf·(k1+1) / (tf + k1·(1 − b + b·dl/avgdl)). k1 = 1.2 controls TF saturation; b = 0.75 controls how much field length matters.
  • Lucene's BM25 IDF is ln(1 + (N − n + 0.5)/(n + 0.5)), which is never negative.
  • Final score of a bool = sum of its scoring clauses, times boosts. Use explain: true or the _explain API to see the breakdown.
  • Custom ranking: function_score (decay by date/distance, field_value_factor for popularity), script_score, rank_feature, or a rescore phase / learning to rank.

Interview questions

  • How does Elasticsearch calculate relevance?
  • What is the difference between TF-IDF and BM25?
  • What do k1 and b control in BM25?
  • How would you boost newer or more popular documents?

Aggregations: bucket, metric, pipeline

Bucket aggs group docs, metric aggs compute numbers over a group, pipeline aggs compute over other aggs' results.

  • Bucket: terms, date_histogram, histogram, range, filters, composite, geohash_grid. Buckets can hold sub-aggregations.
  • Metric: avg, sum, min, max, stats, value_count, cardinality (approximate, HyperLogLog++), percentiles (approximate, TDigest), top_hits.
  • Pipeline: take another agg's output via buckets_path: derivative, cumulative_sum, moving_fn, avg_bucket, max_bucket, bucket_sort, bucket_selector.
  • Aggregations run on doc values over all docs matching the query (not just the returned page). Use size: 0 when you only need aggs.
  • terms is approximate across shards: each shard returns its top shard_size buckets, so counts can be off; check doc_count_error_upper_bound.
  • To page through all buckets (e.g. every customer), use composite with after_key, not a huge terms.size.

Interview questions

  • What are the types of aggregations?
  • Why can terms aggregation counts be inaccurate?
  • How would you build faceted search (counts per brand, color) next to results?

Pagination: from/size, search_after, PIT, scroll

Use from/size for the first few pages, search_after + PIT for deep or full iteration; scroll is legacy for deep paging.

  • from + size is simple but each shard must build a queue of from + size hits; capped at 10,000 by index.max_result_window.
  • search_after: pass the sort values of the last hit to get the next page. Cost stays constant per page; needs a unique tie-breaker in the sort.
  • Point in time (PIT): a lightweight snapshot of index state (POST /index/_pit?keep_alive=1m). With search_after, pages stay consistent even if refreshes happen. PIT adds an implicit _shard_doc tie-breaker.
  • Scroll: older API that keeps a search context open. Elastic no longer recommends it for deep pagination; use search_after + PIT.
  • search_after can't jump to page 57 — it's for “next page” / infinite scroll and exports. That's also how Google-style UIs avoid deep pages.
  • Close PITs when done (DELETE /_pit); open contexts keep old segments from being deleted.

Interview questions

  • Why is deep pagination with from/size expensive?
  • How does search_after work?
  • What is a point in time and why use it with search_after?
  • Scroll vs search_after?

Operations & Scale

Reindexing, aliases & zero-downtime mapping changes

Read and write through an alias, build a new index with the new mapping, reindex, then swap the alias atomically.

  • An alias is a named pointer to one or more indices. Apps use the alias (products), never the physical name (products-v3).
  • _aliases applies multiple add/remove actions atomically, so clients never see a moment without an index.
  • _reindex copies docs from a source index (or remote cluster) to a destination, optionally with a query, script or ingest pipeline. It reads _source, so _source must be enabled.
  • For large indices run reindex with wait_for_completion=false (returns a task), and slices: auto to parallelize.
  • Writes during reindex: either pause writes, dual-write to old and new, or replay changes since the start time (from the source DB/CDC) after the swap.
  • Other tools: _update_by_query (re-process docs in place, e.g. pick up a new multi-field), _delete_by_query, _split/_shrink/_clone.

Interview questions

  • How do you change a field's mapping in production with zero downtime?
  • What is an index alias and why use it?
  • What does _update_by_query do and when is it enough?

ILM, data streams & hot-warm-cold

Time-series data rolls over into new backing indices and moves to cheaper tiers as it ages, then gets deleted.

  • Data stream: an append-only name (e.g. logs-app-prod) backed by hidden time-based indices. Docs need @timestamp. Writes go to the latest backing index.
  • Rollover creates a new backing index when a condition is met: max_primary_shard_size (e.g. 50gb), max_age, max_docs.
  • ILM (Index Lifecycle Management) phases: hot (indexing + frequent search), warm (read-only, fewer resources), cold (rarely searched, can use searchable snapshots), frozen (searchable snapshots, mostly in object storage), delete.
  • Phase actions include rollover, shrink, forcemerge, allocate/migrate (move to a data tier), searchable_snapshot, readonly, downsample, delete.
  • Hardware: hot nodes = fast SSD and CPU; warm/cold = bigger, cheaper disks; frozen = small local cache over S3/GCS/Azure snapshots.
  • Deleting a whole old index is instant and cheap; deleting docs by query is slow and leaves tombstones until merge.

Interview questions

  • What is ILM and why use it?
  • Explain hot-warm-cold architecture.
  • Data stream vs plain index with an alias?

The ELK / Elastic Stack

Elasticsearch stores and searches, Logstash and Beats/Elastic Agent collect and transform, Kibana visualizes.

  • Elasticsearch: storage, search and aggregations. Logstash: server-side pipeline (inputs → filters like grok → outputs). Kibana: UI for dashboards, Discover, alerting and management.
  • Beats (Filebeat, Metricbeat, …) are lightweight shippers on hosts. Elastic Agent + Fleet is the newer single-agent approach managed centrally.
  • Ingest can also happen inside ES with ingest pipelines (grok, dissect, date, geoip, set, rename) on ingest nodes — often replacing Logstash for simple parsing.
  • Common production setup: shippers → Kafka (buffer) → Logstash → Elasticsearch → Kibana. Kafka absorbs spikes and ES outages.
  • Typical uses: centralized logging, APM, infrastructure metrics, SIEM.

Interview questions

  • What is the ELK stack?
  • Logstash vs ingest pipelines vs Beats?
  • How would you design a logging pipeline for 100 services?

Modern Elasticsearch & Ecosystem

OpenSearch fork & choosing a search engine

OpenSearch is the AWS-led Apache-2.0 fork of Elasticsearch 7.10; APIs are similar but the projects have diverged.

  • In 2021 Elastic moved Elasticsearch and Kibana from Apache 2.0 to SSPL + Elastic License. AWS forked the last Apache-2.0 versions (ES 7.10.2, Kibana 7.10.2) as OpenSearch and OpenSearch Dashboards.
  • In 2024 Elastic added AGPLv3 as an extra license option. OpenSearch moved to the OpenSearch Software Foundation under the Linux Foundation.
  • Core concepts (indices, shards, Query DSL, analyzers, aggregations) are the same; newer features differ (security plugin vs X-Pack, vector engines, ES|QL vs PPL/SQL, retrievers).
  • Client libraries are not interchangeable across major versions; ES 8+ clients check they're talking to Elasticsearch.
  • Alternatives: Apache Solr (also Lucene), Meilisearch/Typesense (simple, typo-tolerant site search), PostgreSQL full-text search (tsvector, GIN) when the data is small and already in Postgres, dedicated vector DBs for pure vector workloads.

Interview questions

  • What is OpenSearch and why does it exist?
  • Elasticsearch vs Solr?
  • When would you not add Elasticsearch to a system?