SteelReed

Search

Search posts, questions…

7. System Design

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.

18 Nov 20268 min readMid

–

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.

JSON
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_id as _id.
  • Stop late old events: ?version=17&version_type=external; ES rejects a version less than or equal to the current one with version_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, create v2, 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 not text.
  • A single number uses a numeric type, not a range field.
  • Object arrays filtered on several conditions are nested, and the query uses nested.
  • Yes/no conditions sit in filter, not must.
  • No ?refresh=true after 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.
  • text to search, keyword to filter and sort; need both, use a multi-field.
  • Accent-insensitive: asciifolding plus 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

All Data Modeling & Scaling questions →

Loading comments…
Next on the roadmapThird-party integration: choosing a provider, sync versus async, webhooks and an anti-corruption layer