Elasticsearch
medium 34 minElasticsearch is a distributed search and analytics engine built on Apache Lucene.
See it run
How a document becomes safe and then searchable, how a search asks every shard, and what a lost node does.
Operations
Write, then refresh
One document goes to a primary and its replica. It is safe before it can be found.
Step 1 of 5
Route
shard 1
The hash of id p7 modulo 3 is 1. Its primary is on node 2.
Step 1: Route
shard = hash(doc.id) % number_of_shardsprimary(shard).apply(doc) # buffer + translogfor r in in_sync_replicas(shard): r.apply(doc)fsync_translogs()answer("201 Created") # safeevery("1s", refresh) # now searchable- Waits for
- All in-sync copies
- Watch out for
- 1 s delay
- GET by id
- sees it at once
refresh=wait_for makes one request wait for the next refresh. Forcing a refresh on every write makes many tiny segments.
In the real world
The same elasticsearch doing real jobs. Pick one and step through it.
Search for laptop, then choose Dell, without losing the other brands.
Step 1 of 3
Search
| Dell | HP | Lenovo | hits shown | |
|---|---|---|---|---|
| no choice | 50 | 30 | 20 | 100 |
100 laptops are found. The terms aggregation counts the brands.
Step 1: Search
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A term query on a text field
majorThe index holds lower case terms, the query is not changed, so nothing is found.
Wrong{"term": {"title": "Active"}}Right{"match": {"title": "Active"}}{"term": {"status": "Active"}} # keywordThe only copy of the data
criticalThere are no transactions over documents, and a wrong mapping means building everything again.
Wrongsave_order(elasticsearch)Rightsave_order(database) # then the change stream feeds the indexThousands of tiny shards
majorEvery shard costs memory, and every search visits each one.
Wrongindex_per_customer_per_day(shards=5)Rightdata_stream(rollover="50gb per primary shard")Deep pages with from and size
majorEach shard must send all earlier hits again.
Wrongsearch(from_=10000, size=20)Rightsearch(size=20, search_after=last_sort, pit=pit)Refresh after every write
minorIt makes many small segments and slows indexing.
Wronges.index(..., refresh=True)Rightes.index(..., refresh="wait_for") # only where needed
Interview tips
How to explain it
- Each shard is a small search engine.
- Writes: primary, replicas, translog, then refresh.
- Searches: ask all shards, merge.
Before production
- Explicit mappings and aliases.
- Shards of 10 to 50 GB.
- Three master-eligible nodes.
- Snapshots and a tried restore.
Reach for it when
- People search words and expect ranking.
- Filters need counts.
- Logs are kept and searched by time.
Be careful when
- Documents change constantly.
- Readers must see their own write at once.
- The data is small.