Elasticsearch: analyzers, the inverted index, doc values and a mapping for homestay search
How Elasticsearch stores a document (analyzers, inverted index, _source, doc values, BKD trees), and a homestay search mapping tested on Elasticsearch 8.15: Vietnamese diacritic folding, object vs nested, a misused range field, shard sizing and syncing from PostgreSQL.
On this page
1. The problem
A homestay search page must ignore Vietnamese accents and filter by price, guests and a 5 km radius within tens of ms. The first mapping used float_range for the average price and an object array for rooms: price sorting was out of order, and "double bed for 1 guest" returned matches that don't exist.
2. Key idea
Start with PostgreSQL (tsvector + GIN, pg_trgm, PostGIS). Add Elasticsearch (ES) when you need relevance scoring, large facets, language processing, or when search load starts hurting the transactional DB. A new document becomes searchable only after the next refresh (every second by default): ES is near real-time.
| Structure | Serves | Default for |
|---|---|---|
| Inverted index | match, term, match_phrase |
text, keyword |
| BKD tree | numeric and date range, geo_distance |
numbers, date, geo_point |
| Doc values | sorting, aggregations | every type except text |
_source |
returning hits, reindexing | every document |
text has no doc values, so it can't be sorted. Sort on name.raw (a keyword); don't turn on fielddata: true.
2.1 What does an analyzer do?
An analyzer is character filters → tokenizer → token filters, run both at index time and at search time. The standard analyzer keeps accents: "Nhà gỗ Đà Lạt" becomes nhà, gỗ, đà, lạt. Add asciifolding and it becomes nha, go, da, lat (including đ → d).
Stripping all accents makes "bàn", "bán" and "bạn" collide. So keep two subfields, one accented and one folded, and boost the accented one.
2.2 How do you pick a field type?
| Type | Use when | Don't use when |
|---|---|---|
text + keyword subfield |
names you search and sort | ids and codes: keyword alone |
long / scaled_float |
a single number: price, rating | a seasonal price range |
long_range |
a range: seasonal price, time window | an average price: sorting breaks |
nested |
object arrays filtered on several fields per element | a single object like host; children that change constantly |
3. In code
Only text that needs ranking goes in must; yes/no conditions go in filter, which is unscored and cached.
GET homestays/_search
{
"query": { "bool": {
"must": [ { "match": { "name": "nhà gỗ" } } ],
"filter": [
{ "term": { "city": "Đà Lạt" } },
{ "range": { "max_guests": { "gte": 2 } } },
{ "terms": { "amenities": ["wifi"] } },
{ "geo_distance": { "distance": "5km", "location": { "lat": 11.94, "lon": 108.44 } } }
] } },
"sort": [ { "_geo_distance": { "location": { "lat": 11.94, "lon": 108.44 }, "unit": "m" } } ]
}
// -> h1, sort = 2180 (m)The Java client builds exactly this tree; when debugging, read the JSON it sends.
Syncing from PostgreSQL and changing a mapping without downtime
PostgreSQL is the source of truth. Avoid dual writes (the DB commits, ES fails, and they drift forever). Use an outbox (write an event row in the same transaction; a worker sends it to ES) or CDC (Debezium reads the WAL through Kafka).
- Idempotent writes: use
homestay_idas_id. - Stop late old events:
?version=17&version_type=external; ES rejects a version less than or equal to the current one withversion_conflict_engine_exception, and the consumer skips it instead of retrying. - Field types and the primary shard count can't change in place. Always read and write through an alias
homestays→homestays_v1; to change the mapping, createv2, reindex, and swap the alias atomically with_aliases. - Per-night availability changes with every booking: keep it in PostgreSQL. ES narrows to a few hundred ids; the DB checks the calendar and locks the room when booking.
4. Working with AI
Hand to AI: mappings, queries, _bulk loading scripts.
Check in AI-written code:
- The mapping has
dynamic: "strict"; fields used for sorting or aggregations are nottext. - A single number uses a numeric type, not a range field.
- Object arrays filtered on several conditions are
nested, and the query usesnested. - Yes/no conditions sit in
filter, notmust. - No
?refresh=trueafter every write; code reads and writes through an alias.
5. Exercises
Exercise 1: Read a wrong result
The query "room for 4 guests with a double bed" returns a homestay with only {bed: double, guests: 2} and {bed: bunk, guests: 4}. Explain and fix it.
Solution to Exercise 1
rooms is an object, flattened into rooms.bed = [double, bunk] and rooms.guests = [2, 4], so "double" matches the first element and "4" matches the second.
Fix: change rooms to nested and use a nested query. The type can't change in place, so create homestays_v2, reindex and swap the alias. If you only need this one filter, precompute a keyword field room_types: ["double:2", "bunk:4"] and filter with term "double:4".
Exercise 2: Pick where reviews live
The AI suggests putting reviews inside the homestay document as nested. Reviews have Vietnamese text, stars and a date; the search page needs the average rating. Choose and explain.
Solution to Exercise 2
Not nested: reviews are many and keep arriving, and each new one reindexes the whole homestay with all its hidden documents. Use a separate index reviews_v1 with homestay_id, stars (byte), content (accented text plus a folded subfield) and created_at.
Compute the average and count in PostgreSQL and write them to the homestay's rating and review_count, so the search page never queries the review index. The choice changes if each homestay has only a few fixed reviews.
Summary
- Inverted index to search, doc values to sort and aggregate, BKD tree for ranges and geo.
textto search,keywordto filter and sort; need both, use a multi-field.- Accent-insensitive:
asciifoldingplus an accented field to boost. - Filtering per array element:
nested. - ES is a lagging copy via outbox or CDC; change mappings through an alias.
Read more: Hybrid search: full-text, vectors and rerank.
References
Practice interview questions on this topic
- What is an inverted index in Elasticsearch, and how do text and keyword differ?
- In Elasticsearch, how do must and filter differ, when do you use nested, and why isn't a new document searchable immediately?
- How do you correctly sync data from PostgreSQL/MySQL to Elasticsearch?
- How do you change the analyzer/mapping of a live Elasticsearch index, and choose the shard count?
Comments
Community rules