Muhammad Fari Madyan
Hire me
Firestore & Search · part 6 of 6

Firestore, Caching & Search Part 6: Search Relevance and Operations — Business Signals, Multilingual Search, nDCG & Elasticsearch on GCP

Part six and the end of a Firestore, Caching & Search series that opens with a quiz: combining text scores with popularity, rating and freshness through function_score, per-language fields, autocomplete with search_as_you_type, measuring quality with zero-result rate and nDCG@10, lessons from a semantic search project, and Elasticsearch shards, replicas and snapshots on GCP.

Muhammad Fari Madyan

· 13 min read

Baca dalam Bahasa Indonesia →

Opening: A Technically Correct First Result

A user types "tidur cepat" ("fall asleep fast"). The first result: a track titled "Cara Cepat Tidur Siang di Kantor" ("A Quick Way to Nap at the Office"), 3 minutes, low rating, uploaded four years ago, and almost never played. The most popular sleep meditation in the app sits in sixth place.

Technically, Elasticsearch is not wrong. That title does contain both search words, and its text score is the highest. But users are not looking for matching words. They are looking for the track most likely to help them sleep tonight.

Part 5 made sure the index stays in sync with the database. This final part answers the next question: are the search results good, how do you measure that, and how do you operate Elasticsearch on GCP.


Warm-Up Quiz: Do You Still Remember?

Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.

Question 1. During a load test, semantic queries that usually take 60–80 ms suddenly take only 2 ms. The most likely explanation?

  • A. The model gets faster after "warming up"
  • B. The load test repeats the same queries, and what is being measured is the inference cache, not the model
  • C. Elasticsearch skips the model for short queries
Show the answer to question 1

B. This happened in my own project: 1,286 of the first 1,920 inferences were served by the inference cache. With the cache off, the limit was about 13 inferences per second. Section 5 has the full numbers.

Question 2. 8% of searches find nothing (an 8% zero-result rate). What does that signal?

  • A. Elasticsearch is short on memory
  • B. There are synonyms, typos, languages, or content users look for that are not handled yet
  • C. Normal, nothing to look at
Show the answer to question 2

B. The list of zero-result queries is the cheapest to-do list for improving search: add synonyms, fix analyzers, or tell the content team that a topic is in demand but missing.

Question 3. What does nDCG@10 measure?

  • A. How many milliseconds a search takes
  • B. Whether the best documents are at the top, with graded relevance
  • C. What percentage of documents are indexed
Show the answer to question 3

B. nDCG@10 gives more weight to relevant documents near the top, and tells "very relevant" apart from "somewhat relevant". It is 1.0 for a perfect order. Section 4 has a worked example.

Question 4. The shard size guidance in the Elasticsearch docs is...

  • A. As small as possible, say 100 MB, so it is fast
  • B. Between 10 GB and 50 GB, and under 200 million documents per shard
  • C. One shard per document
Show the answer to question 4

B. Too many small shards burden the cluster (oversharding). Shards that are too large slow down searches and recovery. For a track catalog, one primary shard is often enough. The maths is in section 6.

Question 5. Autocomplete as the user types "med" is best built with...

  • A. The same query as full search, sent on every keystroke
  • B. A dedicated field or index like search_as_you_type, because the needs differ from full search
  • C. LIKE 'med%' in the database
Show the answer to question 5

B. Autocomplete needs very fast prefix matching on short text. search_as_you_type prepares prefix pieces at index time, so the query is light. Section 3 covers it.


1. Relevance: Text Alone Is Not Enough

A text score like BM25 answers "how well do the words match". For a content app, that is only half the answer. The other half comes from business signals:

SignalExampleWhy it matters
PopularityCompleted plays in the last 30 daysMany other people found it helpful
QualityAverage rating with a minimum number of ratingsPopularity alone can come from a misleading title
LanguageMatches the user's languageA great track in a language you do not understand is useless
FreshnessUploaded in the last few weeksGives new content a chance to surface

In Elasticsearch, these signals are combined with the text score through function_score or rank_feature fields:

HTTP
GET tracks/_search
{
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "must": { "multi_match": { "query": "tidur cepat", "fields": ["title_id^3", "description_id"], "fuzziness": "AUTO" } },
          "filter": { "term": { "lang": "id" } }
        }
      },
      "functions": [
        { "field_value_factor": { "field": "completed_plays_30d", "modifier": "log1p", "missing": 0 } },
        { "field_value_factor": { "field": "rating", "factor": 0.5, "missing": 3 } },
        { "gauss": { "published_at": { "origin": "now", "scale": "30d", "decay": 0.5 } }, "weight": 0.3 }
      ],
      "score_mode": "sum",
      "boost_mode": "multiply"
    }
  }
}

