Elasticsearch & Distributed Search Engine Master Interview Bank
Apache Lucene inverted index internals, term dictionary & posting lists, cluster topology, sharding & replica routing, BM25 scoring, and aggregations.
Curriculum Roadmap & Learning Path
3 StagesPart 1: Basic & Foundational Concepts (Junior / Entry-Level)
10 QuestionsWhat is Elasticsearch and how does it relate to Apache Lucene?
Elasticsearch is a distributed, JSON-based, RESTful search and analytics engine built on top of Apache Lucene: Apache Lucene: A low-level Java search library that implements inverted indexing, tokenization, and search algorithms on a single machine.
What are Clusters, Nodes, Indices, and Documents in Elasticsearch?
Cluster: A collection of one or more connected servers (nodes) that collectively hold your entire data and provide federated search and indexing • Node: A single running instance of Elasticsearch running within the cluster • Index: A logical namespace that groups related documents (similar to a table in SQL, but optimized for search).
What is an Inverted Index and why is it so fast for text search?
It splits document text into individual vocabulary terms, standardizes them, and maintains a sorted list of every document ID where each term • Searching for words becomes an instantaneous O(1) dictionary lookup, followed by intersecting or unioning document ID lists!.
What is the difference between `text` and `keyword` data types?
text: Analyzed and tokenized into individual terms • keyword: Not analyzed; stored exactly as an unaltered string.
What is the difference between Primary Shards and Replica Shards?
Primary Shard: A self-contained instance of a Lucene index holding a fraction of the index's total data • Replica Shard: An exact copy of a primary shard.
What are the basic Elasticsearch CRUD REST API endpoints?
Create / Index: PUT /my-index/doc/1 or POST /my-index/doc • Read: GET /my-index/doc/1 • Update: POST /my-index/update/1 (partial updates) • Delete: DELETE /my-index/_doc/1.
What is the difference between a Match Query and a Term Query?
Match Query: The query string is passed through the analyzer (lowercased, stemmed, tokenized) before searching the inverted index • Term Query: The query string is looked up verbatim without any analysis.
What is Dynamic Mapping and what are its risks in production?
Dynamic mapping automatically detects field types from incoming JSON and creates mapping definitions dynamically: Risk (Mapping Explosion): If users send arbitrary or unbounded JSON keys (e.g. user-generated tags as key names), thousands of new fields are.
What is the Match Phrase query?
A Match Phrase query analyzes the input text and matches documents that contain the exact sequence of terms in the exact specified order: Supports a slop parameter (e.g. slop: 2), which allows terms to be separated by up to N intervening words while still matching.
How does the Bulk API work and why is it used for high-volume indexing?
The _bulk API executes multiple index, create, update, or delete operations in a single network request: Avoids the massive overhead of establishing individual HTTP request-response cycles • Dramatically increases indexing throughput (often 10x-50x faster than individual requests) • Accepts newline-delimited JSON (NDJSON) format.
Part 2: Core Architecture & Implementation (Mid-Level)
10 QuestionsHow does the Bool Query work with must, filter, should, and must_not clauses?
The Bool query is the primary compound query in Elasticsearch: must: Clause must appear in matching documents • filter: Clause must appear in matching documents, but does not compute relevance scores and results are automatically cached in memory • should: Acts as an OR condition.
How does the BM25 relevance ranking algorithm calculate scores?
Okapi BM25 is the default scoring algorithm in Lucene / Elasticsearch, improving upon classical TF-IDF: Term Frequency (TF): How often the term appears in the document • Inverse Document Frequency (IDF): Rare terms across the index get much higher weight than common terms like "the" or "is".
What is an Analyzer and what are its three components (Char Filters, Tokenizers, Token Filters)?
An analyzer converts raw text into a stream of indexed terms: Character Filters: Pre-processes raw text before tokenization (e.g. stripping HTML tags htmlstrip, mapping & to and) • Tokenizer: Splits text into individual tokens (e.g. standard tokenizer splits by whitespace and punctuation).
What are Metric Aggregations vs Bucket Aggregations?
Aggregations provide real-time analytics across documents: Metric Aggregations: Calculate mathematical summaries over a field: avg, sum, min, max, cardinality (distinct count using HyperLogLog++), percentiles.
How does Elasticsearch route a document to a specific shard?
When indexing a document, Elasticsearch determines the target primary shard using a hash formula: shard = \text{hash}(routing) \pmod{\text{number\of\primary\shards}}: By default, routing is the document's id.
What are the pagination methods in Elasticsearch: from/size vs search_after vs scroll?
from + size: Traditional offset pagination • search_after (Recommended): Cursor-based pagination using the sort values of the last document • scroll API: Creates a point-in-time snapshot for streaming massive datasets (e.g. reindexing millions of records).
How do Index Templates and Component Templates work?
Templates automatically apply settings (shard count, replica count) and mappings to newly created indices that match a name pattern (e.g. logs-*): Component Templates: Reusable modular building blocks (e.g. a standard timestamp mapping or common security settings).
What is the difference between `nested` objects and `flattened` objects?
Standard Object Array: Elasticsearch flattens arrays of objects, losing individual object boundaries (e.g. user.first = ["Alice", "Bob"] and • nested Data Type: Indexes each array item as a hidden separate Lucene document, preserving object boundaries for precise multi-field queries (at.
How does Synonym filtering work in search?
Synonym token filters map alternative words to the same concept (e.g. ["couch", "sofa"] or ["laptop", "notebook"]): Index-time Synonyms: Expands synonyms when writing to disk • Search-time Synonyms (Best Practice): Expands synonyms dynamically only when the query runs.
How does Elasticsearch achieve High Availability during node failure?
Elasticsearch ensures that a primary shard and its corresponding replica are never placed on the same physical node • If Node A holding Primary Shard 0 crashes • The Master node detects the heartbeat timeout • The Master immediately promotes the Replica Shard 0 on Node B to be the new Primary Shard.
Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
30 QuestionsHow do Lucene Segments, Immutability, and Segment Merges work?
Immutability: Once written to disk, a segment is never modified • Deletes: When an item is deleted or updated, it is marked as deleted in a .del bitset file (soft delete); the old data remains on disk.
What is the difference between a Refresh and a Flush in Elasticsearch?
Refresh (refresh_interval, default 1s): Writes in-memory indexing buffers to a new Lucene segment in the OS file system cache • Flush: Executes a Lucene commit point.
What are the Node Roles in modern Elasticsearch clusters?
Separating node roles prevents resource contention at scale: master (Master-Eligible): Manages cluster state, shard allocation, index creation • data: Stores shard data and executes query/aggregation workloads • ingest: Runs ingestion pipelines (grok parsing, enrich, date transforms) before indexing.
What is Index Lifecycle Management (ILM) and how do its 5 phases work?
ILM automates the aging of indices across hardware tiers to minimize infrastructure cost: Hot: Active write and read traffic on high-performance NVMe SSDs • Warm: No new writes; query traffic continues on cheaper SSDs • Cold: Infrequent queries; stored on cheap magnetic disks or backed by searchable snapshots in S3.
How do you prevent OutOfMemory (OOM) and manage JVM Heap in Elasticsearch?
The 50% Rule: Never allocate more than 50% of physical system RAM to Elasticsearch JVM Heap (max 31 GB to keep Compressed Ordinary Object • The remaining 50% RAM must be left free for the OS File System Cache so Lucene can cache index segments in memory.
What is the difference between `doc_values` and `fielddata`?
Both are columnar data representations used for sorting and aggregations: doc_values: On-disk columnar store created at index time for all non-analyzed fields • fielddata: In-memory columnar data structure loaded dynamically into JVM heap when aggregating on analyzed text fields.
How does Elasticsearch achieve Master Node Consensus and prevent Split-Brain?
In Elasticsearch 7.x+, split-brain is prevented using a Raft-inspired master election algorithm: Requires a strict quorum: floor(N / 2) + 1 master-eligible nodes must agree • Master nodes maintain voting configurations that automatically adapt during node scale-up or maintenance.
How does the Write Path work in a distributed Elasticsearch cluster?
Client sends write request to any node (Coordinating Node) • Coordinating node determines the Primary Shard location via hash(routing) • Request forwards to node holding the Primary Shard • Primary validates the document, writes locally, and forwards the write in parallel to all in-sync Replica Shards.
How does the Read / Search Path work in Elasticsearch (Scatter-Gather)?
Query Phase (Scatter): Coordinating node broadcasts search query to a primary or replica shard for every shard in the index • Fetch Phase (Gather): Coordinating node merges all shard results, sorts them to determine the global top K, and sends targeted requests only to.
How do you optimize Elasticsearch for Maximum Indexing Throughput?
Use the bulk API with batches of 5-15 MB • Increase index.refreshinterval from 1s to 30s or disable it (-1) during bulk ingestion • Set numberofreplicas to 0 during initial data loads, restoring replicas afterward • Increase indexing buffer size (indices.memory.indexbuffersize: 20%).
What is the difference between Dense Vector search in Elasticsearch and traditional search?
Elasticsearch 8.x supports a native dense_vector field type using HNSW indexing: Allows running exact lexical queries (BM25) and approximate semantic vector search within the exact same query.
What is Cross-Cluster Search (CCS) and Cross-Cluster Replication (CCR)?
CCS (Cross-Cluster Search): Enables a single coordinating node to execute federated queries across multiple independent clusters located in • CCR (Cross-Cluster Replication): Unidirectional active-passive replication of indices from a leader cluster to a follower cluster for disaster.
What are Searchable Snapshots and how do they reduce cold storage costs by 80%?
Searchable snapshots allow searching read-only index snapshots stored directly in Amazon S3, Azure Blob, or Google Cloud Storage: Nodes download only small index headers and pull data blocks into local cache on demand • Eliminates the need to attach expensive persistent SSDs to cold and frozen data nodes.
How do you troubleshoot high CPU or long Garbage Collection pauses in Elasticsearch?
Run GET /nodes/hotthreads to inspect which Java threads are consuming CPU (e.g. Lucene merge, query execution, regex) • Check thread pool rejections via GET /cat/threadpool?v • Inspect slow logs (elasticsearchindexslowlog.log and elasticsearchsearchslowlog.log).
When should you NOT use Elasticsearch?
Primary transactional system of record with ACID multi-table updates: Elasticsearch does not support ACID multi-document transactions or foreign • Deep relational data modeling: Joining multiple tables requires denormalization or slow application-side joins.
Lucene Inverted Index Deep Dive: Term dictionary, Term index (FST), and Postings lists with Skip lists.
Term Index (FST - Finite State Transducer): Stored in RAM • Term Dictionary: Alphabetically sorted list of all unique terms stored on disk • Postings Lists: Linked lists of Document IDs containing the term, along with term frequencies and byte offsets for phrase searches.
Doc Values vs Fielddata: Memory tradeoffs, column-oriented storage, and sorting/aggregations architecture.
The inverted index is optimized for search ("find documents matching 'kubernetes'"), but terrible for sorting or aggregations ("group by category and calculate average price"): Doc Values: On-disk, column-oriented data structure built at index time for non-analyzed fields (keyword, numeric, date).
Reindexing Patterns and Zero-Downtime Index Migrations: Index Aliases and the `_reindex` API.
Because Lucene inverted indexes are immutable, changing field data types or analyzers requires creating a new index and reindexing documents: Index Aliases: Never point applications directly to a raw index name (ordersv1) • Zero-Downtime Reindex Workflow • Create new index ordersv2 with updated mapping.
Aggregations Deep Dive: Bucket aggregations, Metric aggregations, and Precision Threshold in `cardinality`.
Bucket Aggregations: Group documents into sets/buckets (e.g. terms, datehistogram, range) • Metric Aggregations: Compute mathematical metrics over document sets (e.g. avg, sum, min, percentiles) • Cardinality Aggregation (HyperLogLog++): Counting unique visitors over billions of records.
Deep Pagination at Scale: `from`/`size` limit vs `search_after` vs Scroll API.
from / size (The 10,000 Limit): Requesting from: 100000, size: 10 forces every shard to fetch 100,010 documents into memory and ship them to the • search_after (Recommended for Live Pagination): Uses the sort values of the last retrieved document as an index cursor • Scroll API: Designed exclusively for batch data exports (ETL).
Shard Sizing and Allocation: Why 20GB-50GB per shard is the golden rule and diagnosing "Too many shards".
Every Elasticsearch shard is a full Apache Lucene index requiring its own file descriptors, term indices, and memory buffers: The Golden Rule: Aim for primary shard sizes between 20 GB and 50 GB for logs/time-series data, and 10 GB to 30 GB for search catalogs.
Index Lifecycle Management (ILM): Hot, Warm, Cold, Frozen, and Delete tiers automation.
ILM automates storage tiering as data ages, slashing infrastructure costs by 70%: Hot Tier: High-speed NVMe SSDs • Warm Tier (after 7 days): Rolled over, read-only index • Cold Tier (after 30 days): Read-only searchable snapshots stored directly on AWS S3 / GCS • Frozen Tier (after 90 days): Fully decoupled object storage cache.
Query Context vs Filter Context: Why filters use bitsets and avoid scoring, boosting search performance.
Query Context ("query": { "match".. • Filter Context ("filter": { "term".. • Bypasses scoring entirely • Generates compact in-memory Bitsets (Roaring bitmaps) that are cached automatically in the Node Query Cache.
Parent-Child (`join` field) vs Nested Objects (`nested` type): Architectural tradeoffs.
nested Objects: Flat arrays of objects are indexed as separate hidden Lucene documents stored in contiguous disk blocks • Fast read/query performance • Downside: Updating a single child item requires re-indexing the entire root parent document and all siblings!
Elasticsearch Node Roles: Master-eligible, Data, Ingest, Coordinating-only, and Machine Learning.
In large clusters, separating node responsibilities guarantees stability: master (Dedicated Master Nodes): 3 lightweight nodes that manage cluster state, shard routing, and index mappings • data: Store Lucene shards and execute data queries/indexing.
Circuit Breakers in Elasticsearch: Fielddata circuit breaker, Parent circuit breaker, and preventing OOM heap crashes.
Circuit breakers protect nodes from running out of JVM heap memory and crashing during aggressive queries: Parent Circuit Breaker (indices.breaker.total.userealmemory: true): Trips if total allocated JVM memory exceeds 95% of heap, rejecting incoming.
Custom Analyzers: Character filters, Tokenizers, and Token filters (synonyms, stemming).
An Analyzer processes raw text into inverted index tokens through 3 sequential stages: Character Filters: Strips HTML tags (htmlstrip) or normalizes characters (mapping) • Tokenizer: Splits text stream into individual tokens (e.g. standard breaks on punctuation/whitespace; edgengram creates autocomplete character.
Elasticsearch Cluster Recovery and Peer Recovery: Translog retention, shard sync, and fast cluster restarts.
When a node restarts or a shard moves between nodes: Translog (Transaction Log): Lucene commits data to disk periodically (every 30 minutes or 512MB) • Peer Recovery: The primary shard transfers missing operations from its Translog to the replica shard over the network.
Security and RBAC: TLS encryption, Document-Level Security (DLS), and Field-Level Security (FLS).
Enterprise security enforcement inside the Elasticsearch engine: Transport TLS (Port 9300) & HTTP TLS (Port 9200) • Document-Level Security (DLS): Evaluates a query template against the user's role • Field-Level Security (FLS): Masks sensitive fields.
Hybrid Search with Reciprocal Rank Fusion (RRF): Combining BM25 keyword matching with kNN vector search scores.
Keyword search (BM25) is great for exact identifiers and domain terminology; semantic vector search is great for conceptual meaning and typo tolerance: Reciprocal Rank Fusion (RRF): A state-of-the-art rank aggregation algorithm that merges the ranked lists of lexical search and dense vector kNN.