Search Systems: Scoring, Elasticsearch, Typeahead, Personalization & ML Ranking
"The Probabilistic Relevance Framework (PRF) is a formal framework for document retrieval, grounded in work done in the 1970–1980s, which led to the development of one of the most successful text-retrieval algorithms, BM25." — Stephen Robertson and Hugo Zaragoza, The Probabilistic Relevance Framework: BM25 and Beyond, Foundations and Trends in Information Retrieval 3(4), 2009
Summary: A search system turns text into an inverted index, turns a query into the same terms, retrieves candidates in milliseconds and ranks them in stages (BM25, business signals, vectors, a learned model); everything around it (analysis, typeahead, indexing pipeline, shards, metrics) exists so that this loop stays fast, fresh and relevant. Focus: inverted index internals (term dictionary, postings lists, skip lists, segments, merges, refresh and near-real-time search, doc values, Lucene), text analysis with Persian specifics (ZWNJ, half-space, ی/ي and ک/ك), TF-IDF to BM25 (k1, b), BM25F and field boosting, function score and decay, learning to rank (features, LambdaMART, XGBoost), click models and position bias, NDCG/MAP/MRR, A/B tests and interleaving, query understanding, facets, typeahead (prefix trie, completion suggester, edge n-grams, debouncing, caching), personalisation, hybrid search (HNSW, IVF, RRF, cross-encoders), the indexing pipeline (outbox/CDC, bulk API, aliases, zero-downtime reindex, ILM), shards, caches, circuit breakers, multi-tenancy and the products (Elasticsearch, OpenSearch, Solr, Meilisearch, Typesense, Vespa, Algolia), with Go and Laravel 13 code. Learning goal: Design product search with typeahead for a catalogue of millions of items: choose the engine, write the analyzer and mapping, explain every factor of a BM25 score, add business and ML ranking without breaking latency, keep the index fresh from the database, size shards, and prove a ranking change with NDCG offline and an A/B test or interleaving online.
This chapter sits in the Domain Systems group, after Payment Processing Architecture and before ML Systems. It owns the system-level design: ranking stages, the numbers, the trade-off tables and the worked e-commerce design. Neighbours own their mechanics: PostgreSQL full-text search versus Elasticsearch basics live in Full-Text Search, pgvector and vector index internals in Vector Search & pgvector, feature stores and model serving in ML Systems, the outbox and CDC in Transactional Outbox and Change Data Capture, cache patterns in Caching, shard keys in Sharding at System Level, and Unicode normalisation in Bits, Bytes & Text Encoding.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a database LIKE is not search | Why it exists |
| Papers and docs behind each idea | Where it comes from |
| Term dictionary, postings, skip lists | Inverted index |
| Segments, refresh, merge, translog, doc values | Segments and near-real-time |
| Tokenizers, stemming, stop words, synonyms | Text analysis |
| Persian: ZWNJ, half-space, ی and ک | Persian and Arabic text |
| n-grams and edge n-grams | n-grams |
| TF-IDF, BM25, k1 and b | BM25 |
| Field boosts and BM25F | Field boosting and BM25F |
| Popularity, recency, decay | Function score and decay |
| LambdaMART, XGBoost, features | Learning to rank |
| Position bias, click models | Click models |
| NDCG, MAP, MRR, A/B, interleaving | Offline metrics, Online evaluation |
| Spell correction, synonyms, intent, entities | Query understanding |
| Facets, filters, aggregations | Facets and filters |
| Autocomplete under 100 ms | Typeahead |
| Per-user ranking, cold start, privacy | Personalisation |
| Embeddings, HNSW, IVF, RRF, cross-encoder | Semantic and hybrid search |
| Outbox, bulk, aliases, reindex, mappings | Indexing pipeline |
| ILM and hot-warm-cold | Index lifecycle |
| Shards, replicas, routing, hot shards | Shards and replicas |
| Caches, query cost, circuit breakers | Query cost and caches |
| Read-after-write, eventual consistency | Consistency |
| One index per tenant or a filter | Multi-tenancy |
| Latency, zero-result rate, CTR | Observability |
| Elasticsearch vs OpenSearch vs Solr vs Meilisearch vs Typesense vs Vespa vs Algolia | Products |
| Knobs, defaults, errors verbatim | Mechanics |
| Code | Go, Laravel |
| E-commerce search with typeahead, end to end | Solving the classic problems |
| Which engine and which ranking stage | Choosing |
| Monolith to distributed system | In architecture |
| Run and drills | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The building blocks.
| Block | In plain words | Tiny example | What it buys | What it costs |
|---|---|---|---|---|
| Inverted index | For each word, the list of documents that contain it | shoe -> [1, 2, 7] | Lookups proportional to matches, not to the catalogue | Index build, storage, write amplification |
| Analyzer | The same text-to-terms recipe at index time and query time | "Running Shoes" -> run, shoe | Matches across case, plural, script variants | A wrong analyzer is invisible until recall drops |
| BM25 | Score = rarity of the word x saturated frequency x length normalisation | k1 = 1.2, b = 0.75 | Good lexical relevance with no training | Knows nothing about popularity, meaning or the user |
| Function score | Multiply or add business signals | log1p(sales) * gauss(age) | Popular, fresh, in-stock first | Hand-tuned weights drift |
| Learning to rank | A model re-orders the top N using many features | LambdaMART on 40 features | Best measured relevance | Judgments, training pipeline, feature parity |
| Vector retrieval | Nearest neighbours of a query embedding | HNSW, k = 100 | Matches meaning, synonyms, other languages | Memory, approximate recall, no exact term match |
| Hybrid + RRF | Fuse lexical and vector lists by rank | 1 / (60 + rank) | Robust without score calibration | Two retrievals per query |
| Typeahead | Precomputed completions per prefix | ip -> iphone 15, ipad | Guides the query before it is typed | A second index and a log pipeline |
| Indexing pipeline | Database change to searchable document | outbox -> relay -> _bulk -> refresh | Freshness with the database as truth | Lag, ordering, reindex operations |
| Shards and replicas | Split the index; copy each split | 6 primaries x 1 replica | Parallelism, availability | Fan-out cost per query, sizing |
Products at a glance.
| Product | Core | Ranking default | Typeahead | Vectors / hybrid | Hosting |
|---|---|---|---|---|---|
| Elasticsearch | Lucene | BM25 (k1 1.2, b 0.75) | completion suggester, search_as_you_type, edge n-grams | dense_vector HNSW, RRF retriever, LTR rescorer | Self-managed or Elastic Cloud |
| OpenSearch | Lucene (fork of Elasticsearch 7.10) | BM25 | Same families of features | k-NN plugin, hybrid query with normalization or RRF | Self-managed or AWS OpenSearch Service |
| Solr | Lucene | BM25 (Lucene default similarity) | Suggester component | Dense vector field, LTR module | Self-managed |
| Meilisearch | Own engine (Rust) | Ordered ranking rules: words, typo, proximity, attributeRank, sort, wordPosition, exactness | Prefix search by default | Hybrid with embedders | Self-hosted or Meilisearch Cloud |
| Typesense | Own engine (C++) | _text_match then sort fields | Prefix by default | Vector and hybrid | Self-hosted or Typesense Cloud |
| Vespa | Own engine | Rank profiles: first-phase, second-phase, global-phase | Via queries on prefix fields | Native tensors, HNSW, ML models in ranking | Self-hosted or Vespa Cloud |
| Algolia | Hosted SaaS | Tie-breaking ranking formula plus custom ranking | Autocomplete library, Query Suggestions | NeuralSearch (vendor feature) | SaaS only |
The usual problems and the first fix.
| Problem | Symptom | First fix | Section |
|---|---|---|---|
LIKE '%q%' on the database | Slow, unranked, no typo tolerance | An inverted index with an analyzer | Why |
| Arabic keyboard letters | كتاب finds nothing, کتاب finds everything | arabic_normalization + persian_normalization at both ends | Persian |
| Long descriptions win | A 5,000-word page outranks the exact product title | BM25 b, field boosts, BM25F | BM25, BM25F |
| Relevant but out of stock or ancient | Users scroll past dead items | Filters plus function score decay | Function score |
| "Just saved it, cannot find it" | New product invisible for a second | refresh=wait_for on that write, or read from the database | Consistency |
| Mapping change needs a field type change | illegal_argument_exception on update | New index + _reindex + alias swap | Indexing pipeline |
| One tenant or brand dominates a shard | One node at 100% CPU | Routing with routing_partition_size, split hot tenants | Shards |
| Typeahead over 300 ms | Suggestions arrive after the user finished typing | Completion suggester, prefix cache, debounce | Typeahead |
| Synonym queries miss meaning | "sneakers" does not find "running shoes" | Synonym graph, then hybrid vector retrieval | Hybrid |
| "The new ranking is better" with no proof | Arguments in meetings | NDCG on judgments, then interleaving or A/B | Metrics |
Numbers to keep in your head. Each is from a saved page or a labelled estimate.
| Fact | Value | Source |
|---|---|---|
| Elasticsearch default refresh | Every 1 s, only for indices searched in the last 30 s | Elasticsearch near-real-time docs |
| BM25 defaults | k1 = 1.2, b = 0.75 | Elasticsearch similarity docs; Lucene BM25Similarity |
| BM25 "reasonably good" ranges | 0.5 < b < 0.8, 1.2 < k1 < 2 | Robertson and Zaragoza 2009 |
| RRF constant | k = 60 (paper); rank_constant default 60 | Cormack et al. 2009; Elasticsearch RRF docs |
| Shard size guidance | 10 GB to 50 GB, under 200 M documents per shard | Elasticsearch "Size your shards" |
| Shards per node limit | 1,000 non-frozen shards per node | Elasticsearch "Size your shards" |
| Node query cache | 10% of heap, up to 10,000 queries | Elasticsearch node query cache settings |
| Shard request cache | 1% of heap | Elasticsearch shard request cache settings |
| Parent circuit breaker | 95% of heap (real memory), request 60%, fielddata 40% | Elasticsearch circuit breaker settings |
| Lucene postings block | 128 integers per packed block; skip data every block and every 32 blocks | Lucene 10.3 postings format |
| Typeahead budget | About 100 ms keystroke to paint, server share 20 to 50 ms | Rule of thumb, see Latency Budgets |
| Demo on one laptop | Trie lookup of a prefix about 9 microseconds | Lab demo, labelled |
The picture is the core of the page: an analyzer turns four short documents into terms, the term dictionary keeps each term once with its document frequency, and each term points to a postings list of (document, term frequency, positions). A query never reads documents; it reads two or three short lists and intersects them. Everything else (scoring, shards, typeahead) is built on that.
Why it exists
A user types "running shoes" and expects, in under a few hundred milliseconds, the 24 products most likely to be bought, even if the title says "Trail Runner Shoe", the user typed "runing", or the text is Persian typed on an Arabic keyboard. A relational database answers "which rows match this predicate" and returns them in an order you specify; a search engine answers "which documents are the best answers to this need" and invents the order.
Database query (WHERE title LIKE '%shoe%') | Search engine query |
|---|---|
| Exact predicate: a row matches or not | Graded relevance: every match gets a score |
| Leading wildcard cannot use a B-tree index: full scan | Inverted index: cost proportional to postings read |
| Case, plural, script and typo are your problem | Analyzer and fuzzy matching handle them |
| Order by a column | Order by BM25 plus signals plus a model |
Facets = many GROUP BY queries | Aggregations computed in the same request from doc values |
| Strongly consistent with the write | Near-real-time: visible after a refresh |
| Source of truth | A derived, rebuildable read model |
One analogy, reused through the page: the index at the back of a textbook. The index lists every important word and the pages where it occurs (term dictionary and postings). Words like "the" are not listed (stop words). "Run, running, ran" share one entry (stemming). A word that appears on three pages tells you more than one that appears on three hundred (IDF). The publisher prints a new small supplement each week instead of reprinting the book (segments) and merges supplements into a new edition now and then (merges). The librarian who knows which page students actually open first is the ranking model.
Three common misunderstandings, up front
- "Search is a database feature with a fancy index." The index is the easy part. Relevance (analysis, scoring, evaluation) is where projects fail, and it is measured, not argued.
- "Elasticsearch is my database." It is a derived store: near-real-time, no multi-document transactions, mappings that cannot change in place. Keep the truth in PostgreSQL or MySQL and rebuild the index from it.
- "Vectors replaced BM25." Dense retrieval misses exact identifiers (SKUs, model numbers, names) that BM25 finds trivially; production systems fuse both and re-rank.
Where it comes from
Every statement below was read on the saved page named in References. Secondary sources are labelled.
| Source | What it states | Why it matters here |
|---|---|---|
| Robertson and Zaragoza (2009) | The probabilistic relevance framework produced BM25 and BM25F; term contribution has a "saturation point"; b and k1 have reasonable ranges | The scoring formula every Lucene engine ships |
| Lucene index file formats (10.3) | The terms index "can list, for a term, the documents that contain it"; segments, term dictionary .tim, term index .tip, postings .doc, positions .pos, norms, doc values, HNSW graph .vex | What a segment physically is |
| Lucene 10.3 postings format | Packed blocks of 128 integers; skip data on two levels | Why AND queries skip ahead |
| Elasticsearch near-real-time docs | A refresh writes and opens a new segment; default every second for recently searched indices | Freshness and its cost |
| Järvelin and Kekäläinen (2002) | Cumulated gain measures; a discount "to devaluate late-retrieved documents" | NDCG |
| Joachims et al. (2005) | Clicks are informative but biased, including a "trust bias" toward top-ranked results | Position bias and click models |
| Cormack, Clarke and Büttcher (SIGIR 2009) | RRF; k = 60 fixed in a pilot and not changed | Hybrid fusion without score calibration |
| Burges, From RankNet to LambdaRank to LambdaMART (Microsoft Research, 2010) | LambdaMART is gradient-boosted trees with LambdaRank gradients (summary from the Elasticsearch LTR page; the report itself could not be fetched, see the note in References) | The default LTR model |
| Malkov and Yashunin (HNSW, arXiv 1603.09320) | Hierarchical proximity graphs give "logarithmic complexity scaling" | The ANN index behind Lucene vectors |
| Chapelle, Joachims, Radlinski, Yue (2012) | Interleaving evaluates rankers from implicit feedback | Online comparison that needs less traffic than A/B |
| Elasticsearch LTR docs (8.12+) | Judgment lists, three feature families, LambdaMART via XGBoost, inference as a rescorer | LTR inside the engine |
| OpenSearch hybrid search docs | Hybrid query, score normalisation (min_max, l2, z_score) or RRF | The OpenSearch way of fusion |
| Laravel 13 Scout docs | Drivers: database, collection, Algolia, Meilisearch, Typesense, Turbopuffer; custom engines | The Laravel integration |
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a sequence, real scenarios, what each product does, and how to use it.
Inverted index, term dictionary, postings lists, skip lists Must-know
In plain words: instead of storing "document -> words", store "word -> documents"; then a query reads only the lists for its words.
Common misunderstanding: "An inverted index is like a B-tree on the text column." A B-tree on title finds rows whose whole title sorts near a key; it cannot find the word "shoe" in the middle of a title. The inverted index indexes every term of every analysed field separately, with counts and positions.
Definition: Lucene's terms index "falls into the family of indexes known as an inverted index. This is because it can list, for a term, the documents that contain it." Per segment there is a term dictionary (.tim, sorted terms with document frequency and pointers; .tip is an FST index into it), postings lists (.doc: doc ids and term frequencies, .pos: positions, .pay: offsets and payloads), norms (.nvd: per-field length factor) and doc values (.dvd: columnar values for sort and aggregations). Postings are delta-encoded in packed blocks of 128 integers, and "skip data is interleaved with blocks on 2 levels" (every block, and every 32 blocks), so an AND query can jump to the next candidate doc id.
Query: running AND shoe (postings sorted by doc id)
1 dictionary lookup "running" -> df 2 -> postings [1, 3]
2 dictionary lookup "shoe" -> df 90,000 -> postings [1, 2, 5, 8, ... ]
3 drive from the SHORT list: candidate 1 -> advance(shoe, 1) -> found
4 candidate 3 -> advance(shoe, 3): skip pointers jump over blocks < 3 -> not found
5 phrase "running shoe": positions of running in doc 1 = [1], of shoe = [2] -> adjacent, match
6 score each match with df (dictionary), tf (postings), length (norms)Real scenario: a marketplace with 30 million listings where "iphone 15 case" reads three postings lists and touches a few thousand candidates; a log search where status:500 AND service:checkout intersects a huge list with a small one; a legal archive phrase search ("force majeure") that needs positions; disabling positions on an ID field to save space.
What each product does:
| Product | Index structure | Notes |
|---|---|---|
| Elasticsearch / OpenSearch / Solr | Lucene segments as above | index_options chooses docs, freqs, positions, offsets |
| Meilisearch | Own inverted index in LMDB (vendor docs) | Word and prefix databases; typo tolerance built in |
| Typesense | In-memory adaptive radix tree index (vendor docs, not fetched) | Whole index held in RAM |
| Vespa | Posting lists plus attribute (in-memory column) fields | Ranking runs on content nodes |
| PostgreSQL FTS | GIN index on tsvector (an inverted index) | See Full-Text Search |
How to use it: let the engine own the structure, but choose what is indexed: index: false for fields only displayed, index_options: docs for filters-only text, keyword for exact values. The Go index package below builds the same structure with skip pointers so you can see the AND-walk cost drop in a test.
Segments, merges, refresh, near-real-time, translog, doc values Must-know
In plain words: the index is a stack of small immutable files; new writes become a new small file every second, and a background job glues small files into bigger ones.
Common misunderstanding: "A successful index request means the document is searchable." It means it is durable (in the translog) and buffered. Search sees it after the next refresh. "Updating one field rewrites the field" is also wrong: Lucene segments are immutable, so an update is a delete bit on the old version plus a whole new document.
Definition: In Elasticsearch "this process of writing and opening a new segment is called a refresh", and "by default, Elasticsearch periodically refreshes indices every second, but only on indices that have received one search request or more in the last 30 seconds." A flush is a Lucene commit (segments fsynced, translog trimmed); the translog makes acknowledged writes durable between commits. Merges (Lucene TieredMergePolicy by default) combine segments of similar size and purge deleted documents; caches built per segment are lost when the segment merges away. Doc values are "an on-disk data structure that is built at document index time", storing field values "in a columnar format that is more efficient for sorting and aggregation".
T = seconds; refresh_interval = 1s
1 T0.0 PUT /products/_doc/42 {...} -> buffer + translog, 201 Created
2 T0.2 GET /products/_search?q=42 -> not found (not refreshed yet)
3 T1.0 refresh -> new segment s17 opened, doc 42 visible
4 T1.1 POST /products/_update/42 price -> doc 42 in s17 marked deleted, new version buffered
5 T2.0 refresh -> s18 has the new version
6 T9.0 merge s14..s18 -> s19 -> deleted versions purged, filter caches for s14..s18 droppedReal scenario: a backfill of 50 million products that runs three times faster with refresh_interval: -1 and zero replicas, then restores both; a "price changed but search still shows the old price" ticket that is the refresh interval plus a cache; an update-heavy counter field (views) that causes constant merges and should live outside the index; a cluster where 30,000 tiny segments slow every query until a _forcemerge on read-only indices.
What each product does:
| Product | Visibility after write | Knob |
|---|---|---|
| Elasticsearch | Next refresh (1 s default, idle indices skip) | index.refresh_interval, ?refresh=wait_for, POST _refresh |
| OpenSearch | Same model (Lucene) | index.refresh_interval; segment replication option |
| Solr | Soft commit opens a searcher | autoSoftCommit / autoCommit in solrconfig.xml |
| Meilisearch | Asynchronous task queue; visible when the task succeeds | Poll the task; batches |
| Typesense | Synchronous on the receiving node | Raft replication to followers |
| Algolia | Asynchronous indexing task | waitTask in clients |
How to use it: keep 1s for product search; raise to 30s for log-like indices; set -1 during bulk backfills; use refresh=wait_for only on the one write a user immediately searches for (never on bulk); keep frequently changing counters out of the document or update them in batches.
Text analysis: analyzer, tokenizer, normalisation, stemming, lemmatisation, stop words, synonyms Must-know
In plain words: before text is indexed it is cut into words and cleaned; the query goes through the same cleaning, so both sides speak the same vocabulary.
Common misunderstanding: "The engine understands words." It compares byte strings of terms. If the index stored running and the query produced run, nothing matches; if the analyzer at index time differs from the one at query time, recall silently drops.
Definition: an analyzer is char filters (rewrite characters, for example the ZWNJ mapping), one tokenizer (split into tokens: standard follows Unicode word boundaries, whitespace, keyword, icu_tokenizer from the ICU plugin), and token filters: lowercase, normalisation (asciifolding, arabic_normalization, persian_normalization), stop words (stop), stemming (rule-based suffix stripping: porter_stem, snowball, persian_stem), lemmatisation (dictionary reduction to a lemma: went -> go; not in core Elasticsearch, done with plugins or upstream NLP), and synonyms (synonym, synonym_graph at query time so multi-word synonyms keep positions). Elasticsearch ships language analyzers including arabic, english, persian and sorani.
Analyzer "english" on index and query
1 text "The Runners' Shoes"
2 tokenize [The] [Runners'] [Shoes]
3 lowercase [the] [runners'] [shoes]
4 possessive + stop [runners] [shoes]
5 stem [runner] [shoe]
6 query "running shoe" -> [run] [shoe] -> "runner" != "run": only shoe matches
7 lesson: stemmers conflate some forms, not all; test with _analyzeReal scenario: English stemming that turns "university" and "universe" into the same stem (over-stemming) and pollutes results; stop words removed from "The Who" so the band disappears; a synonym list tv, television applied at index time that needs a full reindex for every change, moved to query time with synonym_graph and the updateable synonyms API; a SKU field analysed by standard that splits AB-12 into two tokens and must be keyword.
What each product does:
| Product | Analysis model | Synonyms |
|---|---|---|
| Elasticsearch / OpenSearch | Char filters, tokenizer, token filters; _analyze API to test | synonym, synonym_graph; synonyms sets API (Elasticsearch 8.10+) |
| Solr | Same Lucene chain in the schema (fieldType) | SynonymGraphFilterFactory, managed resources |
| Meilisearch | Built-in tokenizer (charabia) with language detection; stop words and synonyms settings | synonyms setting |
| Typesense | Built-in tokenizer; symbols_to_index, token_separators | Synonyms API (one-way, multi-way) |
| Algolia | Built-in; ignorePlurals, removeStopWords per language | Synonyms (regular, one-way, placeholders) |
| PostgreSQL FTS | Text search configurations and dictionaries | Thesaurus dictionary |
How to use it: write the analyzer explicitly in the mapping, test it with GET /index/_analyze, keep a test file of tricky inputs (the Go analysis tests are such a file), and put synonyms at query time. Lemmatisation is worth it only if you have a language model; light stemming plus synonyms covers most shops.
Persian and Arabic text: ZWNJ, half-space, ی/ي, ک/ك, digits Must-know
In plain words: Persian text arrives in several byte forms that look identical on screen; unless both document and query are folded to one form, "کتاب" and "كتاب" are different words to the engine.
Common misunderstanding: "UTF-8 solves it." UTF-8 encodes each variant faithfully; the problem is that Arabic yeh ي (U+064A) and Persian yeh ی (U+06CC), Arabic kaf ك (U+0643) and keheh ک (U+06A9) are different code points, and the half-space ZWNJ (zero-width non-joiner, U+200C) may be present, absent or replaced by a space in the same word: میروم, میروم, می روم.
Definition: a Persian analyzer must (1) map Arabic letter variants to Persian ones (arabic_normalization and persian_normalization in Lucene/Elasticsearch), (2) decide what ZWNJ means: the built-in persian analyzer's char filter "replaces zero-width non-joiners with an ASCII space" (so کتابها becomes two tokens), while removing it keeps the word whole; (3) remove diacritics (harakat) and tatweel; (4) fold Persian ۱۲۳ and Arabic-Indic ١٢٣ digits with decimal_digit; (5) remove stop words (_persian_) and apply light stemming (persian_stem, plural suffixes such as ها).
Document "کتابهای علمی" typed on a Persian keyboard; query "كتاب علمي" on an Arabic keyboard
1 no normalisation: doc terms [کتابهای] [علمی], query terms [كتاب] [علمي] -> 0 hits
2 + arabic/persian normalisation: query -> [کتاب] [علمی] -> علمی matches, کتابهای still does not
3 + ZWNJ as space (built-in persian): doc -> [کتاب] [های] [علمی] -> both match; "های" is noise
4 + ZWNJ removed + light stem: doc -> [کتاب] [علمی] -> clean match
5 phrase queries: ZWNJ-as-space shifts positions; pick one rule and use it on both sidesReal scenario: an Iranian bookshop where half the catalogue was imported from Arabic-keyboard spreadsheets; a typeahead that suggests both كتاب and کتاب as separate popular queries; a price filter on ۱۲۰۰۰۰ stored as text; user-generated reviews mixing ZWNJ, space and nothing.
What each product does:
| Product | Persian support | Notes |
|---|---|---|
| Elasticsearch / OpenSearch | persian analyzer: ZWNJ char filter, decimal_digit, arabic_normalization, persian_normalization, _persian_ stop words, persian_stem | Rebuild it as a custom analyzer to change the ZWNJ rule |
| Solr | PersianNormalizationFilterFactory, PersianCharFilterFactory | Same Lucene code |
| Meilisearch / Typesense / Algolia | Generic Unicode tokenisation; Arabic-script support varies | Normalise in your application before indexing and before querying |
| PostgreSQL FTS | simple config plus your own normalisation | No Persian stemmer in core |
| This chapter's Go and PHP | analysis.Normalize and PersianNormalizer::normalize | Same mapping in both languages, tested |
How to use it: normalise in one place (the analyzer for Lucene engines, application code for the others) and apply it to documents, queries, typeahead inputs and query logs alike; treat ZWNJ consistently (removing it is usually better for product titles); test with real keyboard input from both layouts.
n-grams and edge n-grams Important
In plain words: cut each word into its pieces (all substrings of length n, or only the prefixes) so a partial word can match.
Common misunderstanding: "Use n-grams for autocomplete." Full n-grams (ngram tokenizer) index every substring and multiply index size; for prefix matching edge n-grams (edge_ngram, prefixes only) are enough, and they must be applied only at index time, with a normal search_analyzer, or the query "shoe" becomes s, sh, sho, shoe and matches everything starting with "s".
Definition: edge_ngram emits prefixes of length min_gram to max_gram (Elasticsearch defaults 1 and 2, so always set them). Terms longer than max_gram are truncated in the index: "if the max_gram is 3, searches for apple won't match the indexed term app." search_as_you_type fields create ._2gram, ._3gram shingle subfields and ._index_prefix automatically. n-grams of characters (trigrams) also give typo-tolerant matching at a large size cost.
edge_ngram min 2 max 10 on "sneakers"; search_analyzer standard
1 index terms: sn, sne, snea, sneak, sneake, sneaker, sneakers
2 query "snea" -> one term [snea] -> matches
3 WRONG: same analyzer at query time -> [sn][sne][snea] -> matches "snow boots" via "sn"
4 query "sneakers-xl-2024" longer than max_gram -> no indexed term that long -> no match unless truncate filterReal scenario: a mobile shop search box that matches "iph" without a dedicated suggester; a product-code search where infix matching (ngram min 3) finds "X200" inside "AX200B"; an index that grew 6x because ngram with min 1 max 10 was used on descriptions.
What each product does:
| Product | Prefix matching | Infix |
|---|---|---|
| Elasticsearch / OpenSearch | edge_ngram, search_as_you_type, match_phrase_prefix, prefix query | ngram, wildcard field type |
| Solr | EdgeNGramFilterFactory | NGramFilterFactory |
| Meilisearch / Typesense | Prefix search on the last word by default | Not by default |
| Algolia | Prefix on the last word (queryType: prefixLast) | Not by default |
How to use it: edge n-grams on a title.prefix subfield (as in the Go esclient mapping), search_analyzer without them, max_gram near 15 to 20, and keep descriptions out of it.
TF-IDF to BM25: k1 and b Must-know
In plain words: a document scores high when it contains rare query words, contains them a few times (more helps less and less), and is not just long.
Common misunderstanding: "More occurrences, higher score, forever." That is raw TF-IDF, and spammy pages that repeat a word win. BM25's term weight saturates: "any one term's contribution to the document score cannot exceed a saturation point (the asymptotic limit)". A second misunderstanding: "BM25 scores are comparable across queries or indices." They are not; they depend on the collection statistics.
Definition: for query terms q_i, BM25 as implemented in Lucene is
score(D, Q) = sum over terms q in Q of IDF(q) * tf * (k1 + 1) / (tf + k1 * (1 - b + b * |D| / avgdl))
IDF(q) = ln(1 + (N - df + 0.5) / (df + 0.5)) -- Lucene's variant, never negative
tf = frequency of q in the field of D
|D|, avgdl = field length of D, average field length in the shard
k1 = saturation (default 1.2): 0 means "presence only", large means close to raw tf
b = length normalisation (default 0.75): 0 none, 1 fullTF-IDF was the predecessor (Lucene's classic similarity, removed as the default in Lucene 6 / Elasticsearch 5); Robertson and Zaragoza report that "values such as 0.5 < b < 0.8 and 1.2 < k1 < 2 are reasonably good in many circumstances" but that optimal values depend on the documents and queries.
Collection N = 1,000; avgdl = 10 terms; query "trail shoe"; k1 1.2, b 0.75
1 df(trail) = 10 -> IDF = ln(1 + 990.5/10.5) = 4.56
2 df(shoe) = 300 -> IDF = ln(1 + 700.5/300.5) = 1.20
3 doc A: |D| 10, tf(trail) 1, tf(shoe) 1 -> 4.56*1.0 + 1.20*1.0 = 5.76
4 doc B: |D| 10, tf(shoe) 8 only -> 1.20 * 8*2.2/(8+1.2) = 1.20*1.91 = 2.30
5 doc C: |D| 100, tf(trail) 1, tf(shoe) 1 -> norm = 0.25+7.5 = 7.75; each tf weight 2.2/(1+9.3) = 0.21 -> 1.23
6 rare word wins (A), repetition saturates (B), long fields are discounted (C)Real scenario: a product catalogue where long SEO descriptions beat exact titles until title gets its own field and boost; tweets or product names where b near 0.3 works better because length carries little meaning; a shard with only 50 documents where IDF is noisy and "shard-local statistics" produce different scores per shard (search_type=dfs_query_then_fetch computes global statistics at extra cost); the explain=true output used to answer "why is this first?".
What each product does:
| Product | Default scoring | Tunable |
|---|---|---|
| Elasticsearch | BM25, per-field similarity | k1, b, discount_overlaps; scripted similarity |
| OpenSearch | BM25 | Same |
| Solr | BM25 (BM25SimilarityFactory) | k1, b per field type |
| Meilisearch | No BM25; ordered ranking rules (words, typo, proximity, attributeRank, sort, wordPosition, exactness) | Rule order, custom ranking rules |
| Typesense | _text_match from tokens matched, typos, proximity | text_match_type, up to two tie-break sort fields |
| Vespa | nativeRank or bm25(field) feature in a rank profile | Any expression |
| Algolia | Tie-breaking criteria (typo, geo, words, filters, proximity, attribute, exact, custom) | Order of criteria, custom ranking |
How to use it: start with defaults, read explain for a few bad queries, separate fields before you tune k1 and b, and tune only with a judgment set (the Go index tests show the effect of b = 0 and of saturation).
Field boosting and BM25F Important
In plain words: a word in the title should count more than the same word in the description; BM25F combines fields before saturating, instead of adding separate field scores.
Common misunderstanding: "title^3 and summing per-field BM25 is BM25F." Summing per-field scores (multi_match best_fields or most_fields) saturates each field separately, so a term repeated in five fields counts five times. BM25F builds one weighted pseudo-frequency sum(boost_f * tf_f / norm_f) and saturates once.
Definition: BM25F (Robertson and Zaragoza section 3.6) treats a document as weighted streams. Elasticsearch implements this idea in combined_fields (and multi_match type: cross_fields is a related blend); best_fields takes the best field (with tie_breaker), most_fields sums fields. Query-time boosts (title^3) multiply a field's contribution; index-time boosts are deprecated.
Query "shoe"; title boost 3, body boost 1
1 doc 1: title "Trail running shoes" (tf 1), body tf 1
2 most_fields: BM25(title)*3 + BM25(body) -> each field saturates alone -> counted twice
3 BM25F: pseudo-tf = 3*1/norm_title + 1*1/norm_body -> one saturation -> bounded
4 doc 5: body "boots boots ... shoes" (tf 1), no title match -> stays below title matchesReal scenario: "iphone" in the title of a phone versus in the description of a case ("compatible with iPhone"); a recipe site where the ingredient field should beat comments; a job board blending title, skills and description.
What each product does:
| Product | Multi-field scoring |
|---|---|
| Elasticsearch / OpenSearch | multi_match (best_fields, most_fields, cross_fields, phrase, bool_prefix), combined_fields (BM25F style) |
| Solr | eDisMax qf=title^3 description with tie |
| Meilisearch | searchableAttributes order is the attribute rank |
| Typesense | query_by plus query_by_weights |
| Algolia | Ordered searchableAttributes |
| Vespa | bm25(title), bm25(body) features combined in an expression |
How to use it: combined_fields or BM25F for fields that hold the same kind of text; best_fields with a tie-breaker when fields are different kinds; keep boosts in one config file and change them only with an offline evaluation.
Function score, popularity and recency decay Important
In plain words: text relevance says "this product is about shoes"; business signals say "and people buy it, it is new, it is in stock". Combine them in the score.
Common misunderstanding: "Sort by popularity." Sorting throws away relevance (a popular phone case for the query "phone"); multiplying by a dampened popularity keeps relevance as the main driver. Another: "add the sales count to the score." Raw counts are unbounded; use log1p or a saturation function.
Definition: Elasticsearch function_score wraps a query and modifies scores with functions: field_value_factor (with modifier such as log1p, sqrt), weight, random_score, script_score, and decay functions gauss, linear, exp with origin, scale, offset, decay (the score is decay at distance scale beyond offset); score_mode combines functions, boost_mode combines with the query score (multiply, sum, replace, max, min, avg). rank_feature fields and the rank_feature query are a faster alternative for static signals.
Query "shoe", BM25 = 5.0; popularity = 120 sales; age = 60 days; gauss(scale 30d, decay 0.5)
1 popularity factor = log1p(120) = 4.80
2 recency factor = exp(-60^2 / (2*sigma^2)), sigma^2 = -30^2 / (2 ln 0.5) -> 0.0625
3 score_mode multiply: 4.80 * 0.0625 = 0.30
4 boost_mode multiply: 5.0 * 0.30 = 1.50
5 a 3-day-old item with 10 sales: log1p(10)=2.40, gauss=0.99 -> 5.0*2.38 = 11.9 -> fresh winsReal scenario: news search with a strong recency decay; marketplace search with a seller-quality factor; geo decay for "restaurants near me" (see Geospatial Indexing); a promotional boost that a merchandiser can pin; out-of-stock items filtered, not just demoted.
What each product does:
| Product | Business signals |
|---|---|
| Elasticsearch / OpenSearch | function_score, script_score, rank_feature, distance_feature |
| Solr | Function queries, boost parameter in eDisMax |
| Meilisearch | sort rule and custom ranking rules (popularity:desc) as tie-breakers |
| Typesense | sort_by tie-breakers after _text_match |
| Algolia | Custom ranking attributes after textual criteria |
| Vespa | Any expression in first-phase or second-phase ranking |
How to use it: filter hard constraints (in stock, region, adult content), multiply soft ones with dampened functions, keep the formula in one place (the PHP engine below uses log1p popularity and a 30-day gauss), and later replace hand-tuned weights with LTR.
Learning to rank: features, LambdaMART, XGBoost Important
In plain words: instead of guessing weights for BM25, popularity and price, learn them from examples of good and bad results, and let a model re-order the top results.
Common misunderstanding: "LTR replaces the engine." The model is too expensive for millions of documents; it re-scores the top N (100 to 1,000) that a cheap first stage retrieved. Another: "train on clicks as labels." Raw clicks carry position bias (next block).
Definition: an LTR model is trained "on a judgment list, which is a set of queries and documents with a relevance grade" (0 to 4 for example). Features come in three families: document features (price, sales), query features (number of words), query-document features (BM25 of the title). In Elasticsearch (8.12+) features are templated queries, training happens outside ("using a GBDT model"), and "LambdaMART provides strong ranking performance with low inference latencies"; XGBoost provides LambdaMART as XGBRanker with rank:ndcg or rank:pairwise, and Eland uploads it; inference runs as a learning_to_rank rescorer over a window_size. LambdaMART (Burges 2010) is gradient-boosted regression trees trained with LambdaRank gradients: pairwise swaps weighted by how much NDCG would change.
Offline training and online inference
1 judgments: (query "trail shoe", doc 17, grade 3), (.., doc 4, grade 0), ... -- humans + clicks
2 features per pair: title_bm25, body_bm25, log_sales, price_rel_to_median, age_days, ctr_30d
3 train XGBRanker(objective rank:ndcg), validate NDCG@10 on held-out queries
4 upload model (Eland) -> stored as a trained model in the cluster
5 query: BM25 retrieves top 1,000 -> rescore window 200 with the model -> return 24
6 log features AT SERVE TIME for the next training round (avoid train/serve skew)Real scenario: a marketplace where the model learned that price relative to the category median matters more than absolute price; a job site ranking by predicted apply rate; a model that regressed because a feature (ctr_30d) was computed differently online than offline; Airbnb and others describe similar staged rankers in their engineering writing (not fetched for this chapter, so treat as background).
What each product does:
| Product | LTR support |
|---|---|
| Elasticsearch | Native LTR (8.12+, subscription-dependent), XGBoost models via Eland, learning_to_rank rescorer |
| OpenSearch | Learning to Rank plugin (feature sets, XGBoost or RankLib models, sltr query) |
| Solr | LTR module (feature store, model store, rq reranking) |
| Vespa | ONNX, XGBoost and LightGBM models inside rank profiles (second-phase, global-phase) |
| Meilisearch / Typesense / Algolia | No custom model inside the engine; re-rank in your service (Algolia has vendor AI ranking features) |
How to use it: build a judgment set first (it also powers offline metrics), log features at serve time, start with 10 to 30 features and LambdaMART, re-rank 100 to 200 results, and ship only after NDCG offline and an online test.
Click models and position bias Important
In plain words: people click the first result more just because it is first; a click is a vote weighted by where the item stood.
Common misunderstanding: "CTR per document is relevance." A mediocre item at rank 1 collects more clicks than an excellent one at rank 8; training on raw clicks freezes the current ranking (a feedback loop).
Definition: Joachims et al. found that clicks are informative but biased, including "a 'trust bias' which leads to more clicks on links ranked highly by Google, even if those abstracts are less relevant than other abstracts the user viewed." Click models separate examination from attractiveness: the position-based model (P(click) = P(examined at rank r) x P(relevant)), the cascade model (users scan top-down and stop at the first satisfying result), and dynamic Bayesian network models. Practical debiasing uses inverse propensity weighting (weight a click by 1 / P(examined at rank r)), estimated by small randomisation (swap results at ranks k and k+1 for a fraction of traffic), and pairwise preferences ("skip-above": a clicked result is preferred over unclicked ones above it).
Query "running shoes", 10,000 impressions
1 rank 1 doc A: 2,000 clicks (CTR 20%) examination propensity at rank 1 = 1.0
2 rank 5 doc B: 600 clicks (CTR 6%) propensity at rank 5 = 0.25 (from randomisation)
3 debiased: A 20% / 1.0 = 0.20 ; B 6% / 0.25 = 0.24 -> B is at least as attractive
4 skip-above: user clicked B at 5, skipped 1-4 -> preferences B > A, B > ...
5 train LTR on debiased labels; keep randomising a little to keep estimates freshReal scenario: a shop whose "popular" ranking never lets new products be seen; an LTR model that learned "rank 1 is relevant"; a dashboard showing CTR rising after a UI change that only moved results up.
What each product does:
| Product | Click data support |
|---|---|
| Elasticsearch | Behavioral analytics (event collection) can feed judgment lists; debiasing is yours |
| OpenSearch | Search relevance tooling and user behaviour insights plugins (check the version) |
| Algolia | Click and conversion events (Insights API) feed its ranking features |
| Vespa / Solr / Meilisearch / Typesense | You collect events and compute features |
How to use it: log impressions (all shown ids with rank), not only clicks; store click_rank; estimate propensities with a small randomised bucket; use debiased or pairwise labels for LTR. The SQL search_events table below holds exactly these fields.
Offline metrics: NDCG, MAP, MRR Must-know
In plain words: grade results for a fixed set of queries, then compute one number that rewards putting the best results first.
Common misunderstanding: "Precision and recall are enough." They ignore order within the top results and treat relevance as yes/no; product search is graded (perfect, good, fair, bad) and order is everything.
Definition: DCG@k = sum over ranks i ≤ k of gain(rel_i) / log2(i + 1), commonly gain = 2^rel − 1; the original paper "applies a discount factor to the relevance scores in order to devaluate late-retrieved documents." NDCG@k divides by the DCG of the ideal order, so it lies in [0, 1] and is comparable across queries. MRR is the mean of 1 / rank of the first relevant result (navigational queries: "the one right answer"). AP averages precision at each relevant hit; MAP is its mean over queries (binary relevance). Also used: Precision@k, Recall@k, ERR.
Grades of the top 4 for one query: [2, 3, 0, 1] (ideal order [3, 2, 1, 0])
1 DCG@3 = (2^2-1)/log2 2 + (2^3-1)/log2 3 + 0 = 3 + 4.42 = 7.42
2 IDCG@3 = 7/1 + 3/1.585 + 1/2 = 7 + 1.89 + 0.5 = 9.39
3 NDCG@3 = 7.42 / 9.39 = 0.790 (the Go demo prints 0.790)
4 MRR (first grade >= 2 at rank 1) = 1.0
5 swap ranks 1 and 2 -> NDCG@3 = 1.0Real scenario: a team that keeps 500 judged queries (head, torso and tail) and blocks any ranking change that lowers NDCG@10 by more than 1%; MRR for "order number" or "SKU" queries; recall@1000 for the first stage (did the candidate set contain the good items at all?).
What each product does:
| Product | Built-in evaluation |
|---|---|
| Elasticsearch / OpenSearch | _rank_eval API: precision, recall, MRR, DCG and ERR over rated documents |
| Solr / Vespa / Meilisearch / Typesense / Algolia | External tools (Quepid, your own scripts); Algolia has A/B testing |
| Go (this chapter) | metrics.NDCG, MRR, AveragePrecision with tests |
How to use it: sample queries from logs by frequency band, judge with guidelines (two raters, disagreement review), compute NDCG@10 and MRR per band, and keep recall@N for the retrieval stage separate from NDCG for the ranker.
Online evaluation: A/B tests and interleaving Important
In plain words: offline metrics guess; online tests ask real users. An A/B test splits users; interleaving shows each user a mixed list and sees which ranker's items they click.
Common misunderstanding: "Run an A/B for a day and read CTR." Search metrics are noisy and seasonal; small ranking changes need large samples, and CTR alone rewards clickbait. Interleaving reaches a decision with far less traffic but tells you only which ranker is preferred, not revenue impact.
Definition: an A/B test randomises users (not requests) to control and treatment and compares business metrics (conversion, revenue per search, zero-result rate, time to first click) with a pre-registered sample size and guardrails (latency). Interleaving (team-draft or balanced) merges results of rankers A and B into one list, credits each click to the ranker that contributed the item, and declares the preferred ranker; Chapelle et al. describe it as "an increasingly popular technique for evaluating information retrieval systems based on implicit user feedback", agreeing with offline judgments while needing fewer users.
Team-draft interleaving for one query
1 A = [a1, a2, a3, ...] B = [b1, a1, b2, ...]
2 coin toss: A picks first -> a1 (team A); B picks its best not shown -> b1 (team B)
3 B picks -> b2? no, alternate: A picks a2, B picks b2 ...
4 user clicks b1 and a2 -> one credit each; repeat over 50,000 queries
5 B wins 54% of decided queries -> B preferred; then A/B for revenue with the winnerReal scenario: a marketplace that interleaves every candidate ranker for a week and A/B tests only the winners; a "zero-result rate" guardrail that blocks a too-aggressive spell corrector; Netflix and others write about interleaving for ranking (background, not fetched).
What each product does:
| Product | Online testing |
|---|---|
| Algolia | A/B testing in the dashboard (index or settings variants) |
| Elasticsearch / OpenSearch / Solr / Vespa | No built-in A/B; route traffic by user id in your API, log variant ids |
| Meilisearch / Typesense | External |
How to use it: assign variants by hashed user id, log variant and impressions on every search, interleave to choose among rankers, A/B to measure business impact, and guard with latency and zero-result rate.
Query understanding: spell correction, query expansion, intent, entity recognition Important
In plain words: before searching, work out what the user meant: fix typos, add equivalent words, detect "this is a brand and a size", and turn those into filters.
Common misunderstanding: "Fuzzy matching is spell correction." fuzziness: AUTO tolerates edit distance per term at a cost on every query and still ranks "shoe" next to "shot"; real spell correction proposes a corrected query from the query log and the index vocabulary ("did you mean"), applied when the original query returns few or no results.
Definition: spell correction with edit distance (Damerau-Levenshtein) candidates ranked by frequency and context (Elasticsearch term and phrase suggesters; the phrase suggester selects "entire corrected phrases instead of individual tokens weighted based on ngram-language models"); query expansion with synonyms, stems, transliteration (iphone / آیفون) or embeddings; query relaxation (drop the least important term when nothing matches); intent classification (navigational, product, category, question; or "which department"); entity recognition (brand nike, colour red, size 42, price "under 50") that becomes structured filters or boosts.
Query "nkie red runing shoes 42"
1 spell: nkie -> nike (brand dictionary, edit distance 2 with transposition 1), runing -> running
2 entities: brand=nike, colour=red, size=42; remaining text "running shoes"
3 intent: category=footwear/running (classifier on the query log)
4 rewrite: text "running shoes" + filter brand=nike, size=42 + boost colour=red
5 zero results? relax: drop size filter, show "no 42 in stock, showing other sizes"Real scenario: a grocery search that maps "coke" to a brand and a category; a bookshop that recognises ISBNs and goes straight to the product; Persian/English transliteration ("samsung" / "سامسونگ"); a support search that routes questions to an FAQ index.
What each product does:
| Product | Built in |
|---|---|
| Elasticsearch / OpenSearch | fuzziness, term and phrase suggesters, synonyms, percolator for rules; Elasticsearch query rules (pinned results) |
| Solr | SpellCheckComponent, query elevation |
| Meilisearch / Typesense / Algolia | Typo tolerance built in; Algolia query rules and categorisation features |
| Vespa | Query profiles and searchers (Java) for rewriting |
How to use it: typo tolerance in the engine for the long tail, a dictionary-based corrector for "did you mean", a small rule table for the head queries, and an entity extractor for brands, sizes and colours; log the rewritten query next to the original.
Facets, filters and aggregations Must-know
In plain words: filters cut the result set (brand = Nike); facets show counts per value so users can cut it themselves (Nike 120, Adidas 80).
Common misunderstanding: "Put filters inside the scoring query." A clause in must changes scores and cannot be cached as a filter; a filter clause is yes/no, does not score, and is eligible for the node query cache. Another: "facet counts are exact." terms aggregations across shards are approximate unless shard_size is large enough (doc_count_error_upper_bound reports the error).
Definition: in Elasticsearch, bool.filter and bool.must_not run in filter context; aggregations (terms, range, histogram, cardinality, nested and filter aggs) read doc values; post_filter applies a filter after aggregations, which is how a facet keeps counts for other values of the selected facet (multi-select facets). Meilisearch requires filterableAttributes, Typesense facet: true per field.
User selects brand=nike in a multi-select facet
1 query: match "running shoes", filter category=shoes, in_stock=true
2 aggs: brand terms (must IGNORE the brand selection to show other brands)
3 post_filter: brand=nike -> hits limited to Nike, brand facet still shows Adidas 80
4 size facet: computed WITH brand=nike (filter aggregation) -> sizes available in NikeReal scenario: e-commerce faceted navigation; log analytics with date histograms; a job board with salary ranges; a high-cardinality "seller" facet that kills heap until shard_size and size are bounded.
What each product does:
| Product | Filters and facets |
|---|---|
| Elasticsearch / OpenSearch | bool.filter, post_filter, aggregations on doc values, composite aggs for paging |
| Solr | fq (cached in filterCache), JSON facets |
| Meilisearch | filter and facets on filterableAttributes |
| Typesense | filter_by, facet_by on fields with facet: true |
| Algolia | filters, facets, attributesForFaceting |
| Vespa | YQL where filters, grouping language |
How to use it: hard constraints in filter, post_filter for multi-select facets, keyword fields for facets, bounded facet sizes, and Scout where/whereIn (which require filterableAttributes on Meilisearch).
Typeahead and autocomplete Must-know
In plain words: as the user types "ip", show "iphone 15, ipad, iphone case" before they finish, ranked by how often people search them, within roughly 100 ms per keystroke.
Common misunderstanding: "Autocomplete is the same search with a prefix query." Running full search on every keystroke multiplies load by the number of characters typed and returns documents, not queries. Typeahead usually suggests queries (from the query log) and sometimes top products, from a dedicated structure: a prefix trie or FST with precomputed top-K per prefix. Elasticsearch's completion suggester "is not meant for spell correction or did-you-mean functionality".
Definition: a prefix trie stores each suggestion along a path of characters; each node keeps the top K completions by weight, so lookup is O(prefix length). Weights come from the query log (searches that led to a click or purchase, decayed by age), filtered for quality and privacy (minimum distinct users). Elasticsearch's completion suggester maps a completion field with input and weight; it "uses data structures that enable fast lookups, but are costly to build and are stored in-memory" (an FST per segment), supports fuzzy, skip_duplicates and context suggesters (category, geo). Alternatives: search_as_you_type fields or edge n-grams for product-level suggestions. Client-side: debouncing (wait about 100 to 200 ms after the last keystroke), cancel stale requests, keep results for prefixes already seen; server-side: cache hot short prefixes (they are few: a few thousand two-character prefixes cover most traffic), CDN cache for anonymous suggestions. Algolia's Autocomplete describes the pattern: "A user types into an input, and the autocomplete suggests full terms or results to complete their thought."
Keystrokes "i", "p", "h" within 250 ms; debounce 150 ms; budget 100 ms
1 t=0 "i" -> debounce timer starts (no request: 1 char below minimum)
2 t=90 "ip" -> timer restarts
3 t=240 timer fires -> GET /api/suggest?q=ip
4 server: normalise -> cache hit "suggest:v1:ip" -> 3 ms
5 t=260 "iph" typed -> new request, previous response ignored if late (AbortController)
6 cache miss "iph" -> completion suggester 12 ms -> cache for 60 s (stale up to 300 s)
7 user picks "iphone 15" -> logged as accepted suggestion -> weight += 1 tonightReal scenario: a shop where 40% of searches start from a suggestion; Persian suggestions where the Arabic-keyboard prefix must hit the same node (the Go trie tests this); a trending query ("new phone launch") that needs hourly weight refresh; offensive or private queries that must never be suggested (blocklist plus k-anonymity floor).
What each product does:
| Product | Typeahead mechanism |
|---|---|
| Elasticsearch / OpenSearch | completion suggester (FST, weights, contexts, fuzzy), search_as_you_type, edge n-grams |
| Solr | Suggester component (AnalyzingInfixLookupFactory, FuzzyLookupFactory) |
| Meilisearch / Typesense | Prefix search on every query; a separate "queries" index for suggestions |
| Algolia | Autocomplete UI library plus Query Suggestions indices built from analytics |
| Redis | Sorted sets per prefix or FT.SUGADD / FT.SUGGET in Redis Search |
| Go (this chapter) | typeahead.Trie with top-K per node and Personalize |
How to use it: a nightly (or hourly) job builds suggestions from the query log with decay and filters; serve them from a completion field or an in-memory trie; debounce in the client; cache with Cache::flexible (the Laravel controller below); set a hard server timeout and return an empty list rather than late suggestions.
Personalisation: user features, re-ranking, cold start, privacy Important
In plain words: two users typing "apple" may want fruit or phones; use what you know about this user to re-order the top results, without making results strange for new users.
Common misunderstanding: "Personalise retrieval." Filtering the candidate set by user history hides items and creates filter bubbles; most systems retrieve the same candidates for everyone and personalise the re-ranking of the top N with user features.
Definition: user features (preferred brands, price band, sizes, recent categories, locale), user-item features (has viewed, has bought, similarity of item embedding to the user embedding) feed the re-ranker; cold start (new user or new item) falls back to global popularity, context features (device, locale, time) and exploration slots for new items; privacy: minimise and expire behavioural data, honour consent and deletion requests, never put personal data in shared caches or in typeahead weights, and keep a non-personalised mode.
User u (bought Nike, size 42) searches "running shoes"
1 retrieval: same 1,000 candidates as everyone
2 features: brand_affinity(u, nike) = 0.8, size_available(42) = 1, price_band_match = 0.6
3 re-rank top 200 with the LTR model that includes user features
4 cache: the personalised result is NOT cached under the query key (or keyed by segment)
5 new user: features missing -> model uses global features only -> same as anonymous rankingReal scenario: a fashion shop boosting a user's sizes; typeahead that ranks "iphone case" first for a user who bought an iPhone (the Go Personalize function); GDPR-style deletion that must also purge the user's feature row; a shared CDN cache that leaked one user's personalised suggestions to another (key by user or do not cache).
What each product does:
| Product | Personalisation |
|---|---|
| Elasticsearch / OpenSearch / Solr | Pass user features as query parameters into function score, LTR features or a rescorer; or re-rank in your service |
| Vespa | User tensors in the query, ranked against item tensors on content nodes |
| Algolia | Vendor personalisation features based on events |
| Meilisearch / Typesense | Re-rank in your service, or filter/boost by parameters |
How to use it: personalise the second stage, keep a global fallback, key caches by segment rather than user where possible, and store user features in the feature store described in ML Systems.
Semantic and hybrid search: embeddings, ANN, HNSW, IVF, RRF, cross-encoders Must-know
In plain words: turn the query and documents into vectors that sit close when meanings are close, find the nearest ones fast, and merge that list with the keyword list.
Common misunderstanding: "Average the BM25 score and the cosine similarity." The two scales are unrelated (BM25 is unbounded and query-dependent; cosine lies in [-1, 1]); a weighted sum needs normalisation that drifts per query. Rank-based fusion (RRF) avoids calibration. Another: "ANN returns the true nearest neighbours." It returns approximately nearest ones; recall is a knob (num_candidates, ef_search).
Definition: a bi-encoder embedding model maps text to a dense vector (hundreds of dimensions); ANN (approximate nearest neighbour) indexes make top-k search sub-linear: HNSW builds layered proximity graphs and "allows a logarithmic complexity scaling" (Malkov and Yashunin); Elasticsearch "uses the HNSW algorithm to support efficient kNN search" and quantises float vectors by default (int8_hnsw, bbq_hnsw for 384+ dimensions in 9.x); IVF (inverted file) clusters vectors with k-means and searches only the nprobe nearest clusters (Faiss, pgvector ivfflat, Milvus; see Vector Search & pgvector). Hybrid search runs lexical and vector retrieval and fuses: RRF score = sum of 1 / (k + rank), where "k = 60 was fixed during a pilot investigation and not altered during subsequent validation" (Cormack et al.); Elasticsearch's rrf retriever has rank_constant (default 60) and rank_window_size; OpenSearch's hybrid query normalises scores (min_max, l2, z_score) or uses RRF. A cross-encoder reads query and document together and outputs a relevance score: far more accurate than a bi-encoder, far too slow for retrieval, so it re-ranks the top 50 to 200.
Query "shoes for wet trails" (no document contains "wet")
1 BM25 top: [shoe-rack, trail-runner, trail-socks, ...] rank of trail-runner = 2
2 kNN top : [waterproof-trail-shoe, trail-runner, gore-tex-boot] rank 1, 2, 3
3 RRF(60): trail-runner = 1/62 + 1/62 = 0.0323 ; waterproof = 1/61 = 0.0164 ; shoe-rack = 1/61 = 0.0164
4 fused: trail-runner, waterproof-trail-shoe, shoe-rack, ...
5 cross-encoder re-rank top 50: waterproof-trail-shoe 0.93, trail-runner 0.88, shoe-rack 0.05
6 final: waterproof, trail-runner, gore-tex-boot ... (shoe-rack demoted)Real scenario: "something to keep coffee hot" finding thermoses; Persian queries matching English product names through a multilingual model; SKU queries ("RTX 4070") that only BM25 gets right; a RAG system that retrieves passages with hybrid search before an LLM answers (see ML Systems).
What each product does:
| Product | Vectors and fusion |
|---|---|
| Elasticsearch | dense_vector (HNSW, int8/bbq quantisation), knn search, rrf retriever, semantic_text, text_similarity_reranker retriever |
| OpenSearch | k-NN plugin (Lucene, Faiss, NMSLIB engines; HNSW, IVF), neural search, hybrid query with normalization processor or RRF |
| Solr | DenseVectorField (HNSW), knn query parser |
| Vespa | Tensors, HNSW, multi-phase ranking with ONNX cross-encoders |
| Meilisearch / Typesense | Embedders and hybrid search with a semantic ratio or weights |
| Laravel Scout 13 | semantic() and hybrid(textWeight, semanticWeight) on database (pgvector), Meilisearch, Typesense, Turbopuffer engines |
| PostgreSQL | pgvector HNSW / IVFFlat, fused with FTS in SQL (see Vector Search & pgvector) |
How to use it: keep BM25, add kNN as a second retriever, fuse with RRF (the Go fusion package), re-rank the top 50 to 200 with a cross-encoder or LTR, and measure recall@100 of each retriever separately.
Indexing pipeline: outbox and CDC, bulk API, refresh, aliases, mappings, zero-downtime reindex Must-know
In plain words: the database changes, and a reliable conveyor carries that change into the search index within seconds; when the index shape must change, build a new index beside the old one and switch a pointer.
Common misunderstanding: "Write to the database and then to Elasticsearch in the same request." That dual write loses updates when the second call fails or reorders them under concurrency. Another: "change the mapping in place." You can add fields, but changing a field's type or analyzer needs a new index.
Definition: the write transaction stores the row and an outbox row (or CDC reads the WAL/binlog with Debezium); a relay or consumer turns changes into bulk API requests (_bulk NDJSON of index/update/delete actions; responses report per-item errors such as 429 es_rejected_execution_exception); documents are upserts by id, optionally with external versioning (version_type=external) so an old event cannot overwrite a newer one. Clients read and write through an alias: "you can use the aliases API to perform multiple actions in a single atomic operation", so a zero-downtime reindex is: create products_v8 with the new mapping (dynamic: strict to stop field explosions), backfill with _reindex or a database replay, catch up from the change log, swap the alias, keep v7 for rollback. See Transactional Outbox and Change Data Capture for the delivery mechanics.
Price change for product 42 at T0
1 T0.000 BEGIN; UPDATE products ...; INSERT INTO search_outbox(42,'upsert'); COMMIT
2 T0.200 relay polls (FOR UPDATE SKIP LOCKED), loads product 42 + brand
3 T0.250 POST _bulk {"index":{"_index":"products","_id":"42"}} {...} -> alias -> products_v7
4 T1.000 refresh -> searchable; lag SLI = 1.0 s
5 reindex: v8 built from DB snapshot at S, then outbox events after S replayed into v8
6 POST _aliases {remove v7, add v8 is_write_index} -> one atomic switch, no failed readsReal scenario: a marketplace adding a Persian analyzer to title (type change: new index); a CDC pipeline that indexes 2,000 changes per second with 5 to 15 MB bulk requests; a reindex that dropped writes because the application wrote to products_v7 directly; the Laravel Scout queue that indexes on model events and the outbox relay that makes those events durable.
What each product does:
| Product | Bulk and zero-downtime |
|---|---|
| Elasticsearch / OpenSearch | _bulk, _reindex, aliases with is_write_index, data streams for append-only data |
| Solr | /update with JSON arrays; collection aliases; reindex by re-feeding |
| Meilisearch | addDocuments in batches (asynchronous tasks); swap-indexes for atomic swaps |
| Typesense | import JSONL; collection aliases |
| Algolia | saveObjects batches; operationIndex copy/move for atomic reindex |
| Vespa | Document API / feed client; schema changes that need refeed are flagged at deploy |
| Laravel Scout | Observers per model save, scout:import, scout:queue-import --chunk, searchable()/unsearchable() |
How to use it: never dual-write; use the outbox (the RelayProductOutbox command and schema.sql below) or CDC; bulk in 5 to 15 MB batches with retries on 429; always go through an alias; version the mapping in the repository; alert on indexing lag.
Index lifecycle: ILM, rollover, hot-warm-cold Good to know
In plain words: for data that grows by time (logs, events, query logs) start a new index every day or every 50 GB, keep recent ones on fast machines, move old ones to cheap machines, and delete the oldest.
Common misunderstanding: "ILM is for product search." Product catalogues are one living index behind an alias; ILM is for time-series (the search query log or click events are a good fit).
Definition: Elasticsearch ILM moves indices "through phases (hot, warm, cold, frozen, delete) based on pre-defined conditions": rollover creates a new write index at a size, document count or age (guidance: max_primary_shard_size 50 GB, min_primary_shard_size 10 GB), warm can shrink and force-merge read-only indices, cold and frozen move to cheaper data tiers or searchable snapshots, delete enforces retention. Data streams are the recommended wrapper. OpenSearch has the equivalent Index State Management (ISM).
Query-log data stream, policy: hot 1 day or 50 GB -> warm 7 days -> cold 30 days -> delete 90 days
1 day 0 .ds-search-events-000001 on hot nodes (SSD), receiving writes
2 day 1 rollover -> 000002 is the write index; 000001 still hot for queries
3 day 8 000001 -> warm: read-only, force-merge to 1 segment, shrink shards
4 day 38 -> cold tier (cheaper disks or searchable snapshot)
5 day 90 delete -> retention enforced (also satisfies privacy policy for raw queries)Real scenario: query and click logs for typeahead and LTR kept 90 days; observability logs in the same cluster that must not starve product search (separate tiers or clusters).
What each product does:
| Product | Time-based lifecycle |
|---|---|
| Elasticsearch | ILM, data streams, data tiers (hot, warm, cold, frozen) |
| OpenSearch | Index State Management (ISM), UltraWarm and cold storage on AWS |
| Solr | Time routed aliases |
| Meilisearch / Typesense / Algolia | Not designed for time-series retention; delete by filter |
How to use it: a data stream with ILM for search events, a plain alias without ILM for the catalogue, and retention set from the privacy policy.
Shards, replicas, routing and hot shards Must-know
In plain words: split the index into shards so several machines search in parallel; copy each shard so a node can die; choose how documents land on shards so one shard is not doing all the work.
Common misunderstanding: "More shards, more speed." Each query fans out to one copy of every shard; "searching a thousand 50MB shards will be substantially more expensive than searching a single 50GB shard containing the same data." Another: "the number of primaries can be changed any time." It is fixed at creation (_split and _shrink exist with constraints; usually you reindex).
Definition: a document goes to shard_num = hash(_routing) % num_primary_shards (with number_of_routing_shards refinements), where _routing defaults to _id. Custom routing (tenant id, seller id) sends a query to one shard instead of all; index.routing_partition_size spreads one routing value over several shards to avoid a hot shard. Guidance: "Aim for shard sizes between 10GB and 50GB" and "keep the number of documents on each shard below 200 million"; a node is limited to 1,000 non-frozen shards. Replicas serve reads and failover; adding replicas increases read throughput but not write throughput (every replica indexes every document, unless segment replication is used in OpenSearch).
10 M products, 80 GB primary data, 6 data nodes
1 size: 80 GB / 25 GB target -> 4 primaries (round to 6 for even spread) -> 13 GB each
2 replicas 1 -> 12 shard copies, 2 per node; one node lost -> replicas promoted
3 query: coordinating node -> 6 shards in parallel -> each returns top 24 ids + scores (query phase)
4 merge -> fetch phase reads _source for 24 docs from the shards that own them
5 hot shard: routing by seller_id, one seller has 30% of items -> that shard is 4x slower
6 fix: routing_partition_size 3, or route only small sellers, or no custom routingReal scenario: a catalogue index with 60 shards for 5 GB of data (heap and latency wasted); a multi-tenant SaaS using routing by tenant where one enterprise tenant creates a hot shard; deep pagination (from: 10000) that makes every shard sort 10,024 documents (use search_after with a point in time).
What each product does:
| Product | Partitioning |
|---|---|
| Elasticsearch / OpenSearch | Primary shards fixed at create, replicas dynamic, _routing, routing_partition_size, _split/_shrink |
| Solr (SolrCloud) | Shards and replicas per collection, compositeId router, shard splitting |
| Vespa | Content cluster redistributes buckets automatically on node changes |
| Meilisearch | Single node per index (replication and sharding in the enterprise/cloud offering, check docs) |
| Typesense | Each node holds the full dataset, Raft replication (no sharding) |
| Algolia | Managed; large indices use vendor-managed clusters |
How to use it: size by data (10 to 50 GB per shard), start with replicas = 1, route only when queries are always per tenant and tenants are similar in size, and read Sharding at System Level for the general rules.
Query cost, caches and circuit breakers Important
In plain words: some queries are cheap (a term in a filter), some are expensive (leading wildcards, deep pages, huge aggregations, scripts); caches make repeated work free, and circuit breakers reject a request before it eats all memory.
Common misunderstanding: "Caching the whole search response is enough." Most search queries are unique in the long tail; the engine's caches work at lower levels (filters per segment, shard-level aggregations), and the application cache is for the head (typeahead prefixes, top queries).
Definition: Elasticsearch has the node query cache (filter cache): "The results of queries used in the filter context are cached", LRU, default indices.queries.cache.size 10% of heap and up to 10,000 queries, per segment for segments with at least 10,000 documents, and "Term queries and queries used outside of a filter context are not eligible for caching"; the shard request cache (indices.requests.cache.size 1% of heap) caches whole shard responses for size: 0 requests such as aggregations, invalidated by refresh; the field data cache for text fields with fielddata (avoid). Circuit breakers: parent indices.breaker.total.limit 95% of heap with real-memory accounting (70% otherwise), request 60%, fielddata 40%; when one trips the request fails with circuit_breaking_exception (HTTP 429). Expensive query types can be disabled with search.allow_expensive_queries: false.
Facet request, 3 shards, aggregation only (size 0)
1 first call: each shard computes brand terms agg -> stores result in shard request cache
2 second call within 1 s: served from cache (same request body, same index state)
3 refresh happens -> cache entries for that shard invalidated
4 huge terms agg on seller_id (5 M values) -> request breaker estimates > 60% heap
5 -> 429 circuit_breaking_exception "[parent] Data too large" -> client backs off, query is boundedReal scenario: a dashboard that refreshes every 5 s and is served by the request cache; a bot sending *phone* wildcards that saturates CPU until expensive queries are disabled and rate limiting is applied (Rate Limiting); a cluster that went down from out-of-memory before breakers were tuned.
What each product does:
| Product | Caches and protection |
|---|---|
| Elasticsearch | Node query cache, shard request cache, field data cache, circuit breakers, search.allow_expensive_queries, max_result_window |
| OpenSearch | Same family (fork); query insights plugin for top queries |
| Solr | filterCache, queryResultCache, documentCache; timeAllowed; circuit breakers (Solr 8+) |
| Vespa | Query timeouts and degradation, coverage reporting |
| Meilisearch / Typesense / Algolia | Managed caches; limits on result windows; rate limits on hosted plans |
| Application | Redis or Laravel cache for typeahead and head queries (Caching) |
How to use it: constraints in filter, aggregations with size: 0 where possible, search_after instead of deep from, timeouts on every request, breakers left at defaults unless measured, and an application cache only for the head.
Consistency: eventual, read-after-write via refresh Important
In plain words: the index trails the database by the pipeline lag plus the refresh interval; users notice only when they just changed something themselves.
Common misunderstanding: "Force refresh=true on every write to be safe." Each forced refresh creates a tiny segment; under load this multiplies merges and slows indexing and search. Read-after-write is needed for the writer, not for everyone.
Definition: search is eventually consistent with the source of truth: lag = relay delay + bulk time + time to next refresh. For read-after-write, options are: ?refresh=wait_for on that one write ("it's recommended to use the index API's refresh=wait_for query parameter option" when an application indexes and then searches), reading the just-changed entity from the database by id (realtime GET by id in Elasticsearch also reads the translog), or merging the user's pending changes into the response client-side. Replicas may also differ briefly; preference keeps a user on the same shard copies for stable pagination. See Consistency Models.
Seller edits a title and returns to "my listings" search
1 T0 DB commit + outbox row
2 T0.3 bulk index (no refresh)
3 T0.5 seller's list page queries search -> old title (not refreshed) <- complaint
4 fix A: the seller-facing write uses refresh=wait_for -> response returns at T1.0, page shows new title
5 fix B: "my listings" reads from the database (owner view), search is for buyersReal scenario: admin screens backed by the database while the storefront uses search; inventory that must not be sold from stale search (re-check stock in the database at add-to-cart); a "delete my data" request that must also be visible as gone (delete plus wait_for).
What each product does:
| Product | Read-your-writes options |
|---|---|
| Elasticsearch / OpenSearch | refresh=wait_for, refresh=true, realtime GET by id, preference |
| Solr | Real-time get handler, soft commits |
| Meilisearch / Algolia | Wait for the indexing task to complete |
| Typesense | Write is visible on the node that accepted it |
How to use it: treat search as a read model, use the database for owner and checkout views, wait_for on single interactive writes, and an SLI for indexing lag.
Multi-tenancy: index per tenant or shared index with a filter Important
In plain words: in a SaaS each customer must search only their own data; either give each one an index or share one index and always filter by tenant.
Common misunderstanding: "One index per tenant is the safe default." With thousands of tenants that means thousands of indices and shards, cluster-state and heap overhead (the docs ask for at least 1 GB of master heap per 3,000 indices); shared indices with mandatory filters scale better for many small tenants.
Definition: index per tenant gives isolation, per-tenant mappings, analyzers and easy deletion, at a per-index cost; shared index with tenant_id keyword, a mandatory filter, and routing by tenant (with routing_partition_size for large ones) is cheap but needs enforcement: filtered aliases per tenant, document-level security (Elasticsearch, OpenSearch security plugin), or scoped API keys (Algolia secured API keys, Typesense scoped search keys, Meilisearch tenant tokens). Hybrid: big tenants get their own index, the long tail shares. IDF is computed per shard, so in a shared index one tenant's vocabulary affects another tenant's scores. See Multi-Tenancy Strategies.
Shared index, tenant 7 searches "invoice"
1 API derives tenant from the auth token, never from the query string
2 query: bool { must: match invoice, filter: term tenant_id=7 }, routing=7
3 one shard (or 3 with partition size 3) searched instead of all 12
4 bug path: a developer forgets the filter -> tenant 7 sees tenant 9's invoices
5 defence: filtered alias "tenant-7" or DLS role; the app can only query that alias / keyReal scenario: a helpdesk SaaS with 20,000 small tenants in one index and 15 large tenants in their own; a tenant offboarding that must delete all its documents (_delete_by_query versus dropping an index); a hosted-search key leaked from a browser that must be scoped to one tenant.
What each product does:
| Product | Tenant isolation |
|---|---|
| Elasticsearch | Filtered aliases, document and field level security, API keys with role descriptors |
| OpenSearch | Security plugin with DLS/FLS, tenants for dashboards |
| Solr | Collection per tenant or fq filters; rule-based authorization |
| Meilisearch | Tenant tokens with embedded filters |
| Typesense | Scoped API keys with embedded filter_by |
| Algolia | Secured API keys with filters |
How to use it: derive tenant id server-side, enforce with an alias or a scoped key, route by tenant, and graduate large tenants to their own index.
Observability: latency percentiles, zero-result rate, CTR Important
In plain words: watch both whether search is fast and whether it is useful; a fast search that finds nothing is broken.
Common misunderstanding: "Average latency is fine." Search fans out to shards, so the p99 of one shard becomes the median of the request (see Latency Budgets); and system metrics say nothing about relevance.
Definition: system SLIs: p50/p95/p99 latency for search and typeahead separately, error and rejection rate (429s), indexing lag (commit to searchable), heap and breaker trips, slow logs (index.search.slowlog.threshold.query.warn). Quality SLIs: zero-result rate (share of searches with no hits), CTR (searches with at least one click), time to first click, reformulation rate (another search within seconds), abandonment, conversion per search, suggestion acceptance rate. Track quality per query band (head, torso, tail) and per locale.
Daily review
1 p99 search 180 ms (SLO 300 ms) ok ; p99 typeahead 70 ms (SLO 100 ms) ok
2 zero-result rate 6.1% (was 3.8%) -> top zero-result queries: "آیفون ۱۵", "iphone15"
3 cause: new Persian digits in queries, analyzer missing decimal_digit on the suggest field
4 fix + reindex suggest field -> zero-result rate back to 3.9%
5 CTR unchanged, reformulations down -> confirms the fixReal scenario: a weekly "top zero-result queries" report that drives synonyms and catalogue gaps; a latency regression caused by a new aggregation; a CTR drop after a UI change, not a ranking change.
What each product does:
| Product | Observability |
|---|---|
| Elasticsearch / OpenSearch | _nodes/stats, slow logs, profile API ("profile": true), _cat/*, Kibana / OpenSearch Dashboards |
| Solr | Metrics API, slow request logging |
| Algolia / Meilisearch / Typesense | Vendor analytics (top searches, no-result searches) on hosted plans |
| Application | Search events table (SQL below), OpenTelemetry spans (Observability) |
How to use it: log every search (query, normalised query, variant, result count, latency, shown ids) and every click; dashboard zero-result rate and CTR next to latency; alert on indexing lag.
Products: Elasticsearch, OpenSearch, Solr, Meilisearch, Typesense, Vespa, Algolia
What each product really is (the defaults that matter):
| Product | Model | Strengths | Watch out for |
|---|---|---|---|
| Elasticsearch | Lucene-based distributed engine, Elastic licence choices (Elastic License, SSPL, AGPL added in 2024) | Richest query DSL, aggregations, vectors, RRF, LTR, ecosystem | Operational weight; some features are subscription-gated |
| OpenSearch | Apache-2.0 fork of Elasticsearch 7.10, Linux Foundation project | Open licence, k-NN with Faiss, hybrid query, AWS managed service | APIs diverged after 7.10; clients differ (opensearch-go) |
| Solr | Apache Lucene project's server | Mature, schema-driven, LTR module, good for on-premise | Smaller cloud ecosystem; SolrCloud plus ZooKeeper |
| Meilisearch | Rust, single binary, typo-tolerant by default | Great developer experience, instant search, Scout driver | Ranking rules instead of BM25; large-scale sharding in enterprise/cloud |
| Typesense | C++, in-memory, Raft cluster | Fast, simple, Scout driver, scoped keys | Dataset must fit in RAM on every node |
| Vespa | Search, recommendation and ML ranking engine (from Yahoo) | Multi-phase ranking with models on content nodes, tensors, large scale | Steeper learning curve; Java searchers |
| Algolia | Hosted SaaS | Speed out of the box, analytics, A/B tests, Query Suggestions | Cost per record and operation; vendor lock-in |
| PostgreSQL FTS (+ pgvector) | In the database | No new system, transactional freshness | Limited ranking and analysis; see Full-Text Search |
Licences, fork history and internal data structures of Meilisearch and Typesense in this table are from general knowledge and vendor pages not saved for this chapter; the ranking rules (Meilisearch), _text_match (Typesense), rank phases (Vespa) and Scout drivers were read on the saved pages.
Mechanics
Knobs and defaults, per product
| Product | Knob | Default or value | Effect |
|---|---|---|---|
| Elasticsearch | index.refresh_interval | 1s (skipped for indices idle 30 s) | Freshness versus segment churn |
| Elasticsearch | ?refresh= | false; wait_for; true | Visibility of one write |
| Elasticsearch | BM25 k1 / b | 1.2 / 0.75 | Saturation / length normalisation |
| Elasticsearch | number_of_shards | 1 (since 7.0) | Fixed at creation |
| Elasticsearch | number_of_replicas | 1 | Read capacity and HA |
| Elasticsearch | index.max_result_window | 10,000 | from + size cap; use search_after |
| Elasticsearch | edge_ngram min_gram / max_gram | 1 / 2 | Always set explicitly |
| Elasticsearch | rrf rank_constant / rank_window_size | 60 / size | Fusion weight of lower ranks / depth |
| Elasticsearch | knn k, num_candidates | your choice (for example 50 / 200) | Recall versus latency |
| Elasticsearch | indices.queries.cache.size | 10% of heap | Filter cache |
| Elasticsearch | indices.requests.cache.size | 1% of heap | Shard request cache |
| Elasticsearch | indices.breaker.total.limit | 95% heap (real memory) | Parent breaker |
| Elasticsearch | indices.breaker.request.limit / fielddata.limit | 60% / 40% | Per-request and fielddata breakers |
| Elasticsearch | Shard size guidance | 10 to 50 GB, under 200 M docs | Sizing |
| Elasticsearch | cluster.max_shards_per_node | 1,000 non-frozen | Shard count ceiling |
| Lucene | Postings block | 128 ints; skip levels every block and 32 blocks | AND/phrase speed |
| Lucene | TieredMergePolicy | default merge policy | Segment counts and delete reclaim |
| Meilisearch | rankingRules | words, typo, proximity, attributeRank, sort, wordPosition, exactness | Order is the ranking |
| Typesense | text_match_type | max_score | Per-field aggregation of text match |
| Scout | queue | false | true moves indexing to queue workers |
(Values not on the saved pages and taken from general Elasticsearch knowledge: number_of_shards 1, number_of_replicas 1, index.max_result_window 10,000, the setting name cluster.max_shards_per_node.)
What goes wrong, verbatim
| Error or symptom | Meaning | Fix |
|---|---|---|
429 es_rejected_execution_exception | Write or search thread pool queue full | Back off and retry with jitter; smaller bulks; more nodes |
circuit_breaking_exception ... [parent] Data too large | A breaker estimated memory over its limit | Bound aggregations, smaller size, more heap or nodes |
illegal_argument_exception ... mapper [title] cannot be changed from type [text] to [keyword] | Field type change on an existing index | New index, reindex, alias swap |
strict_dynamic_mapping_exception | Document has a field not in a dynamic: strict mapping | Add the field to the mapping deliberately |
Result window is too large, from + size must be less than or equal to: [10000] | Deep pagination | search_after with a point in time |
search_phase_execution_exception with too_many_clauses | Query expanded into too many terms (wildcards, huge terms) | Limit expansions, use terms lookup or filters |
version_conflict_engine_exception (409) | Optimistic concurrency or external version older than stored | Expected for stale events; drop it |
index_not_found_exception after a deploy | Application wrote to a versioned name that was deleted | Always use the alias |
Bulk response "errors": true with HTTP 200 | Some items failed though the request succeeded | Inspect every item; retry failed ones |
| Zero results only for Arabic-keyboard input | Missing normalisation | arabic_normalization, persian_normalization |
(The exact text of these Elasticsearch messages comes from common usage; the documented facts checked for this chapter are the 429 retry advice, breaker names and defaults, and max_result_window.)
How a search request executes
GET /products/_search (6 primaries, 1 replica, coordinating node C)
1 C parses the query, resolves the alias -> products_v8, picks one copy of each shard (adaptive replica selection)
2 query phase: each shard runs the query on every segment, keeps a priority queue of top (from+size) ids and scores
3 each shard computes its aggregations from doc values, returns ids, scores, agg partials
4 C merges 6 queues -> global top 24; merges aggregations (approximate for terms)
5 optional rescore (LTR) per shard on the top window_size before step 4
6 fetch phase: C asks the owning shards for _source of 24 docs; highlights computed
7 response; took = slowest shard + merge + fetch -> tail latency is per-shard p99Go
Before
A substring scan with no analysis and no ranking: Arabic-keyboard input and capitalisation both return nothing, and cost is linear in the catalogue.
// Before: "search" as a substring scan over every row, ranked by nothing.
// It ignores word boundaries, case folding, Persian letter variants and
// relevance; cost grows linearly with the catalogue.
package main
import (
"fmt"
"strings"
)
type Product struct {
ID int
Title string
}
// search mimics WHERE title LIKE '%q%': every row is read, results come back
// in storage order, and "كتاب" (Arabic kaf/yeh) never matches "کتاب".
func search(rows []Product, q string) []Product {
var out []Product
for _, p := range rows {
if strings.Contains(p.Title, q) {
out = append(out, p)
}
}
return out
}
func main() {
rows := []Product{
{1, "Running shoes for trail"},
{2, "کتاب آموزش Go"},
{3, "Shoe rack"},
}
fmt.Println(search(rows, "shoes")) // misses "Shoe rack"? fine; misses "Shoes" capitalised
fmt.Println(search(rows, "كتاب")) // Arabic letters: zero results
fmt.Println(search(rows, "running")) // case sensitive: zero results
}After
analysis is the Persian-aware analyzer chain (letter folding, ZWNJ join or split, diacritics, digits, stop words, light stemming, edge n-grams):
// Package analysis is a small Lucene-style analyzer chain: char filter,
// tokenizer, token filters. It is Persian-aware: it unifies Arabic and
// Persian letter variants, removes diacritics, treats ZWNJ (U+200C) the way
// the Elasticsearch persian analyzer does, folds digits and drops stop words.
package analysis
import (
"strings"
"unicode"
)
// ZWNJ is the zero-width non-joiner, the Persian "half-space".
const ZWNJ = ''
// ZWNJMode chooses how the half-space is treated.
type ZWNJMode int
const (
// ZWNJSplit replaces ZWNJ with a space, as the Elasticsearch persian
// analyzer's zero_width_spaces char filter does ("میروم" -> "می" "روم").
ZWNJSplit ZWNJMode = iota
// ZWNJJoin removes ZWNJ so the word stays one token ("میروم").
ZWNJJoin
)
// Analyzer holds the configuration of one analysis chain.
type Analyzer struct {
ZWNJ ZWNJMode
StopWords map[string]bool
Stem bool
}
// Default returns an analyzer with Persian and English stop words.
func Default() *Analyzer {
sw := map[string]bool{}
for _, w := range []string{"the", "a", "an", "of", "for", "and", "to", "in",
"و", "در", "به", "از", "که", "را", "با", "این", "برای"} {
sw[w] = true
}
return &Analyzer{ZWNJ: ZWNJJoin, StopWords: sw, Stem: true}
}
var letterMap = map[rune]rune{
'ي': 'ی', // Arabic yeh -> Persian yeh
'ى': 'ی', // alef maksura -> Persian yeh
'ك': 'ک', // Arabic kaf -> Persian keheh
'ة': 'ه', // teh marbuta -> heh
'ۀ': 'ه', // heh with yeh above -> heh
'أ': 'ا', 'إ': 'ا', 'آ': 'ا', // alef variants -> alef (search-time folding)
'ؤ': 'و',
}
// Normalize applies the char filter and the normalisation token filters.
func (a *Analyzer) Normalize(s string) string {
var b strings.Builder
for _, r := range s {
switch {
case r == ZWNJ:
if a.ZWNJ == ZWNJSplit {
b.WriteRune(' ')
}
continue
case r == 'ـ': // tatweel (kashida)
continue
case r >= 'ً' && r <= 'ٟ': // harakat (diacritics)
continue
case r >= '۰' && r <= '۹': // Persian digits
b.WriteRune('0' + (r - '۰'))
continue
case r >= '٠' && r <= '٩': // Arabic-Indic digits
b.WriteRune('0' + (r - '٠'))
continue
}
if m, ok := letterMap[r]; ok {
r = m
}
b.WriteRune(unicode.ToLower(r))
}
return b.String()
}
// Tokenize splits on anything that is not a letter or a digit.
func Tokenize(s string) []string {
return strings.FieldsFunc(s, func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsDigit(r)
})
}
// stemEnglish is a deliberately tiny suffix stripper (not Porter).
func stemEnglish(t string) string {
for _, suf := range []string{"ies", "es", "s"} {
if len(t) > len(suf)+2 && strings.HasSuffix(t, suf) && isASCII(t) {
if suf == "ies" {
return strings.TrimSuffix(t, suf) + "y"
}
if suf == "es" && !strings.HasSuffix(t, "shes") && !strings.HasSuffix(t, "ches") && !strings.HasSuffix(t, "xes") {
return strings.TrimSuffix(t, "s")
}
return strings.TrimSuffix(t, suf)
}
}
return t
}
// stemPersian strips the plural suffixes "ها" and "های" (light stemming).
func stemPersian(t string) string {
for _, suf := range []string{"های", "ها"} {
if strings.HasSuffix(t, suf) && len([]rune(t)) > len([]rune(suf))+1 {
return strings.TrimSuffix(t, suf)
}
}
return t
}
func isASCII(s string) bool {
for _, r := range s {
if r > unicode.MaxASCII {
return false
}
}
return true
}
// Analyze runs the full chain and returns index terms in order.
func (a *Analyzer) Analyze(s string) []string {
toks := Tokenize(a.Normalize(s))
out := toks[:0]
for _, t := range toks {
if a.StopWords[t] {
continue
}
if a.Stem {
if isASCII(t) {
t = stemEnglish(t)
} else {
t = stemPersian(t)
}
}
out = append(out, t)
}
return out
}
// EdgeNGrams returns the prefixes of t with length min..max (in runes),
// the index-time trick behind search-as-you-type.
func EdgeNGrams(t string, min, max int) []string {
r := []rune(t)
var out []string
for n := min; n <= max && n <= len(r); n++ {
out = append(out, string(r[:n]))
}
return out
}package analysis
import (
"reflect"
"testing"
)
func TestPersianNormalization(t *testing.T) {
a := Default()
// Arabic kaf and yeh, typed on an Arabic keyboard, must equal the Persian form.
if got, want := a.Analyze("كتاب علمي"), a.Analyze("کتاب علمی"); !reflect.DeepEqual(got, want) {
t.Fatalf("got %v want %v", got, want)
}
}
func TestZWNJ(t *testing.T) {
join := Default()
if got := join.Analyze("میروم"); !reflect.DeepEqual(got, []string{"میروم"}) {
t.Fatalf("join: %v", got)
}
split := Default()
split.ZWNJ = ZWNJSplit
if got := split.Analyze("میروم"); !reflect.DeepEqual(got, []string{"می", "روم"}) {
t.Fatalf("split: %v", got)
}
}
func TestDigitsStopWordsStem(t *testing.T) {
a := Default()
got := a.Analyze("کتابهای Go برای ۱۴۰۳ and the Shoes")
want := []string{"کتاب", "go", "1403", "shoe"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v want %v", got, want)
}
}
func TestEdgeNGrams(t *testing.T) {
if got := EdgeNGrams("کفش", 1, 5); !reflect.DeepEqual(got, []string{"ک", "کف", "کفش"}) {
t.Fatalf("got %v", got)
}
}index is the inverted index with postings, positions, skip pointers, BM25 with k1 and b, BM25F, phrase queries and a gauss decay:
// Package index is an in-memory inverted index: a term dictionary mapping each
// term to a postings list (doc id, term frequency, positions) per field, plus
// field lengths (norms) and a BM25 / BM25F scorer.
package index
import (
"math"
"sort"
"academy/search-systems/analysis"
)
// Posting is one entry of a postings list.
type Posting struct {
Doc int
TF int
Positions []int
}
// Postings is sorted by Doc. Skip pointers every SkipEvery entries let an
// AND query jump ahead instead of walking every entry (Lucene interleaves
// two levels of skip data with its 128-entry blocks).
type Postings struct {
List []Posting
Skips []int // indexes into List
}
// SkipEvery is the skip interval.
const SkipEvery = 4
// Params are the BM25 knobs; Elasticsearch and Lucene default to 1.2 and 0.75.
type Params struct {
K1 float64
B float64
}
// DefaultParams mirrors the Lucene BM25Similarity defaults.
var DefaultParams = Params{K1: 1.2, B: 0.75}
// Index is a multi-field inverted index.
type Index struct {
an *analysis.Analyzer
dict map[string]map[string]*Postings // field -> term -> postings
lengths map[string]map[int]int // field -> doc -> length in terms
total map[string]int // field -> sum of lengths
docs map[int]bool
Params Params
}
// New creates an empty index.
func New(an *analysis.Analyzer) *Index {
return &Index{an: an, dict: map[string]map[string]*Postings{},
lengths: map[string]map[int]int{}, total: map[string]int{},
docs: map[int]bool{}, Params: DefaultParams}
}
// Add indexes a document. Doc ids must be added in increasing order, as a
// segment writer assigns them.
func (ix *Index) Add(doc int, fields map[string]string) {
ix.docs[doc] = true
for f, text := range fields {
terms := ix.an.Analyze(text)
if ix.dict[f] == nil {
ix.dict[f] = map[string]*Postings{}
ix.lengths[f] = map[int]int{}
}
ix.lengths[f][doc] = len(terms)
ix.total[f] += len(terms)
pos := map[string][]int{}
for i, t := range terms {
pos[t] = append(pos[t], i)
}
for t, p := range pos {
pl := ix.dict[f][t]
if pl == nil {
pl = &Postings{}
ix.dict[f][t] = pl
}
if len(pl.List)%SkipEvery == 0 {
pl.Skips = append(pl.Skips, len(pl.List))
}
pl.List = append(pl.List, Posting{Doc: doc, TF: len(p), Positions: p})
}
}
}
// N is the number of documents.
func (ix *Index) N() int { return len(ix.docs) }
// DF is the document frequency of a term in a field.
func (ix *Index) DF(field, term string) int {
if pl := ix.dict[field][term]; pl != nil {
return len(pl.List)
}
return 0
}
// IDF is the Lucene BM25 idf: ln(1 + (N - df + 0.5) / (df + 0.5)), never negative.
func (ix *Index) IDF(field, term string) float64 {
n, df := float64(ix.N()), float64(ix.DF(field, term))
return math.Log(1 + (n-df+0.5)/(df+0.5))
}
func (ix *Index) avgLen(field string) float64 {
if ix.N() == 0 {
return 0
}
return float64(ix.total[field]) / float64(ix.N())
}
// termWeight is the BM25 saturation and length normalisation for one term.
func (ix *Index) termWeight(tf, dl int, avgdl float64) float64 {
k1, b := ix.Params.K1, ix.Params.B
f := float64(tf)
return f * (k1 + 1) / (f + k1*(1-b+b*float64(dl)/avgdl))
}
// Hit is a scored document.
type Hit struct {
Doc int
Score float64
}
// SearchBM25 scores one field with OR semantics.
func (ix *Index) SearchBM25(field, query string, k int) []Hit {
scores := map[int]float64{}
avg := ix.avgLen(field)
for _, t := range ix.an.Analyze(query) {
pl := ix.dict[field][t]
if pl == nil {
continue
}
idf := ix.IDF(field, t)
for _, p := range pl.List {
scores[p.Doc] += idf * ix.termWeight(p.TF, ix.lengths[field][p.Doc], avg)
}
}
return topK(scores, k)
}
// SearchBM25F implements simple BM25F: per-field term frequencies are
// length-normalised, weighted by the field boost and summed BEFORE the
// saturation, so a term repeated in title and body does not count twice.
// IDF is taken from the first field (a common simplification).
func (ix *Index) SearchBM25F(query string, boosts map[string]float64, k int) []Hit {
scores := map[int]float64{}
fields := make([]string, 0, len(boosts))
for f := range boosts {
fields = append(fields, f)
}
sort.Strings(fields)
k1, b := ix.Params.K1, ix.Params.B
for _, t := range ix.an.Analyze(query) {
pseudo := map[int]float64{}
df := 0
for _, f := range fields {
pl := ix.dict[f][t]
if pl == nil {
continue
}
if len(pl.List) > df {
df = len(pl.List)
}
avg := ix.avgLen(f)
for _, p := range pl.List {
norm := 1 - b + b*float64(ix.lengths[f][p.Doc])/avg
pseudo[p.Doc] += boosts[f] * float64(p.TF) / norm
}
}
if df == 0 {
continue
}
n := float64(ix.N())
idf := math.Log(1 + (n-float64(df)+0.5)/(float64(df)+0.5))
for d, tf := range pseudo {
scores[d] += idf * tf * (k1 + 1) / (tf + k1)
}
}
return topK(scores, k)
}
// And returns docs containing every term in field, using skip pointers.
// It also returns how many postings were examined.
func (ix *Index) And(field string, terms ...string) ([]int, int) {
lists := make([]*Postings, 0, len(terms))
for _, t := range terms {
pl := ix.dict[field][t]
if pl == nil {
return nil, 0
}
lists = append(lists, pl)
}
sort.Slice(lists, func(i, j int) bool { return len(lists[i].List) < len(lists[j].List) })
examined := 0
var out []int
for _, p := range lists[0].List {
ok := true
for _, other := range lists[1:] {
found, n := advance(other, p.Doc)
examined += n
if !found {
ok = false
break
}
}
if ok {
out = append(out, p.Doc)
}
}
return out, examined
}
// advance finds target in pl, jumping along skip pointers first.
func advance(pl *Postings, target int) (bool, int) {
n, start := 0, 0
for _, s := range pl.Skips {
n++
if pl.List[s].Doc > target {
break
}
start = s
}
for i := start; i < len(pl.List); i++ {
n++
if pl.List[i].Doc == target {
return true, n
}
if pl.List[i].Doc > target {
return false, n
}
}
return false, n
}
// Phrase returns docs where terms appear consecutively (uses positions).
func (ix *Index) Phrase(field, phrase string) []int {
terms := ix.an.Analyze(phrase)
if len(terms) == 0 {
return nil
}
cand, _ := ix.And(field, terms...)
var out []int
for _, d := range cand {
first := ix.positions(field, terms[0], d)
for _, start := range first {
ok := true
for i := 1; i < len(terms); i++ {
if !contains(ix.positions(field, terms[i], d), start+i) {
ok = false
break
}
}
if ok {
out = append(out, d)
break
}
}
}
return out
}
func (ix *Index) positions(field, term string, doc int) []int {
for _, p := range ix.dict[field][term].List {
if p.Doc == doc {
return p.Positions
}
}
return nil
}
func contains(xs []int, v int) bool {
for _, x := range xs {
if x == v {
return true
}
}
return false
}
func topK(scores map[int]float64, k int) []Hit {
hits := make([]Hit, 0, len(scores))
for d, s := range scores {
hits = append(hits, Hit{d, s})
}
sort.Slice(hits, func(i, j int) bool {
if hits[i].Score != hits[j].Score {
return hits[i].Score > hits[j].Score
}
return hits[i].Doc < hits[j].Doc
})
if k > 0 && len(hits) > k {
hits = hits[:k]
}
return hits
}
// Decay is the Elasticsearch-style gauss decay: 1 at origin (+offset),
// `decay` at distance `scale` from it.
func Decay(distance, scale, offset, decay float64) float64 {
d := math.Max(0, math.Abs(distance)-offset)
sigma2 := -scale * scale / (2 * math.Log(decay))
return math.Exp(-d * d / (2 * sigma2))
}package index
import (
"math"
"testing"
"academy/search-systems/analysis"
)
func build() *Index {
ix := New(analysis.Default())
docs := []map[string]string{
{"title": "Trail running shoes", "body": "Light shoes for running on trail and mud"},
{"title": "Shoe rack", "body": "Wooden rack holds ten shoes"},
{"title": "Running socks", "body": "Socks for running"},
{"title": "کفش کوهنوردی", "body": "کفشهای سبک برای کوه"},
{"title": "Leather boots", "body": "Boots boots boots boots boots boots boots shoes"},
}
for i, d := range docs {
ix.Add(i+1, d)
}
return ix
}
func TestIDFOrdering(t *testing.T) {
ix := build()
if ix.IDF("body", "mud") <= ix.IDF("body", "shoe") {
t.Fatal("a rare term must have a higher idf than a common one")
}
if ix.IDF("body", "missing") <= 0 {
t.Fatal("Lucene idf is never negative")
}
}
func TestSaturation(t *testing.T) {
ix := build()
w1 := ix.termWeight(1, 10, 10)
w100 := ix.termWeight(100, 10, 10)
if w100 > ix.Params.K1+1 || w100 < w1 {
t.Fatalf("tf weight must grow and stay below k1+1: %v %v", w1, w100)
}
ix.Params.B = 0
if ix.termWeight(3, 100, 10) != ix.termWeight(3, 1, 10) {
t.Fatal("b=0 must disable length normalisation")
}
}
func TestBM25Ranking(t *testing.T) {
ix := build()
hits := ix.SearchBM25("body", "running shoes", 3)
if hits[0].Doc != 1 {
t.Fatalf("doc 1 has both terms, got %+v", hits)
}
}
func TestBM25FTitleBoost(t *testing.T) {
ix := build()
hits := ix.SearchBM25F("shoe", map[string]float64{"title": 3, "body": 1}, 5)
if hits[0].Doc != 2 && hits[0].Doc != 1 {
t.Fatalf("a title match must lead, got %+v", hits)
}
for _, h := range hits {
if h.Doc == 5 && h.Score >= hits[0].Score {
t.Fatal("a body-only mention must not beat title matches")
}
}
}
func TestPersianSearch(t *testing.T) {
ix := build()
// Arabic kaf typed by the user, plural with ZWNJ in the document.
hits := ix.SearchBM25("body", "كفش", 5)
if len(hits) != 1 || hits[0].Doc != 4 {
t.Fatalf("got %+v", hits)
}
}
func TestAndAndPhrase(t *testing.T) {
ix := build()
docs, _ := ix.And("body", "running", "trail")
if len(docs) != 1 || docs[0] != 1 {
t.Fatalf("and: %v", docs)
}
if got := ix.Phrase("title", "running shoes"); len(got) != 1 || got[0] != 1 {
t.Fatalf("phrase: %v", got)
}
if got := ix.Phrase("title", "shoes running"); len(got) != 0 {
t.Fatalf("wrong order must not match: %v", got)
}
}
func TestSkipPointersSaveWork(t *testing.T) {
ix := New(analysis.Default())
for d := 1; d <= 1000; d++ {
f := map[string]string{"body": "common"}
if d%250 == 0 {
f["body"] = "common rare"
}
ix.Add(d, f)
}
docs, examined := ix.And("body", "rare", "common")
if len(docs) != 4 {
t.Fatalf("got %v", docs)
}
if examined >= 1000 {
t.Fatalf("skip pointers should avoid a full walk, examined %d", examined)
}
}
func TestDecay(t *testing.T) {
if math.Abs(Decay(0, 10, 0, 0.5)-1) > 1e-9 || math.Abs(Decay(10, 10, 0, 0.5)-0.5) > 1e-9 {
t.Fatal("gauss decay must be 1 at origin and 0.5 at scale")
}
if Decay(3, 10, 5, 0.5) != 1 {
t.Fatal("inside offset there is no decay")
}
}typeahead is the prefix trie with top-K per node and personalised re-ranking:
// Package typeahead is a prefix trie whose nodes cache the top-K completions
// by popularity, so a lookup costs O(len(prefix)) and never walks the subtree.
// Personalisation is a re-rank of those K candidates with a per-user boost.
package typeahead
import (
"sort"
"sync"
"academy/search-systems/analysis"
)
// Suggestion is one completion and its popularity weight.
type Suggestion struct {
Text string
Weight float64
}
type node struct {
children map[rune]*node
top []Suggestion // best K completions below this node
}
// Trie is safe for concurrent readers and one writer at a time.
type Trie struct {
mu sync.RWMutex
root *node
k int
an *analysis.Analyzer
all map[string]float64
}
// New builds a trie that keeps k completions per node.
func New(k int, an *analysis.Analyzer) *Trie {
return &Trie{root: &node{children: map[rune]*node{}}, k: k, an: an, all: map[string]float64{}}
}
// Add inserts or re-weights a query string (weights usually come from the
// query log: count of searches that led to a click, decayed by age).
func (t *Trie) Add(text string, weight float64) {
t.mu.Lock()
defer t.mu.Unlock()
key := t.an.Normalize(text)
t.all[key] = weight
s := Suggestion{Text: key, Weight: weight}
n := t.root
t.offer(n, s)
for _, r := range key {
c := n.children[r]
if c == nil {
c = &node{children: map[rune]*node{}}
n.children[r] = c
}
n = c
t.offer(n, s)
}
}
// offer keeps n.top sorted and bounded to k (replacing an older weight).
func (t *Trie) offer(n *node, s Suggestion) {
for i := range n.top {
if n.top[i].Text == s.Text {
n.top = append(n.top[:i], n.top[i+1:]...)
break
}
}
n.top = append(n.top, s)
sort.Slice(n.top, func(i, j int) bool {
if n.top[i].Weight != n.top[j].Weight {
return n.top[i].Weight > n.top[j].Weight
}
return n.top[i].Text < n.top[j].Text
})
if len(n.top) > t.k {
n.top = n.top[:t.k]
}
}
// Complete returns up to k suggestions for a prefix.
func (t *Trie) Complete(prefix string) []Suggestion {
t.mu.RLock()
defer t.mu.RUnlock()
n := t.root
for _, r := range t.an.Normalize(prefix) {
n = n.children[r]
if n == nil {
return nil
}
}
out := make([]Suggestion, len(n.top))
copy(out, n.top)
return out
}
// Personalize re-ranks candidates with weight * (1 + boost[text]); a cold
// start user (empty map) gets the global order unchanged.
func Personalize(c []Suggestion, boost map[string]float64) []Suggestion {
out := make([]Suggestion, len(c))
copy(out, c)
for i := range out {
out[i].Weight *= 1 + boost[out[i].Text]
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Weight > out[j].Weight })
return out
}package typeahead
import (
"testing"
"academy/search-systems/analysis"
)
func seed() *Trie {
t := New(3, analysis.Default())
t.Add("iphone 15", 900)
t.Add("iphone case", 500)
t.Add("ipad", 700)
t.Add("iphone charger", 300)
t.Add("کفش ورزشی", 400)
t.Add("کفش مجلسی", 100)
return t
}
func TestTopKByPopularity(t *testing.T) {
got := seed().Complete("ip")
if len(got) != 3 || got[0].Text != "iphone 15" || got[1].Text != "ipad" || got[2].Text != "iphone case" {
t.Fatalf("got %+v", got)
}
}
func TestPersianPrefixWithArabicKeyboard(t *testing.T) {
got := seed().Complete("كف") // Arabic kaf
if len(got) != 2 || got[0].Text != "کفش ورزشی" {
t.Fatalf("got %+v", got)
}
}
func TestReweight(t *testing.T) {
tr := seed()
tr.Add("iphone charger", 1000)
if got := tr.Complete("iph"); got[0].Text != "iphone charger" {
t.Fatalf("got %+v", got)
}
}
func TestPersonalizeAndColdStart(t *testing.T) {
c := seed().Complete("ip")
if got := Personalize(c, nil); got[0].Text != "iphone 15" {
t.Fatal("cold start must keep the global order")
}
if got := Personalize(c, map[string]float64{"iphone case": 1.0}); got[0].Text != "iphone case" {
t.Fatalf("got %+v", got)
}
}
func TestMissingPrefix(t *testing.T) {
if seed().Complete("zz") != nil {
t.Fatal("unknown prefix returns nil")
}
}fusion is RRF and min-max normalisation; metrics is NDCG, MRR and AP:
// Package fusion merges ranked lists. RRF (Cormack, Clarke and Buettcher,
// SIGIR 2009) uses only ranks: score(d) = sum over lists of 1 / (k + rank).
package fusion
import "sort"
// Result is a fused document and its RRF score.
type Result struct {
ID string
Score float64
}
// RRF fuses rankings (each a list of ids, best first). k = 60 is the paper's
// value and the Elasticsearch rank_constant default. Ranks start at 1.
func RRF(k float64, rankings ...[]string) []Result {
scores := map[string]float64{}
for _, r := range rankings {
for i, id := range r {
scores[id] += 1 / (k + float64(i+1))
}
}
out := make([]Result, 0, len(scores))
for id, s := range scores {
out = append(out, Result{id, s})
}
sort.Slice(out, func(i, j int) bool {
if out[i].Score != out[j].Score {
return out[i].Score > out[j].Score
}
return out[i].ID < out[j].ID
})
return out
}
// MinMax normalises raw scores to [0,1]; it is the score-based alternative
// (OpenSearch normalization processor min_max) that RRF avoids.
func MinMax(scores map[string]float64) map[string]float64 {
lo, hi := 0.0, 0.0
first := true
for _, s := range scores {
if first || s < lo {
lo = s
}
if first || s > hi {
hi = s
}
first = false
}
out := map[string]float64{}
for id, s := range scores {
if hi == lo {
out[id] = 1
} else {
out[id] = (s - lo) / (hi - lo)
}
}
return out
}package fusion
import (
"math"
"testing"
)
func TestRRF(t *testing.T) {
bm25 := []string{"a", "b", "c"}
vector := []string{"c", "a", "d"}
got := RRF(60, bm25, vector)
if got[0].ID != "a" {
t.Fatalf("a is 1st and 2nd, must win: %+v", got)
}
want := 1.0/61 + 1.0/62
if math.Abs(got[0].Score-want) > 1e-12 {
t.Fatalf("score %v want %v", got[0].Score, want)
}
if got[len(got)-1].ID != "d" && got[len(got)-1].ID != "b" {
t.Fatalf("single-list docs come last: %+v", got)
}
}
func TestSmallKFavoursTop(t *testing.T) {
// With k=1 the first rank of one list dominates; with k=60 agreement wins.
l1 := []string{"x", "p", "q", "y"}
l2 := []string{"z", "r", "s", "y"}
if RRF(1, l1, l2)[0].ID == "y" {
t.Fatal("k=1: a single first place should beat y")
}
if RRF(60, l1, l2)[0].ID != "y" {
t.Fatal("k=60: y appears in both lists and should lead")
}
}
func TestMinMax(t *testing.T) {
n := MinMax(map[string]float64{"a": 12.5, "b": 2.5, "c": 7.5})
if n["a"] != 1 || n["b"] != 0 || n["c"] != 0.5 {
t.Fatalf("%v", n)
}
}// Package metrics holds offline ranking metrics: DCG and NDCG (Jarvelin and
// Kekalainen 2002, with the common 2^rel - 1 gain), MRR and average precision.
package metrics
import (
"math"
"sort"
)
// DCG at k with gain 2^rel - 1 and discount log2(rank + 1).
func DCG(rels []float64, k int) float64 {
s := 0.0
for i := 0; i < len(rels) && i < k; i++ {
s += (math.Pow(2, rels[i]) - 1) / math.Log2(float64(i)+2)
}
return s
}
// NDCG at k: DCG of the ranking divided by DCG of the ideal ordering.
func NDCG(rels []float64, k int) float64 {
ideal := append([]float64(nil), rels...)
sort.Sort(sort.Reverse(sort.Float64Slice(ideal)))
d := DCG(ideal, k)
if d == 0 {
return 0
}
return DCG(rels, k) / d
}
// ReciprocalRank is 1 / rank of the first relevant result (0 if none).
func ReciprocalRank(relevant []bool) float64 {
for i, r := range relevant {
if r {
return 1 / float64(i+1)
}
}
return 0
}
// MRR averages reciprocal rank over queries.
func MRR(queries [][]bool) float64 {
if len(queries) == 0 {
return 0
}
s := 0.0
for _, q := range queries {
s += ReciprocalRank(q)
}
return s / float64(len(queries))
}
// AveragePrecision over a ranked list given the total number of relevant docs.
// MAP is its mean over queries.
func AveragePrecision(relevant []bool, totalRelevant int) float64 {
if totalRelevant == 0 {
return 0
}
hits, s := 0, 0.0
for i, r := range relevant {
if r {
hits++
s += float64(hits) / float64(i+1)
}
}
return s / float64(totalRelevant)
}package metrics
import (
"math"
"testing"
)
func near(a, b float64) bool { return math.Abs(a-b) < 1e-3 }
func TestNDCG(t *testing.T) {
if NDCG([]float64{3, 2, 1, 0}, 4) != 1 {
t.Fatal("ideal order must give 1")
}
got := NDCG([]float64{0, 1, 2, 3}, 4)
if got >= 1 || got <= 0 {
t.Fatalf("reversed order must be in (0,1): %v", got)
}
// DCG of [3,2,0] = 7/1 + 3/1.585 + 0 = 8.893
if !near(DCG([]float64{3, 2, 0}, 3), 8.893) {
t.Fatalf("dcg %v", DCG([]float64{3, 2, 0}, 3))
}
}
func TestMRR(t *testing.T) {
q := [][]bool{{false, true}, {true}, {false, false, false}}
if !near(MRR(q), (0.5+1+0)/3) {
t.Fatalf("mrr %v", MRR(q))
}
}
func TestAP(t *testing.T) {
// relevant at ranks 1 and 3, 2 relevant total: (1/1 + 2/3) / 2
if !near(AveragePrecision([]bool{true, false, true}, 2), (1+2.0/3)/2) {
t.Fatal("ap")
}
}The production calls with the official client (github.com/elastic/go-elasticsearch/v9): versioned index with a Persian analyzer and a completion field, esutil.BulkIndexer, atomic alias swap and a hybrid query with an rrf retriever. It exits when ES_URL is unset:
// Command esclient shows the production calls against Elasticsearch with the
// official client github.com/elastic/go-elasticsearch/v9: create a versioned
// index with a Persian analyzer and a completion field, bulk-load it with
// esutil.BulkIndexer, swap an alias atomically (zero-downtime reindex) and
// run a hybrid BM25 + kNN query fused with an RRF retriever.
// It exits immediately when ES_URL is not set, so it compiles and runs in CI.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/elastic/go-elasticsearch/v9"
"github.com/elastic/go-elasticsearch/v9/esutil"
)
const mapping = `{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"refresh_interval": "30s",
"analysis": {
"char_filter": {
"zwnj_to_space": { "type": "mapping", "mappings": ["\\u200C=>\\u0020"] }
},
"filter": {
"fa_stop": { "type": "stop", "stopwords": "_persian_" },
"edge_2_15": { "type": "edge_ngram", "min_gram": 2, "max_gram": 15 }
},
"analyzer": {
"fa_text": {
"tokenizer": "standard",
"char_filter": ["zwnj_to_space"],
"filter": ["lowercase", "decimal_digit", "arabic_normalization", "persian_normalization", "fa_stop"]
},
"fa_prefix": {
"tokenizer": "standard",
"filter": ["lowercase", "decimal_digit", "arabic_normalization", "persian_normalization", "edge_2_15"]
}
}
}
},
"mappings": {
"dynamic": "strict",
"properties": {
"title": { "type": "text", "analyzer": "fa_text",
"fields": { "prefix": { "type": "text", "analyzer": "fa_prefix", "search_analyzer": "fa_text" } } },
"brand": { "type": "keyword" },
"category": { "type": "keyword" },
"price": { "type": "scaled_float", "scaling_factor": 100 },
"popularity": { "type": "rank_feature" },
"in_stock": { "type": "boolean" },
"updated_at": { "type": "date" },
"suggest": { "type": "completion", "analyzer": "fa_text" },
"embedding": { "type": "dense_vector", "dims": 4, "index": true, "similarity": "cosine" }
}
}
}`
// Product is the indexed document (the search read model, not the DB row).
type Product struct {
ID string `json:"-"`
Title string `json:"title"`
Brand string `json:"brand"`
Category string `json:"category"`
Price float64 `json:"price"`
Popularity float64 `json:"popularity"`
InStock bool `json:"in_stock"`
UpdatedAt time.Time `json:"updated_at"`
Suggest any `json:"suggest"`
Embedding []float32 `json:"embedding"`
}
func main() {
url := os.Getenv("ES_URL")
if url == "" {
fmt.Println("ES_URL not set; skipping (this program needs a running cluster)")
return
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
es, err := elasticsearch.NewClient(elasticsearch.Config{Addresses: []string{url}})
if err != nil {
log.Fatal(err)
}
newIndex := "products_v" + time.Now().UTC().Format("20060102150405")
res, err := es.Indices.Create(newIndex, es.Indices.Create.WithBody(strings.NewReader(mapping)), es.Indices.Create.WithContext(ctx))
if err != nil {
log.Fatal(err)
}
res.Body.Close()
if res.IsError() {
log.Fatalf("create: %s", res.Status())
}
bi, err := esutil.NewBulkIndexer(esutil.BulkIndexerConfig{
Client: es, Index: newIndex, NumWorkers: 4, FlushBytes: 5 << 20, FlushInterval: time.Second,
})
if err != nil {
log.Fatal(err)
}
for _, p := range sample() {
body, _ := json.Marshal(p)
err := bi.Add(ctx, esutil.BulkIndexerItem{
Action: "index", DocumentID: p.ID, Body: strings.NewReader(string(body)),
OnFailure: func(_ context.Context, item esutil.BulkIndexerItem, r esutil.BulkIndexerResponseItem, err error) {
// 429 es_rejected_execution_exception means back off and retry.
log.Printf("bulk item %s failed: %v %s %s", item.DocumentID, err, r.Error.Type, r.Error.Reason)
},
})
if err != nil {
log.Fatal(err)
}
}
if err := bi.Close(ctx); err != nil {
log.Fatal(err)
}
log.Printf("bulk: %+v", bi.Stats())
// Make the new index searchable now (backfill done), then swap the alias.
if r, err := es.Indices.Refresh(es.Indices.Refresh.WithIndex(newIndex)); err == nil {
r.Body.Close()
}
swap := fmt.Sprintf(`{"actions":[
{"remove":{"index":"products_v*","alias":"products"}},
{"add":{"index":%q,"alias":"products","is_write_index":true}}]}`, newIndex)
r, err := es.Indices.UpdateAliases(strings.NewReader(swap), es.Indices.UpdateAliases.WithContext(ctx))
if err != nil {
log.Fatal(err)
}
r.Body.Close()
// Hybrid search: lexical + kNN fused by RRF (Elasticsearch 8.14+ retrievers).
query := `{
"retriever": { "rrf": {
"retrievers": [
{ "standard": { "query": { "bool": {
"must": { "multi_match": { "query": "كفش ورزشي", "fields": ["title^3", "title.prefix"] } },
"filter": [ { "term": { "in_stock": true } } ] } } } },
{ "knn": { "field": "embedding", "query_vector": [0.1, 0.8, 0.1, 0.0], "k": 50, "num_candidates": 200 } }
],
"rank_constant": 60, "rank_window_size": 50 } },
"aggs": { "brands": { "terms": { "field": "brand" } } },
"size": 10
}`
sr, err := es.Search(es.Search.WithIndex("products"), es.Search.WithBody(strings.NewReader(query)), es.Search.WithContext(ctx))
if err != nil {
log.Fatal(err)
}
defer sr.Body.Close()
fmt.Println(sr.Status())
}
func sample() []Product {
now := time.Now().UTC()
return []Product{
{ID: "1", Title: "کفش ورزشی نایکی", Brand: "nike", Category: "shoes", Price: 89.9, Popularity: 120, InStock: true, UpdatedAt: now,
Suggest: map[string]any{"input": []string{"کفش ورزشی", "nike running"}, "weight": 120}, Embedding: []float32{0.1, 0.9, 0.0, 0.0}},
{ID: "2", Title: "جاکفشی چوبی", Brand: "ikea", Category: "home", Price: 40, Popularity: 15, InStock: true, UpdatedAt: now,
Suggest: map[string]any{"input": []string{"جاکفشی"}, "weight": 15}, Embedding: []float32{0.7, 0.1, 0.2, 0.0}},
}
}A one-process demo used in the Lab:
// Command demo runs the whole pipeline in one process: analyze, index,
// BM25 vs BM25F, typeahead with personalisation, RRF fusion and NDCG.
package main
import (
"fmt"
"time"
"academy/search-systems/analysis"
"academy/search-systems/fusion"
"academy/search-systems/index"
"academy/search-systems/metrics"
"academy/search-systems/typeahead"
)
func main() {
an := analysis.Default()
fmt.Println("analyze:", an.Analyze("كتابهای Go برای ۱۴۰۳"))
ix := index.New(an)
docs := []map[string]string{
{"title": "Trail running shoes", "body": "Light shoes for running on trail"},
{"title": "Shoe rack", "body": "Wooden rack holds ten shoes"},
{"title": "Running socks", "body": "Socks for running"},
{"title": "Leather boots", "body": "Boots boots boots shoes"},
}
for i, d := range docs {
ix.Add(i+1, d)
}
fmt.Println("bm25 body :", ix.SearchBM25("body", "running shoes", 3))
fmt.Println("bm25f :", ix.SearchBM25F("running shoes", map[string]float64{"title": 3, "body": 1}, 3))
tr := typeahead.New(5, an)
for q, w := range map[string]float64{"iphone 15": 900, "ipad": 700, "iphone case": 500, "کفش ورزشی": 400} {
tr.Add(q, w)
}
start := time.Now()
c := tr.Complete("ip")
fmt.Printf("typeahead : %v (%v)\n", c, time.Since(start).Round(time.Microsecond))
fmt.Println("personal :", typeahead.Personalize(c, map[string]float64{"iphone case": 1}))
fmt.Println("rrf :", fusion.RRF(60, []string{"d1", "d2", "d3"}, []string{"d3", "d1", "d4"}))
fmt.Printf("ndcg@3 : %.3f\n", metrics.NDCG([]float64{2, 3, 0, 1}, 3))
}The Go angle
Go has no search library in the standard library; the realistic choices are an engine client or an embedded library. The official Elasticsearch client is github.com/elastic/go-elasticsearch (v8 and v9 modules side by side; this chapter pins v9.1.0 because v9.2+ raises the module's go directive above 1.24); it offers the low-level esapi functions used here, a typed API (NewTypedClient) and esutil.BulkIndexer for concurrent bulk loading with per-item callbacks. For OpenSearch the client is github.com/opensearch-project/opensearch-go (v5 at the time of writing, opensearchapi.NewClient); do not point the Elasticsearch v9 client at OpenSearch, since it checks the product header. Embedded options: Bleve (pure Go, inverted index and BM25-like scoring) for a single-binary search, or the small structures in this chapter for typeahead tries held in memory and refreshed from the query log. Rules that carry over: pass context.Context with a deadline to every search (typeahead under 100 ms), share one client (it pools connections), treat bulk errors: true per item, and normalise Persian text with the same function on the indexing and the query side.
Laravel
Before
-- What the Before controller runs: no index can serve a leading wildcard.
SELECT * FROM products WHERE title LIKE '%كتاب%' OR description LIKE '%كتاب%' LIMIT 20;<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
// Before: LIKE '%q%' on every keystroke. No index can serve a leading
// wildcard, there is no relevance order, "كتاب" (Arabic letters) never
// matches "کتاب", and the database takes every typeahead request.
class SearchController extends Controller
{
public function __invoke(Request $request)
{
$q = (string) $request->query('q', '');
return Product::query()
->where('title', 'like', '%'.$q.'%')
->orWhere('description', 'like', '%'.$q.'%')
->limit(20)
->get();
}
}After
A normaliser shared by indexing and querying:
<?php
namespace App\Search;
// The same normalisation at index time and at query time: Arabic yeh/kaf to
// Persian, ZWNJ removed (or turned into a space), diacritics and tatweel
// dropped, Persian and Arabic-Indic digits folded to ASCII, lower case.
final class PersianNormalizer
{
private const MAP = [
'ي' => 'ی', 'ى' => 'ی', 'ك' => 'ک', 'ة' => 'ه', 'ۀ' => 'ه',
'أ' => 'ا', 'إ' => 'ا', 'آ' => 'ا', 'ؤ' => 'و',
'۰' => '0', '۱' => '1', '۲' => '2', '۳' => '3', '۴' => '4',
'۵' => '5', '۶' => '6', '۷' => '7', '۸' => '8', '۹' => '9',
'٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4',
'٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9',
];
public static function normalize(string $text, bool $zwnjAsSpace = false): string
{
$text = strtr($text, self::MAP);
$text = str_replace("\u{200C}", $zwnjAsSpace ? ' ' : '', $text);
$text = preg_replace('/[\x{064B}-\x{065F}\x{0640}]/u', '', $text) ?? $text;
$text = preg_replace('/\s+/u', ' ', $text) ?? $text;
return mb_strtolower(trim($text));
}
}The searchable model (Scout Searchable trait, toSearchableArray, searchableAs, shouldBeSearchable, searchIndexShouldBeUpdated, makeAllSearchableUsing):
<?php
namespace App\Models;
use App\Search\PersianNormalizer;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Product extends Model
{
use Searchable;
protected $casts = ['in_stock' => 'boolean', 'price' => 'decimal:2'];
// Index name; the engine writes to the alias, never to a versioned index.
public function searchableAs(): string
{
return 'products';
}
// The search document is a read model: denormalised, normalised, small.
public function toSearchableArray(): array
{
return [
'id' => (string) $this->id,
'title' => PersianNormalizer::normalize($this->title),
'description' => PersianNormalizer::normalize((string) $this->description),
'brand' => $this->brand?->slug,
'category' => $this->category_slug,
'price' => (float) $this->price,
'in_stock' => $this->in_stock,
'popularity' => (int) $this->orders_30d,
'updated_at' => $this->updated_at?->toIso8601String(),
];
}
// Drafts and hidden products never reach the index.
public function shouldBeSearchable(): bool
{
return $this->published_at !== null && ! $this->is_hidden;
}
// Skip reindexing when only fields the index does not hold changed.
public function searchIndexShouldBeUpdated(): bool
{
return $this->wasRecentlyCreated
|| $this->wasChanged(['title', 'description', 'price', 'in_stock', 'brand_id', 'published_at', 'is_hidden']);
}
protected function makeAllSearchableUsing(Builder $query): Builder
{
return $query->with('brand');
}
public function brand()
{
return $this->belongsTo(Brand::class);
}
}A custom Scout engine for Elasticsearch (Scout has no first-party Elasticsearch driver), registered with EngineManager::extend:
<?php
namespace App\Search;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\LazyCollection;
use Laravel\Scout\Builder;
use Laravel\Scout\Engines\Engine;
use RuntimeException;
// Scout has no first-party Elasticsearch driver (Laravel 13 ships database,
// collection, Algolia, Meilisearch, Typesense and Turbopuffer). This custom
// engine implements the eight abstract methods with the HTTP client and the
// _bulk / _search / _delete_by_query REST APIs.
class ElasticsearchEngine extends Engine
{
public function __construct(private string $host, private ?string $apiKey = null)
{
}
private function http(): PendingRequest
{
$req = Http::baseUrl($this->host)->acceptJson()->timeout(5)->retry(3, 200, throw: false);
return $this->apiKey ? $req->withHeaders(['Authorization' => 'ApiKey '.$this->apiKey]) : $req;
}
public function update($models)
{
if ($models->isEmpty()) {
return;
}
$index = $models->first()->searchableAs();
$lines = '';
foreach ($models as $model) {
$doc = $model->toSearchableArray();
if ($doc === []) {
continue;
}
$lines .= json_encode(['index' => ['_index' => $index, '_id' => (string) $model->getScoutKey()]])."\n";
$lines .= json_encode($doc, JSON_UNESCAPED_UNICODE)."\n";
}
$res = $this->http()->withBody($lines, 'application/x-ndjson')->post('/_bulk');
if ($res->failed() || $res->json('errors') === true) {
// Per-item errors (for example 429 es_rejected_execution_exception)
// make the queued Scout job fail and retry.
throw new RuntimeException('Elasticsearch bulk failed: '.$res->body());
}
}
public function delete($models)
{
if ($models->isEmpty()) {
return;
}
$index = $models->first()->searchableAs();
$lines = '';
foreach ($models as $model) {
$lines .= json_encode(['delete' => ['_index' => $index, '_id' => (string) $model->getScoutKey()]])."\n";
}
$this->http()->withBody($lines, 'application/x-ndjson')->post('/_bulk');
}
public function search(Builder $builder)
{
return $this->performSearch($builder, ['size' => $builder->limit ?: 20]);
}
public function paginate(Builder $builder, $perPage, $page)
{
return $this->performSearch($builder, ['size' => $perPage, 'from' => ($page - 1) * $perPage]);
}
private function performSearch(Builder $builder, array $page): array
{
$filters = [];
foreach ($builder->wheres as $field => $value) {
$filters[] = ['term' => [$field => $value]];
}
foreach ($builder->whereIns as $field => $values) {
$filters[] = ['terms' => [$field => array_values($values)]];
}
$body = $page + [
'track_total_hits' => true,
'query' => [
'function_score' => [
'query' => ['bool' => [
'must' => [[
'multi_match' => [
'query' => PersianNormalizer::normalize($builder->query),
'fields' => ['title^3', 'description'],
'fuzziness' => 'AUTO',
],
]],
'filter' => $filters,
]],
'functions' => [
['field_value_factor' => ['field' => 'popularity', 'modifier' => 'log1p', 'missing' => 0]],
['gauss' => ['updated_at' => ['origin' => 'now', 'scale' => '30d', 'decay' => 0.5]]],
],
'boost_mode' => 'multiply',
],
],
];
if ($builder->callback) {
return call_user_func($builder->callback, $this->http(), $builder->query, $body);
}
return $this->http()->post('/'.$builder->model->searchableAs().'/_search', $body)->throw()->json();
}
public function mapIds($results)
{
return collect($results['hits']['hits'] ?? [])->pluck('_id')->values();
}
public function map(Builder $builder, $results, $model)
{
$ids = $this->mapIds($results)->all();
if ($ids === []) {
return $model->newCollection();
}
$positions = array_flip($ids);
return $model->getScoutModelsByIds($builder, $ids)
->filter(fn ($m) => isset($positions[(string) $m->getScoutKey()]))
->sortBy(fn ($m) => $positions[(string) $m->getScoutKey()])
->values();
}
public function lazyMap(Builder $builder, $results, $model)
{
return LazyCollection::make($this->map($builder, $results, $model)->all());
}
public function getTotalCount($results)
{
return $results['hits']['total']['value'] ?? 0;
}
public function flush($model)
{
$this->http()->post('/'.$model->searchableAs().'/_delete_by_query', ['query' => ['match_all' => (object) []]]);
}
public function createIndex($name, array $options = [])
{
return $this->http()->put('/'.$name, $options)->json();
}
public function deleteIndex($name)
{
return $this->http()->delete('/'.$name)->json();
}
}<?php
namespace App\Providers;
use App\Search\ElasticsearchEngine;
use Illuminate\Support\ServiceProvider;
use Laravel\Scout\EngineManager;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// SCOUT_DRIVER=elasticsearch selects this engine (config/scout.php 'driver').
resolve(EngineManager::class)->extend('elasticsearch', function () {
return new ElasticsearchEngine(
config('services.elasticsearch.host', 'http://127.0.0.1:9200'),
config('services.elasticsearch.api_key'),
);
});
}
}Meilisearch and Typesense settings in config/scout.php (run php artisan scout:sync-index-settings after changes):
<?php
use App\Models\Product;
// Excerpt of config/scout.php: the three engines this chapter compares.
return [
'driver' => env('SCOUT_DRIVER', 'meilisearch'),
'prefix' => env('SCOUT_PREFIX', ''),
'queue' => ['connection' => 'redis', 'queue' => 'scout'],
'meilisearch' => [
'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'),
'key' => env('MEILISEARCH_KEY'),
'index-settings' => [
Product::class => [
// Required before Scout where() clauses work on Meilisearch.
'filterableAttributes' => ['brand', 'category', 'in_stock'],
'sortableAttributes' => ['price', 'popularity'],
],
],
],
'typesense' => [
'client-settings' => [
'api_key' => env('TYPESENSE_API_KEY', 'xyz'),
'nodes' => [[
'host' => env('TYPESENSE_HOST', 'localhost'),
'port' => env('TYPESENSE_PORT', '8108'),
'path' => env('TYPESENSE_PATH', ''),
'protocol' => env('TYPESENSE_PROTOCOL', 'http'),
]],
],
'model-settings' => [
Product::class => [
'collection-schema' => [
'fields' => [
['name' => 'id', 'type' => 'string'],
['name' => 'title', 'type' => 'string'],
['name' => 'brand', 'type' => 'string', 'facet' => true, 'optional' => true],
['name' => 'category', 'type' => 'string', 'facet' => true],
['name' => 'price', 'type' => 'float'],
['name' => 'popularity', 'type' => 'int32'],
['name' => 'in_stock', 'type' => 'bool'],
],
'default_sorting_field' => 'popularity',
],
'search-parameters' => ['query_by' => 'title'],
],
],
],
];The typeahead endpoint with Cache::flexible (stale-while-revalidate) and the completion suggester:
<?php
namespace App\Http\Controllers;
use App\Search\PersianNormalizer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
// GET /api/suggest?q=كف — budget: under 100 ms end to end.
// The browser debounces (about 150 ms) and cancels stale requests; the server
// caches hot prefixes with stale-while-revalidate and asks the completion
// suggester, never the database.
class TypeaheadController extends Controller
{
public function __invoke(Request $request): JsonResponse
{
$prefix = PersianNormalizer::normalize((string) $request->query('q', ''));
if (mb_strlen($prefix) < 2 || mb_strlen($prefix) > 40) {
return response()->json(['suggestions' => []]);
}
// Short prefixes are few and hot: cache them for everyone.
$key = 'suggest:v1:'.sha1($prefix);
$suggestions = Cache::flexible($key, [60, 300], function () use ($prefix) {
$res = Http::baseUrl(config('services.elasticsearch.host'))
->timeout(0.08) // 80 ms: fail fast, an empty list is acceptable
->post('/products/_search', [
'_source' => false,
'suggest' => ['product' => [
'prefix' => $prefix,
'completion' => [
'field' => 'suggest',
'size' => 8,
'skip_duplicates' => true,
'fuzzy' => ['fuzziness' => mb_strlen($prefix) > 4 ? 1 : 0],
],
]],
]);
return collect($res->json('suggest.product.0.options', []))
->map(fn (array $o) => ['text' => $o['text'], 'weight' => $o['_score']])
->values()
->all();
});
return response()
->json(['suggestions' => $suggestions])
->header('Cache-Control', 'public, max-age=60');
}
}The outbox relay and the alias-swap reindex command:
<?php
namespace App\Console\Commands;
use App\Models\Product;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
// Outbox relay for the search index: the write transaction inserted a row in
// search_outbox; this worker claims a batch with FOR UPDATE SKIP LOCKED,
// loads the latest state and upserts or deletes through Scout (one _bulk).
// Idempotent: re-running a batch writes the same documents again.
class RelayProductOutbox extends Command
{
protected $signature = 'search:relay-outbox {--batch=500}';
protected $description = 'Push product changes from the outbox to the search index';
public function handle(): int
{
do {
$done = DB::transaction(function () {
$rows = DB::table('search_outbox')
->whereNull('processed_at')
->orderBy('id')
->limit((int) $this->option('batch'))
->lockForUpdate()
->skipLocked()
->get();
if ($rows->isEmpty()) {
return 0;
}
$ids = $rows->pluck('aggregate_id')->unique()->all();
$live = Product::query()->whereIn('id', $ids)->get();
$keep = $live->filter->shouldBeSearchable();
$keep->searchable();
// Deleted or unpublished rows: remove by id, no row needed.
$gone = array_map(
fn ($id) => (new Product)->forceFill(['id' => $id]),
array_values(array_diff($ids, $keep->modelKeys())),
);
(new Product)->newCollection($gone)->unsearchable();
DB::table('search_outbox')->whereIn('id', $rows->pluck('id'))->update(['processed_at' => now()]);
return $rows->count();
});
$this->info("relayed {$done}");
} while ($done > 0);
return self::SUCCESS;
}
}<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
// Zero-downtime reindex: create products_vN with the new mapping, copy with
// _reindex (or replay from the database), catch up from the outbox, then move
// the alias in ONE atomic _aliases call. Rollback = point the alias back.
class ReindexProducts extends Command
{
protected $signature = 'search:reindex {from} {to}';
protected $description = 'Copy one versioned products index into another and swap the alias';
public function handle(): int
{
$es = Http::baseUrl(config('services.elasticsearch.host'))->timeout(3600);
[$from, $to] = [$this->argument('from'), $this->argument('to')];
$es->put("/{$to}", json_decode(file_get_contents(base_path('search/products.mapping.json')), true))->throw();
$es->put("/{$to}/_settings", ['index' => ['refresh_interval' => '-1', 'number_of_replicas' => 0]])->throw();
$es->post('/_reindex?wait_for_completion=true', [
'source' => ['index' => $from, 'size' => 1000],
'dest' => ['index' => $to, 'op_type' => 'index'],
])->throw();
$es->put("/{$to}/_settings", ['index' => ['refresh_interval' => '1s', 'number_of_replicas' => 1]])->throw();
$es->post("/{$to}/_refresh")->throw();
$es->post('/_aliases', ['actions' => [
['remove' => ['index' => $from, 'alias' => 'products']],
['add' => ['index' => $to, 'alias' => 'products', 'is_write_index' => true]],
]])->throw();
$this->info("alias products -> {$to}");
return self::SUCCESS;
}
}<?php
use App\Http\Controllers\TypeaheadController;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::get('/suggest', TypeaheadController::class)->middleware('throttle:120,1');
Route::get('/search', function (Request $request) {
return Product::search((string) $request->query('q', ''))
->where('in_stock', true)
->whereIn('category', (array) $request->query('category', []) ?: ['shoes', 'home'])
->paginate(24);
})->middleware('throttle:60,1');The Laravel angle
Laravel 13 Scout "ships with a built-in database engine that uses MySQL / PostgreSQL full-text indexes and LIKE clauses", a collection engine for tests, and "drivers for Algolia, Meilisearch, Typesense, and Turbopuffer"; Elasticsearch and OpenSearch need a community package or a custom engine that extends Laravel\Scout\Engines\Engine (the docs list eight abstract methods: update, delete, search, paginate, mapIds, map, getTotalCount, flush; the engine above also implements lazyMap, createIndex and deleteIndex, which recent Scout versions declare too). Set 'queue' => true so model observers dispatch indexing jobs instead of calling the engine inside the request, and note the docs' warning that Algolia and Meilisearch index asynchronously anyway. searchIndexShouldBeUpdated avoids reindexing on unrelated column changes; scout:queue-import --chunk=500 backfills; withoutSyncingToSearch pauses syncing during mass updates. Scout's observer is not transactional: if the request crashes after commit, the job may never be queued, which is why the chapter adds the outbox relay (lockForUpdate()->skipLocked() is Laravel's FOR UPDATE SKIP LOCKED). Scout 13 also offers semantic() and hybrid(textWeight:, semanticWeight:) for engines with embeddings. For typeahead, Cache::flexible($key, [60, 300], ...) serves a stale value while refreshing after the response. None of the PHP was executed; every file passes php -l.
Solving the classic problems
Worked design: e-commerce product search with typeahead
Scope. 10 million products, 8 languages including Persian, 50 million searches a day, typeahead on every keystroke, facets (brand, category, size, price), freshness under 5 seconds for price and stock, personalised ranking for signed-in users.
Estimate (back of the envelope, labelled). 50 M searches/day = about 580/s average, peak x4 = 2,300/s; typeahead about 4 requests per search after debouncing = 9,000/s peak, mostly cache hits. Documents of 2 KB source = 20 GB, index with analysis and doc values about 2x to 3x = 40 to 60 GB primary data: 3 to 6 primaries at 10 to 20 GB, 1 replica, plus headroom for a reindex (two versions side by side). Writes: 2 M price/stock updates per day = 23/s average, bursts of 2,000/s during feed imports.
High-level design.
Write path
1 Catalog service (PostgreSQL) -> outbox / Debezium -> Kafka "product-changes"
2 Indexer consumers: enrich (brand, category path, popularity from analytics), normalise, embed (batch)
3 _bulk 5-15 MB into alias products (products_vN), refresh 1 s
Read path
4 API gateway -> search service: normalise, spell-correct, extract entities -> filters
5 Elasticsearch: BM25F (title^3, brand^2, description) + kNN on embedding -> rrf, aggs, post_filter
6 re-rank top 200: LTR model (+ user features from the feature store) -> 24 results
7 typeahead service: in-memory trie / completion suggester, Redis cache for 1-3 char prefixes, CDN for anonymous
8 events (impressions, clicks, purchases) -> Kafka -> warehouse -> nightly suggestions, LTR training, dashboardsDecisions.
| Decision | Choice | Alternative | Why |
|---|---|---|---|
| Engine | Elasticsearch or OpenSearch | Meilisearch / Typesense / Algolia | Facets, vectors, LTR, scale; managed option exists |
| Source of truth | PostgreSQL | Search as primary | Reindexable read model |
| Freshness | Outbox/CDC + 1 s refresh | Nightly full rebuild only | Price and stock change often |
| Persian | Custom analyzer, ZWNJ removed, letters folded | Built-in persian | Product titles read better as whole words |
| Ranking | BM25F + function score, then LTR top 200 | Single-stage formula | Measured gains, bounded cost |
| Hybrid | kNN + RRF | Vector only | SKUs and brands need lexical |
| Typeahead | Separate suggestions from query log | Prefix query on products | Latency, quality, privacy filter |
| Personalisation | Re-rank stage only, global fallback | Personalised retrieval | Cold start, cache, filter bubble |
| Multi-language | One index, title.fa, title.en subfields | Index per language | Shared facets; per-language analyzers |
| Evaluation | Judgments + NDCG@10 gate, interleaving, A/B | Gut feeling | Repeatable decisions |
Zero-downtime mapping change
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
Alias swap with _reindex | New index, _reindex, catch-up, _aliases | Atomic switch, instant rollback | Double disk during the copy |
| Replay from the database | Indexer rebuilds v8 from a snapshot plus the change log | Picks up enrichment changes | Slower; needs a replayable pipeline |
| Add a new field only | PUT _mapping with the new field, backfill with _update_by_query | No new index | Only for additive changes |
Scout scout:flush + scout:import | Delete and recreate | Simple | Downtime and empty results meanwhile |
Read-after-write for the editor
refresh=wait_for on the seller's own save, database reads for "my listings", and the realtime GET by id for the detail page; never refresh=true on bulk.
Typeahead under 100 ms
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Client debounce + cancel | 100 to 200 ms debounce, AbortController | Cuts requests by about 3x to 5x (estimate) | Slight perceived delay |
| Server prefix cache | Cache::flexible per normalised prefix | Head prefixes cost a cache read | Personalised results cannot share keys |
| Completion suggester | FST in memory, weights | Milliseconds per lookup | Rebuild cost; whole-index scope unless contexts |
| In-process trie | Go typeahead.Trie built from the log | Microseconds | Memory per replica; refresh job |
| CDN for anonymous | Cache-Control: public, max-age=60 | Offloads origin | Only for non-personalised suggestions |
Zero results
Spell correction then relaxation (drop the least informative term), synonyms from the zero-result report, transliteration for Persian/English brand names, and a semantic retriever as fallback; show "did you mean" instead of an empty page.
Proving a ranking change
-- From the search_events log: CTR and zero-result rate per variant, last 7 days.
SELECT variant,
count(*) AS searches,
avg((results = 0)::int) AS zero_result_rate,
avg((clicked_doc IS NOT NULL)::int) AS ctr,
avg(CASE WHEN click_rank IS NOT NULL THEN 1.0 / click_rank END) AS mrr_of_clicks
FROM search_events
WHERE occurred_at > now() - interval '7 days'
GROUP BY variant;The full schema (outbox, events, suggestion weights with decay and a k-anonymity floor, PostgreSQL FTS baseline):
-- PostgreSQL: the transactional outbox that feeds the search indexer,
-- the query log that feeds typeahead and LTR, and the FTS baseline.
-- 1. Outbox row written in the SAME transaction as the product change.
CREATE TABLE search_outbox (
id bigserial PRIMARY KEY,
aggregate text NOT NULL DEFAULT 'product',
aggregate_id bigint NOT NULL,
op text NOT NULL CHECK (op IN ('upsert', 'delete')),
created_at timestamptz NOT NULL DEFAULT now(),
processed_at timestamptz
);
CREATE INDEX search_outbox_pending ON search_outbox (id) WHERE processed_at IS NULL;
BEGIN;
UPDATE products SET price = 79.90, updated_at = now() WHERE id = 42;
INSERT INTO search_outbox (aggregate_id, op) VALUES (42, 'upsert');
COMMIT;
-- Relay: claim a batch without blocking other relays.
SELECT id, aggregate_id, op
FROM search_outbox
WHERE processed_at IS NULL
ORDER BY id
LIMIT 500
FOR UPDATE SKIP LOCKED;
-- 2. Query and click log: input for typeahead weights, CTR, zero-result rate and LTR judgments.
CREATE TABLE search_events (
id bigserial PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
session_id uuid NOT NULL,
user_id bigint,
query text NOT NULL,
results int NOT NULL,
clicked_doc bigint,
click_rank int
);
-- Zero-result rate and CTR per day.
SELECT date_trunc('day', occurred_at) AS day,
avg((results = 0)::int) AS zero_result_rate,
avg((clicked_doc IS NOT NULL)::int) AS ctr
FROM search_events
GROUP BY 1 ORDER BY 1;
-- Typeahead weights: popular queries of the last 30 days that led to a click,
-- with a 7-day half-life decay.
SELECT lower(query) AS suggestion,
sum(power(0.5, extract(epoch FROM now() - occurred_at) / (7 * 86400))) AS weight
FROM search_events
WHERE occurred_at > now() - interval '30 days' AND clicked_doc IS NOT NULL AND results > 0
GROUP BY 1
HAVING count(DISTINCT session_id) >= 5 -- k-anonymity floor: no private queries in suggestions
ORDER BY weight DESC
LIMIT 100000;
-- 3. Baseline: PostgreSQL full-text search (see /database/full-text-search).
ALTER TABLE products ADD COLUMN tsv tsvector
GENERATED ALWAYS AS (setweight(to_tsvector('simple', coalesce(title, '')), 'A') ||
setweight(to_tsvector('simple', coalesce(description, '')), 'B')) STORED;
CREATE INDEX products_tsv_gin ON products USING gin (tsv);
SELECT id, title, ts_rank_cd(tsv, q) AS rank
FROM products, websearch_to_tsquery('simple', 'running shoes') q
WHERE tsv @@ q
ORDER BY rank DESC
LIMIT 20;(The variant column is added by the A/B router; the schema file shows the base table.)
Choosing
Which engine
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| Up to about a million rows, already on PostgreSQL | PostgreSQL FTS (+ pgvector) | Generated tsvector, GIN | No new system; see Full-Text Search |
| Laravel app, small team, instant search UI | Meilisearch or Typesense via Scout | filterableAttributes, synonyms | Typo tolerance and prefix search by default |
| No ops capacity, budget for SaaS | Algolia | Query Suggestions, A/B | Hosted speed and analytics |
| Facets, aggregations, large catalogue, vectors | Elasticsearch or OpenSearch | Aliases, BM25F, RRF, LTR | Most complete feature set |
| Open licence and AWS managed | OpenSearch | Hybrid query, k-NN | Apache-2.0, AWS service |
| Ranking with heavy ML on content nodes | Vespa | Multi-phase rank profiles | Model evaluation where the data is |
| On-premise, schema-driven, existing Solr skills | Solr | LTR module, eDisMax | Mature and stable |
| Logs and time-series search | Elasticsearch/OpenSearch with ILM | Data streams, tiers | Rollover and retention |
Which ranking stage to add next
| Symptom | Add | Cost | Reason |
|---|---|---|---|
| Long text beats titles | Separate fields, BM25F, boosts | Low | Field structure carries meaning |
| Relevant but unpopular or stale first | Function score (log1p popularity, gauss recency) | Low | Business signals |
| Hand weights keep regressing | LTR re-rank top 200 | Medium: judgments, pipeline | Learned weights, measurable |
| Synonym and intent misses | Query understanding, synonym graph | Low to medium | Cheap recall gains |
| Meaning-level misses remain | kNN retriever + RRF | Medium: embeddings, memory | Semantic recall |
| Top 10 still noisy | Cross-encoder re-rank top 50 | High: GPU or latency | Best precision at the top |
| Signed-in users differ strongly | Personalised features in the re-ranker | Medium plus privacy work | Per-user intent |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel or Go monolith with PostgreSQL uses the database engine of Scout or a tsvector column with GIN, websearch_to_tsquery and ts_rank_cd; typeahead is a small table of popular queries cached in Redis. Freshness is transactional, there is no pipeline, and the limits are ranking quality, Persian analysis and facet speed. This is the right start for a catalogue of thousands to a few hundred thousand rows.
Modular monolith: boundaries without the network
A Search module owns the read model: it subscribes to in-process domain events (ProductPublished, PriceChanged), writes the outbox in the same transaction, and exposes search(query, filters, user) and suggest(prefix); other modules never call the engine directly. Scout with Meilisearch or Elasticsearch sits behind this module, so changing engines touches one boundary.
Microservices: every arrow is a decision
The catalog service publishes product-changes through an outbox or CDC to Kafka; an indexer service consumes, enriches from pricing and inventory topics (event-carried state transfer), and bulk-indexes; the search service owns query understanding, retrieval, re-ranking and the A/B router; the typeahead service serves suggestions built by a batch job from the event stream; a ranking service hosts the LTR or cross-encoder model. Contracts: the change event (id, version, changed fields), the search API (query, filters, user context, variant) and the impression/click events. Idempotency comes from upserts by id with external versions (Idempotent Consumers); failure isolation from timeouts and a fallback to non-personalised ranking when the ranking service is slow (Circuit Breaker).
Distributed data: replicas, caches, regions
Search is a replica of the catalogue with its own lag; inside the cluster, shard replicas add read capacity and failover, and preference keeps a session on the same copies. Caches stack: browser (debounced prefix results), CDN (anonymous suggestions), application Redis (head queries, prefixes), engine (filter and request caches). Multi-region: an independent cluster per region fed by the same change stream (Elasticsearch cross-cluster replication or a per-region indexer), with users routed to the nearest region; global IDF differences between regions are acceptable. The catalogue database is the only place where stock is authoritative: re-check at add-to-cart.
Scaling path: 1x, 10x, 100x
| Scale | Catalogue / traffic | Design | Next bottleneck |
|---|---|---|---|
| 1x | 100 k products, 10 searches/s | PostgreSQL FTS or Scout + Meilisearch, synchronous indexing | Ranking quality, Persian handling |
| 10x | 1 to 10 M products, 500 searches/s, typeahead | Elasticsearch/OpenSearch 3 to 6 nodes, outbox or CDC, aliases, completion suggester, Redis prefix cache, BM25F + function score | Relevance tuning by hand; indexing bursts |
| 100x | 100 M+ products, 10,000+ searches/s, many regions | Per-region clusters, separate typeahead service, hybrid retrieval with RRF, LTR and cross-encoder re-rank service, feature store, interleaving platform | Fan-out tail latency, model serving cost, reindex duration (hours) |
Lab: run the demo, then the engine drills
Run the Go code (run on the author's laptop)
cd docs/snippets/system-design/search-systems/go
go test ./...
go run ./cmd/demo
ES_URL= go run ./esclient # prints "ES_URL not set; skipping" Output observed on one laptop (Go 1.2x); timings vary by machine
1 analyze: [کتاب go 1403]
2 bm25 body : [{1 0.952} {3 0.871} {4 0.357}]
3 bm25f : [{1 1.686} {3 1.224} {2 0.608}]
4 typeahead : [{iphone 15 900} {ipad 700} {iphone case 500}] (9µs)
5 personal : [{iphone case 1000} {iphone 15 900} {ipad 700}]
6 rrf : [{d1 0.0325} {d3 0.0323} {d2 0.0161} {d4 0.0159}]
7 ndcg@3 : 0.790Line 1 shows Arabic-keyboard letters, the ZWNJ plural, a stop word and Persian digits folded into three clean terms; lines 2 and 3 show that BM25F with a title boost lifts doc 2 ("Shoe rack") above doc 4 whose body repeats "boots".
Drills against an engine (expected, not run)
These need a local Elasticsearch 8.14+ or 9.x on http://localhost:9200. Output is expected, not run.
1 PUT /fa_test with the mapping from esclient/main.go
GET /fa_test/_analyze {"analyzer":"fa_text","text":"كتابهاي علمي ۱۴۰۳"}
expected tokens: کتاب, های, علمی, 1403 (ZWNJ became a space in this analyzer)
2 PUT /fa_test/_doc/1 {"title":"کفش ورزشی"} then immediately GET /fa_test/_search?q=title:کفش
expected: 0 hits; repeat with ?refresh=wait_for on the PUT -> 1 hit
3 GET /fa_test/_search {"explain":true,"query":{"match":{"title":"کفش"}}}
expected: explanation lists idf, tf, "k1, term saturation parameter" 1.2 and "b, length normalization parameter" 0.75
4 PUT /fa_test/_mapping {"properties":{"title":{"type":"keyword"}}}
expected: 400 illegal_argument_exception (cannot change type) -> do the alias swap from esclient
5 POST /fa_test/_search {"suggest":{"s":{"prefix":"كف","completion":{"field":"suggest"}}}}
expected: "کفش ورزشی" (Arabic kaf folded by the analyzer)
6 GET /_cat/shards/fa_test?v and GET /_nodes/stats/indices/query_cache,request_cache
expected: 3 primaries + replicas (unassigned on a single node), cache hit/miss countersCommon misconceptions
| Belief | Reality |
|---|---|
LIKE '%q%' with an index is search | A leading wildcard cannot use a B-tree; there is no ranking or analysis |
| Elasticsearch can be the primary database | It is a near-real-time, rebuildable read model without multi-document transactions |
| A 201 from the index API means searchable | Searchable after the next refresh |
| More shards make search faster | Each shard adds per-query overhead; size shards 10 to 50 GB |
| BM25 scores mean the same across queries | They depend on query terms and shard statistics; compare ranks, not scores |
| Repeating a word keeps raising the score | BM25 term weight saturates below k1 + 1 times IDF |
title^3 with most_fields is BM25F | It saturates per field; BM25F combines before saturating (combined_fields) |
| CTR equals relevance | Clicks carry position and trust bias; debias before training |
| Vectors replaced keyword search | Dense retrieval misses exact tokens; hybrid with RRF is the norm |
| Average BM25 and cosine for hybrid | Scales differ; use RRF or per-query normalisation |
| Typeahead is search on each keystroke | It is a separate, precomputed suggestion structure with caching and debouncing |
| UTF-8 solves Persian search | ی/ي, ک/ك and ZWNJ need explicit normalisation on both sides |
| A mapping can be changed in place | Only additive changes; type or analyzer changes need a new index |
refresh=true on every write is safe | It creates tiny segments and slows the cluster; use wait_for on single interactive writes |
| Personalise everything | Personalise the re-rank stage with a global fallback; mind cache keys and privacy |
Cheat sheet
| Topic | What to remember |
|---|---|
| Inverted index | Term dictionary -> postings (doc, tf, positions); skip data; norms; doc values |
| Segments | Immutable; refresh opens new ones (1 s); merges purge deletes; flush commits |
| Analyzer | Char filters -> tokenizer -> filters; same at index and query time; test with _analyze |
| Persian | Fold ي->ی, ك->ک, digits; decide ZWNJ (remove or space); diacritics out; persian_stem |
| Edge n-grams | Index-time only, normal search_analyzer, set min/max gram |
| BM25 | IDF x tf(k1+1)/(tf + k1(1-b+b·dl/avgdl)); k1 1.2, b 0.75 |
| BM25F | Weight fields before saturation; combined_fields |
| Business signals | function_score: log1p popularity, gauss recency; filters for hard constraints |
| LTR | Judgments + features -> LambdaMART (XGBoost) -> rescore top 100-200; log features at serve time |
| Metrics | NDCG@10 graded, MRR navigational, MAP binary; recall@N for retrieval |
| Online | Interleaving to choose, A/B to measure; guard latency and zero-result rate |
| Typeahead | Query-log suggestions, top-K per prefix, debounce 100-200 ms, cache prefixes, under 100 ms |
| Hybrid | BM25 + kNN (HNSW), RRF k = 60, cross-encoder on top 50-200 |
| Pipeline | Outbox/CDC -> bulk -> alias; never dual-write; reindex = new index + alias swap |
| Shards | 10-50 GB, under 200 M docs; routing for tenants; watch hot shards |
| Caches and breakers | Filter cache 10%, request cache 1%, parent breaker 95%; search_after over deep from |
| Consistency | Eventually consistent; refresh=wait_for or DB for the writer |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why can an inverted index answer "running AND shoe" without reading any document? Must-know
Answer
Answer: The term dictionary gives each term's postings list of document ids (with tf and positions); the engine intersects the two sorted lists, using skip data to jump ahead in the longer one, and scores with df, tf and the stored field length (norms).
2 — A product indexed with a 201 response is not found by a search 300 ms later. Why, and what are the fixes? Must-know
Answer
Answer: It is buffered and in the translog but not yet in a searchable segment; the next refresh (1 s default) opens it. Use refresh=wait_for on that interactive write, read the entity from the database or by realtime GET, or accept the lag.
3 — Write the BM25 term weight and explain k1 and b. Important
Answer
Answer: IDF(q) * tf * (k1 + 1) / (tf + k1 * (1 - b + b * dl / avgdl)). k1 controls saturation (how fast extra occurrences stop helping; default 1.2); b controls length normalisation (0 none, 1 full; default 0.75).
4 — How does BM25F differ from summing per-field BM25 with boosts? Good to know
Answer
Answer: BM25F builds one weighted, length-normalised pseudo term frequency across fields and saturates once; summing saturates each field separately, so a term repeated in many fields is counted many times.
5 — What must a Persian analyzer do about ZWNJ and Arabic letters? Important
Answer
Answer: Map Arabic yeh and kaf (and other variants) to Persian yeh and keheh, fold digits, remove diacritics and tatweel, and treat ZWNJ consistently: either replace it with a space (the built-in persian analyzer) or remove it to keep the word whole, on both index and query sides.
6 — Why should edge n-grams not be used in the search analyzer? Important
Answer
Answer: The query would be split into all its prefixes, so a one- or two-letter prefix matches almost everything; edge n-grams belong at index time with a normal search analyzer.
7 — Why are raw clicks poor training labels, and what is one correction? Important
Answer
Answer: Users click higher-ranked results more regardless of relevance (position and trust bias), so the model learns the current ranking. Weight clicks by inverse examination propensity estimated by small randomisations, or use pairwise skip-above preferences.
8 — Compute NDCG@2 for grades [1, 3] with gain 2^rel - 1. Good to know
Answer
Answer: DCG = 1/1 + 7/log2(3) = 1 + 4.42 = 5.42; ideal [3, 1]: 7/1 + 1/1.585 = 7.63; NDCG = 0.71.
9 — Why use RRF instead of averaging BM25 and cosine scores? Important
Answer
Answer: The scores have unrelated, query-dependent scales; RRF uses only ranks, 1/(k + rank) summed over lists with k = 60, so no calibration is needed and agreement between retrievers is rewarded.
10 — How do you change a text field to keyword without downtime? Important
Answer
Answer: Create a new versioned index with the new mapping, backfill with _reindex or a database replay, catch up from the change log, then move the alias in one atomic _aliases call; keep the old index for rollback.
11 — What makes a typeahead endpoint meet a 100 ms budget? Must-know
Answer
Answer: Client debouncing and cancellation, a precomputed suggestion structure (completion suggester FST or in-memory trie with top-K per prefix), a server cache for hot short prefixes, a strict server timeout, and CDN caching for anonymous suggestions.
12 — When should a SaaS use one index per tenant? Good to know
Answer
Answer: When tenants are few or large and need their own mappings, analyzers or deletion; for thousands of small tenants use a shared index with a mandatory tenant filter enforced by filtered aliases, document-level security or scoped keys, plus routing.
Glossary
| Term | Meaning |
|---|---|
| Inverted index | Map from each term to the documents that contain it |
| Term dictionary | Sorted list of all terms with document frequency and pointers (.tim) |
| Term index | FST prefix index into the term dictionary (.tip) |
| Postings list | For one term, the documents, frequencies and positions |
| Skip list | Skip data interleaved with postings so intersection can jump ahead |
| Positions | Token offsets in a field, needed for phrase queries |
| Norms | Per-field length factor used in scoring |
| Doc values | Columnar per-document values for sorting and aggregations |
| Lucene | The Java search library under Elasticsearch, OpenSearch and Solr |
| Segment | An immutable sub-index; a Lucene index is segments plus a commit point |
| Merge | Combining segments and purging deleted documents |
| Refresh | Writing and opening a new segment so recent writes become searchable |
| Near-real-time | Visible to search within about a refresh interval |
| Flush | A Lucene commit that fsyncs segments and trims the translog |
| Translog | Write-ahead log that makes acknowledged writes durable between commits |
| Analyzer | Char filters, a tokenizer and token filters applied to text |
| Tokenizer | Splits text into tokens |
| Normalisation | Folding equivalent characters (case, accents, script variants) to one form |
| Stemming | Rule-based removal of suffixes to a stem |
| Lemmatisation | Dictionary-based reduction of a word to its lemma |
| Stop words | Very common words removed from indexing or queries |
| Synonyms | Equivalent terms expanded at index or query time (synonym_graph) |
| n-gram | Every substring of length n of a token |
| Edge n-gram | Prefixes of a token, for prefix matching |
| Persian analyzer | Elasticsearch analyzer with ZWNJ char filter, normalisation, stop words and stemmer |
| ZWNJ | Zero-width non-joiner U+200C |
| Half-space | Persian name for ZWNJ used inside words (میروم) |
| Relevance | How well a document satisfies the need behind a query |
| TF-IDF | Term frequency times inverse document frequency, BM25's predecessor |
| BM25 | Probabilistic scoring with IDF, saturated tf and length normalisation |
| k1 | BM25 saturation parameter (default 1.2) |
| b | BM25 length normalisation parameter (default 0.75) |
| IDF | Inverse document frequency: rarer terms weigh more |
| BM25F | BM25 over weighted fields combined before saturation |
| Field boosting | Multiplying a field's contribution (title^3) |
| Function score | Elasticsearch query that combines relevance with functions of fields |
| Decay | Gauss, linear or exponential reduction with distance from an origin |
| Learning to rank | A trained model that orders results from features |
| Judgment list | Queries with graded relevance labels for documents |
| Features | Numeric signals about the document, the query or the pair |
| LambdaMART | Gradient-boosted trees trained with LambdaRank gradients for ranking |
| XGBoost | Gradient boosting library providing LambdaMART (XGBRanker) |
| Rescorer | Re-scoring of the top window of results with a costlier function |
| Click model | Model of how users examine and click results |
| Position bias | Higher click rate at higher ranks independent of relevance |
| Trust bias | Users trust top results, clicking them even when less relevant |
| NDCG | Normalised discounted cumulative gain over graded relevance |
| MAP | Mean average precision over queries |
| MRR | Mean reciprocal rank of the first relevant result |
| A/B test | Randomised comparison of variants on separate user groups |
| Interleaving | Mixing two rankers' results in one list and crediting clicks |
| Query understanding | Correcting, expanding and interpreting a query before retrieval |
| Spell correction | Proposing a corrected query ("did you mean") |
| Query expansion | Adding synonyms or related terms to a query |
| Intent | The goal behind a query (navigational, product, category, question) |
| Entity recognition | Detecting brands, sizes, colours, prices in a query |
| Facets | Value counts shown for refining results |
| Aggregations | Engine computations over matching documents (terms, ranges, histograms) |
| Filters | Yes/no clauses that do not score and can be cached |
| Post filter | Filter applied after aggregations, for multi-select facets |
| Typeahead | Suggestions shown while the user types |
| Autocomplete | Completing the current input to a full query or item |
| Prefix trie | Tree of characters where each path is a prefix |
| Completion suggester | Elasticsearch in-memory FST suggester with weights |
| Debouncing | Waiting for a pause in typing before sending a request |
| Personalisation | Ranking adapted to a user's features |
| Re-ranking | Re-ordering the top results with a more expensive model |
| Cold start | No history for a new user or item |
| Semantic search | Retrieval by meaning using embeddings |
| Embedding | Dense vector representation of text |
| ANN | Approximate nearest neighbour search |
| HNSW | Hierarchical navigable small world graph index for ANN |
| IVF | Inverted file index: cluster vectors and search a few clusters |
| Hybrid search | Combining lexical and vector retrieval |
| RRF | Reciprocal rank fusion, sum of 1/(k + rank) |
| Reciprocal rank fusion | Same as RRF |
| Cross-encoder | Model scoring query and document jointly, used for re-ranking |
| Bi-encoder | Model embedding query and document separately |
| Indexing pipeline | The path from a source change to a searchable document |
| Outbox | Table written in the business transaction, relayed to the index |
| CDC | Change data capture from the database log |
| Bulk API | Batch NDJSON endpoint for index, update and delete actions |
| Alias | A name pointing to one or more indices, switched atomically |
| Zero-downtime reindex | New index, backfill, catch up, alias swap |
| Mapping | Schema of fields, types and analyzers in an index |
| ILM | Index lifecycle management with rollover and phases |
| Hot-warm-cold | Data tiers from fast to cheap storage |
| Rollover | Starting a new write index at a size, count or age |
| Shard | One partition of an index, a Lucene index itself |
| Replica | A copy of a shard for reads and failover |
| Routing | Choosing a shard from a routing value (default _id) |
| Hot shard | A shard receiving disproportionate load |
| Circuit breaker | Memory guard that rejects a request before out-of-memory |
| Query cache | Node-level cache of filter results per segment |
| Filter cache | Another name for the query cache of filter clauses |
| Request cache | Shard-level cache of whole responses for size-0 requests |
| Eventual consistency | The index converges to the source after a lag |
| Read-after-write | A writer sees its own change on the next read |
| Multi-tenancy | Serving many customers from one system with isolation |
| Zero-result rate | Share of searches returning no results |
| CTR | Click-through rate: share of searches or impressions with a click |
| Elasticsearch | Distributed Lucene-based search engine by Elastic |
| OpenSearch | Apache-2.0 fork of Elasticsearch 7.10 |
| Solr | Apache Lucene's search server |
| Meilisearch | Rust search engine with ranking rules and typo tolerance |
| Typesense | C++ in-memory search engine with Raft replication |
| Vespa | Search and ML ranking engine with multi-phase rank profiles |
| Algolia | Hosted search-as-a-service |
| Scout | Laravel's driver-based full-text search integration |
References
- Robertson and Zaragoza, The Probabilistic Relevance Framework: BM25 and Beyond (2009): https://www.staff.city.ac.uk/~sbrp622/papers/foundations_bm25_review.pdf
- Cormack, Clarke and Büttcher, Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (SIGIR 2009): https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf
- Järvelin and Kekäläinen, Cumulated Gain-Based Evaluation of IR Techniques (2002), copy: https://faculty.cc.gatech.edu/~zha/CS8803WST/dcg.pdf
- Joachims et al., Accurately Interpreting Clickthrough Data as Implicit Feedback (2005): https://www.cs.cornell.edu/people/tj/publications/joachims_etal_05a.pdf
- Chapelle, Joachims, Radlinski and Yue, Large-Scale Validation and Analysis of Interleaved Search Evaluation (2012): https://www.cs.cornell.edu/people/tj/publications/chapelle_etal_12a.pdf
- Malkov and Yashunin, Efficient and robust approximate nearest neighbor search using HNSW graphs: https://arxiv.org/abs/1603.09320
- Lucene 10.3 index file formats: https://lucene.apache.org/core/10_3_0/core/org/apache/lucene/codecs/lucene103/package-summary.html
- Lucene 10.3 postings format: https://lucene.apache.org/core/10_3_0/core/org/apache/lucene/codecs/lucene103/Lucene103PostingsFormat.html
- Lucene
BM25Similarity: https://lucene.apache.org/core/10_3_0/core/org/apache/lucene/search/similarities/BM25Similarity.html - Lucene
TieredMergePolicy: https://lucene.apache.org/core/10_3_0/core/org/apache/lucene/index/TieredMergePolicy.html - Elasticsearch, near real-time search: https://www.elastic.co/docs/manage-data/data-store/near-real-time-search
- Elasticsearch, refresh API: https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-refresh
- Elasticsearch, full-text search: https://www.elastic.co/docs/solutions/search/full-text
- Elasticsearch, text analysis: https://www.elastic.co/docs/manage-data/data-store/text-analysis
- Elasticsearch, language analyzers (persian): https://www.elastic.co/docs/reference/text-analysis/analysis-lang-analyzer
- Elasticsearch, normalization token filters: https://www.elastic.co/docs/reference/text-analysis/analysis-normalization-tokenfilter
- Elasticsearch, synonym graph token filter: https://www.elastic.co/docs/reference/text-analysis/analysis-synonym-graph-tokenfilter
- Elasticsearch, edge n-gram tokenizer: https://www.elastic.co/docs/reference/text-analysis/analysis-edgengram-tokenizer
- Elasticsearch, search_as_you_type: https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/search-as-you-type
- Elasticsearch, similarity settings: https://www.elastic.co/docs/reference/elasticsearch/index-settings/similarity
- Elasticsearch, function score query: https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-function-score-query
- Elasticsearch, learning to rank: https://www.elastic.co/docs/solutions/search/ranking/learning-to-rank-ltr
- Elasticsearch, suggesters: https://www.elastic.co/docs/reference/elasticsearch/rest-apis/search-suggesters
- Elasticsearch, kNN search: https://www.elastic.co/docs/solutions/search/vector/knn
- Elasticsearch, dense_vector: https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/dense-vector
- Elasticsearch, reciprocal rank fusion: https://www.elastic.co/docs/reference/elasticsearch/rest-apis/reciprocal-rank-fusion
- Elasticsearch, doc values: https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/doc-values
- Elasticsearch, aliases: https://www.elastic.co/docs/manage-data/data-store/aliases
- Elasticsearch, bulk API: https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-bulk
- Elasticsearch, reindex API: https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-reindex
- Elasticsearch, index lifecycle management: https://www.elastic.co/docs/manage-data/lifecycle/index-lifecycle-management
- Elasticsearch, data tiers: https://www.elastic.co/docs/manage-data/lifecycle/data-tiers
- Elasticsearch, size your shards: https://www.elastic.co/docs/deploy-manage/production-guidance/optimize-performance/size-shards
- Elasticsearch,
_routingfield: https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/mapping-routing-field - Elasticsearch, node query cache settings: https://www.elastic.co/docs/reference/elasticsearch/configuration-reference/node-query-cache-settings
- Elasticsearch, shard request cache settings: https://www.elastic.co/docs/reference/elasticsearch/configuration-reference/shard-request-cache-settings
- Elasticsearch, circuit breaker settings: https://www.elastic.co/docs/reference/elasticsearch/configuration-reference/circuit-breaker-settings
- OpenSearch, hybrid search: https://docs.opensearch.org/latest/vector-search/ai-search/hybrid-search/index/
- OpenSearch, AI search (semantic and neural): https://docs.opensearch.org/latest/vector-search/ai-search/index/
- Solr, schema elements and similarity: https://solr.apache.org/guide/solr/latest/indexing-guide/schema-elements.html
- Meilisearch, ranking rules: https://www.meilisearch.com/docs/learn/relevancy/ranking_rules
- Typesense, ranking and relevance: https://typesense.org/docs/guide/ranking-and-relevance.html
- Vespa, ranking: https://docs.vespa.ai/en/ranking.html
- Algolia, what is autocomplete: https://www.algolia.com/doc/ui-libraries/autocomplete/introduction/what-is-autocomplete/
- Algolia, query suggestions: https://www.algolia.com/doc/guides/building-search-ui/ui-and-ux-patterns/query-suggestions/js/
- Laravel 13, Scout: https://laravel.com/docs/13.x/scout
- Laravel 13, cache (
Cache::flexible): https://laravel.com/docs/13.x/cache - elastic/go-elasticsearch: https://github.com/elastic/go-elasticsearch
- opensearch-project/opensearch-go: https://github.com/opensearch-project/opensearch-go
- Note: Burges, From RankNet to LambdaRank to LambdaMART: An Overview (Microsoft Research Technical Report MSR-TR-2010-82) could not be fetched from microsoft.com during writing (connection reset); the LambdaMART description relies on the Elasticsearch LTR page above.