Elasticsearch interview questions and answers, from analyzers to cluster health
Elasticsearch interview questions start with the inverted index and analyzers, because almost every search bug traces back to how text was tokenized at index time and at query time. From there interviewers move to mappings (text versus keyword), shards and replicas, why search is near real-time, how BM25 scores a match, and how to page through millions of hits. Senior and engineer-level rounds add cluster health, shard sizing, reindexing without downtime and relevance tuning.
By Evin JohnPublished 8 min read
Where Elasticsearch shows up in interviews
Elasticsearch questions come from three directions. Backend developers who build product search get asked about mappings, analyzers and relevance. Platform and SRE candidates who run clusters for logs get shard sizing, node roles, index lifecycle and recovery. And in system design rounds, anyone who proposes "put it in Elasticsearch" for search or autocomplete should expect follow-ups on how data gets there and how stale it can be.
- Concept screenInverted index, analyzers, text versus keyword, shards and replicas, what near real-time means.
- Hands-on roundWrite a mapping and a few queries for a product catalog or log index: a bool query, a filter, an aggregation, maybe autocomplete.
- Operations or design roundA yellow or red cluster, a slow query, a mapping that must change on a live index, or search as part of a larger system.
Fundamentals: documents, the inverted index and analysis
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is an inverted index? | Core data structure | For each term, a sorted list of the documents (and positions) that contain it. A search looks up the query's terms and combines their lists, instead of scanning every document. |
| What does an analyzer do? | Text processing | Character filters clean raw text, a tokenizer splits it into tokens, and token filters change them: lowercase, stop words, stemming, synonyms. The output tokens are what gets indexed. |
| Why must index-time and search-time analysis match? | Matching | If the index stores "running" stemmed to "run" but the query is not stemmed, the terms never meet. A separate search_analyzer is fine when it is deliberate, as with edge n-grams for autocomplete. |
| How do you see what an analyzer produces? | Debugging | The _analyze API with the analyzer or field and a sample string returns the tokens. It is the first tool for any "why does this not match" question. |
| What is the difference between match and term queries? | Query types | match analyzes the input and searches the resulting terms; term looks for the exact term with no analysis. A term query against a text field often finds nothing because the indexed tokens were lowercased. |
| What is match_phrase for? | Positions | It requires the terms in order and adjacent (slop allows gaps), using the positions stored in the index. |
| How is Elasticsearch related to Lucene? | Architecture | Each shard is a Lucene index. Elasticsearch adds distribution, replication, the REST API, aggregations and cluster management on top. |
| How is it different from a relational database? | Fit | It is built for search and analytics over denormalized documents, with eventual visibility and no multi-document transactions. Keep the source of truth in a database and index into Elasticsearch. |
Mappings: text, keyword and getting the schema right
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"analysis": {
"filter": {
"autocomplete_filter": { "type": "edge_ngram", "min_gram": 2, "max_gram": 15 }
},
"analyzer": {
"autocomplete": {
"type": "custom",
"tokenizer": "standard",
"filter": ["lowercase", "autocomplete_filter"]
}
}
}
},
"mappings": {
"dynamic": "strict",
"properties": {
"name": {
"type": "text",
"fields": {
"raw": { "type": "keyword" },
"suggest": { "type": "text", "analyzer": "autocomplete", "search_analyzer": "standard" }
}
},
"description": { "type": "text" },
"brand": { "type": "keyword" },
"price": { "type": "scaled_float", "scaling_factor": 100 },
"in_stock": { "type": "boolean" },
"created_at": { "type": "date" },
"variants": {
"type": "nested",
"properties": {
"color": { "type": "keyword" },
"size": { "type": "keyword" }
}
}
}
}
}- What is the difference between text and keyword? text is analyzed into terms for full-text search. keyword stores the whole value as one term, used for exact filters, sorting and aggregations. A product name often needs both, through a multi-field.
- What does dynamic mapping do with a new string field? By default it maps the field as text with a keyword subfield (ignoring long values). Convenient in development, wasteful and surprising in production.
- What is a mapping explosion? Dynamic mapping creating thousands of fields, often from user-supplied keys in a JSON blob, which bloats cluster state and slows the cluster. Use strict or false dynamic settings, the flattened type, or a key-value structure.
- Can you change a field's type on an existing index? Not in place. Create a new index with the right mapping, reindex into it, and switch an alias. Adding new fields is fine.
- What is the difference between object and nested types? An array of objects is flattened, so a query for color red and size small can match a document where those came from different variants. nested indexes each object as a hidden document and needs nested queries, at some cost.
- What are doc_values and fielddata? doc_values are an on-disk columnar structure for sorting and aggregations, on by default for most non-text fields. Aggregating on a text field needs fielddata in heap, which is off by default for good reason.
Shards, replicas and how a write becomes searchable
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is the difference between a primary and a replica shard? | Distribution | Primaries hold the data partitions and take writes first. Replicas are copies on other nodes, used for failover and to serve reads. A replica never sits on the same node as its primary. |
| How does Elasticsearch pick the shard for a document? | Routing | It hashes the routing value, the document id by default, and maps it to a primary shard. That is why the primary count cannot simply change: every document's location would move. |
| How many primary shards does a new index get? | Defaults | One by default in recent major versions, configurable at creation. Replicas default to one and can be changed at any time. |
| Why is search called near real-time? | Refresh | New documents go to an in-memory buffer and the translog. A refresh, every second by default on active indices, writes a new segment that search can see. A get by id can see the document sooner. |
| What is the translog for? | Durability | A write-ahead log that replays acknowledged operations not yet committed to Lucene segments after a crash. A flush commits segments and trims it. |
| What happens to deleted or updated documents? | Segments | Segments are immutable, so a delete is a marker and an update is a delete plus a new document. Merges later remove the dead entries and reclaim space. |
| How would you speed up a large bulk load? | Ingestion | Use the bulk API in batches, raise or disable the refresh interval during the load, set replicas to zero and add them back after, and let Elasticsearch generate ids when you can. |
| How do you avoid lost updates when two writers edit one document? | Concurrency | Optimistic concurrency with if_seq_no and if_primary_term; a conflicting write gets a 409 and the client retries with fresh data. |
Queries, relevance and aggregations
{
"query": {
"bool": {
"must": [
{ "multi_match": { "query": "trail running shoe", "fields": ["name^3", "description"] } }
],
"should": [
{ "match_phrase": { "name": { "query": "trail running", "boost": 2 } } }
],
"filter": [
{ "term": { "in_stock": true } },
{ "range": { "price": { "lte": 150 } } },
{
"nested": {
"path": "variants",
"query": {
"bool": {
"filter": [
{ "term": { "variants.color": "blue" } },
{ "term": { "variants.size": "42" } }
]
}
}
}
}
]
}
},
"aggs": {
"brands": { "terms": { "field": "brand", "size": 10 } }
},
"size": 20,
"sort": ["_score", { "created_at": "desc" }]
}- What is the difference between query context and filter context? Clauses in must and should compute a relevance score. Clauses in filter and must_not only include or exclude, do not score, and their results can be cached. Put yes-or-no conditions in filter.
- How does BM25 score a document? Term frequency in the field (with diminishing returns), inverse document frequency (rare terms count more) and field length normalization (a match in a short title outweighs one in a long body). It has been the default similarity for years.
- Why can scores differ for the same query across shards? Term statistics are computed per shard by default, so small or uneven shards skew IDF. More data per shard evens it out; dfs_query_then_fetch trades speed for global statistics.
- How do you tune relevance? Field boosts, phrase boosts in should, function_score or rank features for popularity and recency, synonyms, and a judged query set to measure changes instead of guessing. The explain API shows why one document beat another.
- Are terms aggregation counts exact? Not always across several shards: each shard returns its top buckets, so counts for the tail can be off. Raising shard_size helps; the response reports an error bound.
- How would you build autocomplete? An edge n-gram subfield like the mapping above, or the completion suggester for prefix-only cases, or search_as_you_type. Debounce on the client and cap results.
- Can Elasticsearch do vector search? Recent versions support dense_vector fields with approximate nearest-neighbor search, and many teams combine it with keyword scoring. Ask which version the team runs before going into detail.
Operations and senior scenarios
| Question | What it tests | What a strong answer shows |
|---|---|---|
| The cluster is yellow. What does that mean? | Health | All primaries are assigned but at least one replica is not, often on a single-node cluster or after a node left. Search works; redundancy is reduced. Allocation explain shows why. |
| The cluster is red. What now? | Incidents | At least one primary is unassigned, so some data is unavailable. Find the shard with allocation explain, bring back the node or disk, and restore from a snapshot if the data is gone. |
| How do you size shards? | Capacity | Avoid thousands of tiny shards, each of which costs heap and cluster state, and avoid huge ones that recover slowly. A common guideline is shards in the tens of gigabytes, then test with real data. |
| How do you change a mapping with no downtime? | Migrations | Create a new index, reindex (or dual-write) into it, then move an alias from old to new in one atomic call. The application only ever queries the alias. |
| How do you manage time-based log data? | Lifecycle | Data streams or rollover indices with index lifecycle management: hot nodes for recent writes, cheaper tiers for older data, then deletion. Queries hit only the indices they need. |
| Why is from plus size bad for deep pages? | Pagination | Each shard must collect from plus size hits and the coordinator sorts them all. The default result window caps it at 10,000. Use search_after with a point in time for deep or stable paging. |
| How do you keep Elasticsearch in sync with the main database? | Data flow | Change data capture or an outbox feeding a queue, with idempotent upserts by id and a periodic full reindex to repair drift. Accept seconds of lag and design the UI for it. |
| What node roles exist, and why separate them? | Topology | Master-eligible nodes manage cluster state, data nodes store shards, ingest nodes run pipelines, coordinating nodes fan out queries. Dedicated masters keep elections stable on large clusters. |
Fictional example
- Interviewer
- The product name field was created by dynamic mapping months ago, so it is text with a name.keyword subfield. The search box sends a term query on name.keyword. What is going on?
- Candidate
- name.keyword is a keyword field, so it holds the exact string "iPhone 15 Pro" as one term, case and spaces included. A term query does no analysis, so only a byte-for-byte match finds it, and a single word such as "iphone" never would. The fix is to search the analyzed name field with a match query, so the standard analyzer lowercases and splits the text on both sides. I would run _analyze on the field to show the tokens, then change the query, and keep name.keyword for sorting and exact filters. If users type partial words, I would add an edge n-gram subfield, which needs a new index and a reindex behind an alias, because analyzers on existing fields cannot change in place.
Two-week Elasticsearch practice plan
- Days 1 to 3: run a local single-node cluster, index a few thousand products, and use _analyze on every field you query.
- Days 4 to 6: write explicit mappings with multi-fields and nested types, then break them with dynamic mapping and see what changes.
- Days 7 to 9: write bool queries with filters, aggregations and a relevance tweak, and use explain to justify each ranking.
- Days 10 to 12: practice an alias-based reindex, a bulk load with refresh disabled, and search_after paging.
- Days 13 and 14: rehearse the yellow and red cluster questions and a search design answer out loud.
Search usually sits next to other stores in a design. Compare it with wide-column storage in Cassandra interview questions and key-value access patterns in DynamoDB interview questions. The system design side is in search autocomplete design, and document stores are covered in MongoDB interview questions.
Mapping and relevance answers are easier to improve when you can reread them. Natively, an AI interview assistant for Mac and Windows, transcribes a mock round on your computer, so you can check whether you named the analyzer before jumping to a fix. In practice it can read a query or a cluster health output from a screenshot and suggest what to look at, and with Pro or the free trial it considers the résumé and job description you add. Transcripts and notes stay saved for review.
Questions people ask
What Elasticsearch questions are asked in interviews?
Expect the inverted index, analyzers and the _analyze API, text versus keyword mappings, nested fields, shards, replicas and routing, refresh and near real-time search, bool queries and filter context, BM25, aggregations, deep pagination and cluster health.
What is the difference between text and keyword in Elasticsearch?
A text field is analyzed into terms for full-text search. A keyword field stores the exact value as one term for filters, sorting and aggregations. Many fields use both through a multi-field.
What are shards and replicas in Elasticsearch?
Primary shards split an index's data across nodes, and their count is set when the index is created. Replicas are copies of primaries on other nodes that provide failover and extra read capacity, and their count can change at any time.
Why is Elasticsearch called near real-time?
A newly indexed document becomes searchable only after a refresh writes a new segment, which happens every second by default on active indices. Until then a search may not return it.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