A few important details:

  • log1p on popularity. Without a logarithm, a track with a million plays beats everything else no matter how well the text matches. With a logarithm, popularity helps without dominating.
  • Popularity comes from an aggregation pipeline, not from every play. Remember Part 2: play counts are aggregated per minute through Pub/Sub, then sent to the index through the outbox (Part 5).
  • The language filter goes in filter, not must, because filters do not affect the score and Elasticsearch can cache them.

The weights are not guessed. They are chosen by measuring, and that is section 4.


2. Multilingual: One Field per Language

An analyzer decides how text is broken into searchable words: lowercasing, stemming ("bermeditasi" → "meditasi" in Indonesian), and stopwords. An English analyzer does not understand Indonesian affixes, and vice versa.

If your content is in dozens of languages, the common pattern is one field per language, each with its language analyzer. Elasticsearch has built-in analyzers for many languages, including indonesian:

HTTP
PUT tracks_v3
{
  "mappings": {
    "properties": {
      "lang":     { "type": "keyword" },
      "title_id": { "type": "text", "analyzer": "indonesian" },
      "title_en": { "type": "text", "analyzer": "english" },
      "title_de": { "type": "text", "analyzer": "german" },
      "title_suggest": { "type": "search_as_you_type" },
      "completed_plays_30d": { "type": "integer" },
      "rating":   { "type": "float" },
      "published_at": { "type": "date" }
    }
  }
}

At index time, the worker fills the field for the track's language. At search time, the app picks the field for the user's language. For users searching in a different language from the content, that is where semantic search helps, and section 5 covers its price.

Mapping changes such as adding a new language are done with the reindex and alias approach from Part 5.


3. Autocomplete: A Different Need

Autocomplete is not full search sent more often. The needs differ:

Full searchAutocomplete
InputA full phraseThe first 2–5 letters
FrequencyOnce per searchEvery keystroke
Latency targetHundreds of milliseconds is still fineMust feel instant
ResultsTracks with full relevance scoringA few short titles

That is why autocomplete is often built as a separate field or index. The search_as_you_type type prepares prefix pieces at index time, so the query is light:

HTTP
GET tracks/_search
{
  "size": 5,
  "_source": ["title_id"],
  "query": {
    "multi_match": {
      "query": "med pag",
      "type": "bool_prefix",
      "fields": ["title_suggest", "title_suggest._2gram", "title_suggest._3gram"]
    }
  }
}

On the app side, wait about 150–200 ms after the last keystroke before sending (debounce), and cancel the old request when a new keystroke arrives. Autocomplete results for popular prefixes are also good candidates for caching (Parts 3 and 4).


4. Measuring Search Quality

Without numbers, every relevance change is just an opinion. Four metrics that complement each other:

MetricHow to read it
Zero-result rateThe percentage of searches that find nothing. A signal of unhandled synonyms, typos or content
Click-through rateWhether users click the top results. Also watch the average click position
nDCG@10 on a golden setMeasured before and after every change
p95 latency and errorsEspecially for semantic queries that call a model

A golden set is a list of queries with human relevance labels, for example 0 (not relevant) to 3 (very relevant) for each query and track pair. A worked example for one query, "tidur cepat", with two configurations:

JS
const label = { t01: 3, t02: 3, t03: 2, t04: 2, t05: 1, t06: 1, t07: 0, t08: 0, t09: 0, t10: 0, t11: 2, t12: 0 };
const dcg = (rels) => rels.reduce((s, r, i) => s + (2 ** r - 1) / Math.log2(i + 2), 0);
const ideal = dcg(Object.values(label).sort((a, b) => b - a).slice(0, 10));
// nDCG@10 = dcg(result order) / ideal
TEXT
teks saja (BM25)          : urutan label [0, 2, 3, 0, 1, 3, 0, 2, 0, 1]  nDCG@10 = 0.592
teks + popularitas + rating: urutan label [3, 3, 2, 0, 2, 2, 1, 0, 1, 0]  nDCG@10 = 0.983

(teks saja = text only, teks + popularitas + rating = text + popularity + rating, urutan label = label order.)

The labels and orders here are an example to show the calculation. What matters is the pattern: an irrelevant track in first place (label 0, like in the opening) costs far more than in ninth place, because the divisor is log2(position + 1).

In production, a golden set has dozens to hundreds of queries, split by category: single words, phrases, typos, paraphrases, and cross-language. Every weight change from section 1 runs against the whole golden set, and only ships if nDCG does not drop in any category.


5. Lessons from My Search Project

I once measured six Elasticsearch configurations on this blog's articles with a labeled golden set, generated typos, and a k6 load test that also scored relevance under load. Three findings matter most here:

  1. What you embed matters more than the model. Embedding the full article content (the default semantic_text approach) was no better than plain BM25: nDCG@10 0.739 versus 0.756. The biggest gain came from changing what gets embedded.
  2. BM25 already tolerates typos for multi-word queries. One mistyped word out of five still leaves four that match. fuzziness: AUTO adds stability: the top result stays the same for 100% of one-edit typos, not 90%.
  3. The model is the bottleneck, and its limit is hard. BM25 with fuzziness held a p95 of about 30–40 ms up to 40 requests per second. Without the inference cache, semantic queries collapsed between 12 and 18 requests per second, and hybrid (two inferences per query) between 6 and 9.

The practical takeaway: start with BM25, the right analyzers, and business signals. Add semantic search for the categories that are actually weak (paraphrases, cross-language), measure with a golden set, and plan capacity from uncached numbers.


6. Operating Elasticsearch on GCP

Two common options:

OptionStrengthPrice paid
Elastic Cloud (Elastic's managed service, running in GCP regions)Upgrades, snapshots and monitoring handled for youA service fee on top of infrastructure
Self-hosted on GKE (for example with the ECK operator)Cheaper on paper, full controlSomeone must handle upgrades, shards, heap, and backups

For a small team, people cost more than the service fee. Same principle as choosing Cloud Run over GKE in Part 1 of the GCP series.

Three operational questions that come up most:

Shard size. The Elasticsearch docs suggest 10–50 GB per shard and under 200 million documents. Rough maths for a catalog of 2 million tracks at about 4 KB per document (titles and descriptions in several languages): about 8 GB. One primary shard is enough. Splitting it into 10 shards only adds overhead, because every search runs on every shard.

Replicas. One replica gives availability (if a node dies, the copy is still there) and adds read capacity, because searches can be served by the primary or the replica. If search traffic grows, add replicas and nodes, not primary shards.

Snapshots to Cloud Storage. The gcs repository type is included in recent Elasticsearch versions. Schedule it with snapshot lifecycle management:

HTTP
PUT _snapshot/gcs_backup
{ "type": "gcs", "settings": { "bucket": "contoh-es-snapshots", "base_path": "tracks" } }

PUT _slm/policy/nightly
{ "schedule": "0 30 18 * * ?", "name": "<nightly-{now/d}>", "repository": "gcs_backup",
  "config": { "indices": ["tracks*"] }, "retention": { "expire_after": "14d" } }

Also remember that the index can be rebuilt from the database (Part 5). Snapshots speed up recovery, but the database remains the last safety net.


7. Three Search Quality Traps

Trap one: popularity without a logarithm. The most popular track always wins, no matter how well the text matches. Use log1p or rank_feature, and measure with a golden set.

Trap two: changing relevance without a golden set. A fix for one query often breaks another. Run the whole golden set before every release.

Trap three: too many shards for small data. An 8 GB catalog does not need 10 shards. Start with one primary, add replicas for read capacity.


Summary

  • Relevance = text score + business signals: popularity (with log1p), rating, language, freshness, through function_score or rank_feature.
  • Multilingual: one field per language with its language analyzer. The language filter goes in filter.
  • Autocomplete: a search_as_you_type field, debounce in the app, cache popular prefixes.
  • Measure: zero-result rate, CTR, nDCG@10 on a golden set, p95 and errors. Worked example: 0.592 → 0.983 after adding business signals.
  • From my project: full-content embedding 0.739 vs BM25 0.756, the semantic model collapsed at 12–18 rps without cache, BM25 stayed at 30–40 ms at 40 rps.
  • Operations on GCP: Elastic Cloud or GKE, shards of 10–50 GB and under 200 million documents, replicas for availability and reads, snapshots to Cloud Storage.

Closing the Series

The "tidur cepat" search from the opening now puts the sleep meditation that helps the most people in first place, and we have numbers to prove it.

If this series had to be summed up in one idea, it would be: every piece of data has one home, and everything else is a copy that must know how stale it is.

  • Firestore (Parts 1–2) is the home for real-time per-user data. Its design starts from queries, its copies spread through idempotent events, and its limits (1 MiB, no unlimited writes to one document, billed offsets) shape the data.
  • The cache (Parts 3–4) is a copy for speed. It sits as close to the user as possible, always has a TTL, rejects writes with an older version, and is measured by hit rate.
  • The search index (Parts 5–6) is a copy for searching. It is filled through an outbox with versions, patched by reconciliation, swapped through an alias, and its quality is proven with a golden set.

Use this series as refresher material: every part opens with a quiz. If you still get every question right, skip to the summary. If you miss one, you know which section to reread.

Thank you for following along to the end. Grab your coffee, and may your searches always find what you are looking for!

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 5Keeping a Search Index in Syncseries completeBack to all articles →

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan