Skip to content

Search and suggestions: build the read model

11 min reading

A design for document ingestion, index updates and suggestions

Page details

System Design · Compose complete systems

11 min reading · 26 min with practice

Sources

Published · Last edited:

Prerequisite: Media under burst traffic and failed processing. For basics, use the independent System Design foundations.

More
20px

Hypothetical scenario. A Northwind buyer enters a precise part number. Dev sends it through the same fuzzy matcher used for ordinary names. Maya also points to a restricted supplier note that resembles a public query. Priya asks which result the input was actually requesting and which candidates may be disclosed.

Dev: “The engine returned something similar very quickly.”

Maya: “Is similarity the right meaning for this input, and is that result eligible?”

Separate exact identity, tolerant discovery, candidate generation, ranking and presentation. Keep source versions and permissions visible so an obsolete or restricted match cannot become acceptable merely by ranking well. This case’s typing and index cohorts are independent from the earlier catalogue-search extension.

This case separates indexing, candidate generation, ranking, eligibility and presentation. Scope includes text search, exact identifiers, bounded prefix suggestions, index updates and evaluation. A public web crawler and model training are excluded. The design begins with the user's query contract rather than choosing a search product and adopting all its defaults.

Search is a derived view. Its latency and relevance are not enough if source versions and permissions are wrong. Decide what delay is acceptable for new items, updates, withdrawal and access changes; these transitions can require different treatment.

Which result would answer the input correctly?

A prefix search for a typed fragment, an exact identifier lookup and a multiword topical query have different semantics. Applying fuzzy matching everywhere can turn a precise identifier into an unrelated near-match. Applying exact matching everywhere can make ordinary wording unhelpful.

Normalization also changes meaning. Case folding, punctuation handling, tokenization and language rules may be useful for names but harmful for identifiers where characters distinguish products. Preserve fields with their intended search behavior rather than putting everything into one analyzed string.

PostgreSQL’s pg_trgm documentation describes trigram similarity and index support for matching text. Such a matching mechanism supplies candidates; the product still decides whether an approximate spelling match is acceptable for a given query.

Build a versioned search view

Ingestion preserves source identity, current version and visibility metadata. A transformation produces typed fields and searchable tokens under a named analyzer version. Updates and withdrawals carry ordered version evidence so retries do not restore obsolete state.

Query intent selects candidates before ranking and visibilityA versioned source index supports exact, prefix and topical candidate paths. A ranking and eligibility stage returns a bounded page with stable source identities.Versioned fieldssource + accessExact identifierPrefix suggestionTopical candidatesRank + eligibilitybounded results

Keep an exact path for structured identifiers. A prefix index or suitable ordered dictionary can support suggestions; an inverted index can retrieve documents containing query terms. A ranking function orders the selected candidates under an explicit query interpretation.

Perform the required eligibility checks before returning titles, snippets or suggestions. A restricted name leaked through autocomplete is still a disclosure even if clicking it later produces an access error. Cache keys must preserve scope and relevant index versions.

Separate exact lookup, text search and suggestion paths

Hypothetical scenario. Q7 is an exact product identifier, while brass valve is a discovery query and bra is a suggestion prefix. Give each path a declared matching contract. An exact identifier must not silently resolve to a merely similar product; approximate text matching is useful only where the user task permits it.

Separate exact lookup, text search and suggestion paths — selected design evidence
Serving pathInputIndex / contract
Exact lookupQ7Authoritative identifier resolution
Discoverybrass valveAnalyzed terms / ranked candidates
SuggestionbraPrefix candidates with eligibility
The selected matching path determines candidate generation; eligibility and evidence still govern display.The selected matching path determines candidate generation; eligibility and evidence still govern display. Query classifier to Exact / text indexes: select declared matching path; Exact / text indexes to Eligibility + merge: candidate identity + revision.Query classifierExact / textindexesEligibility +mergeselect declared matching pathcandidate identity + revision
The selected matching path determines candidate generation; eligibility and evidence still govern display. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

An analyzer maps source text to terms; postings map terms to document identities. A prefix suggestion structure maps a normalized prefix to candidate completions and source references. Trigram matching, inverted terms and prefix lookup are different mechanisms, each with its own index and relevance behavior. Record analyzer identity so a result can be traced to the transformation that produced it.

Shard fan-out adds work and tail waiting. A coordinator merges candidate sets, then applies the selected eligibility and evidence rule. Evaluate exact-ID correctness separately from discovery relevance and suggestion usefulness. One global latency average cannot establish all three contracts, and suggestion requests may greatly outnumber submitted searches.

Derive index and suggestion work

Hypothetical scenario. Choose 100,000 source records with an average of 20 indexed term occurrences. The logical occurrence count is 100,000 × 20 = 2,000,000. At a chosen eight bytes per occurrence record, raw payload is 16,000,000 bytes, or 16 MB. Dictionaries, positions, skip structures, stored fields, allocation and replication are excluded.

Suppose 1,000 people each type a five-character query, issuing one suggestion request after every character. That creates 1,000 × 5 = 5,000 requests. If a deliberate client policy emits only two requests for each completed typing sequence in this example, demand becomes 1,000 × 2 = 2,000. This is a constructed event schedule, not a universal reduction from a particular debounce duration.

For candidate evaluation, choose 40 candidates and a maximum returned page of ten. If eligibility removes 12,28 remain, so a full ten-item page is possible. If eligibility instead removes 35, only five remain. Filling the page requires another bounded candidate fetch or an explicit shorter result; the original candidate budget cannot guarantee ten.

A relevance case has four labeled relevant records. The returned top five include three of them. Precision is 3 ÷ 5 = 0.6 and recall is 3 ÷ 4 = 0.75 at that cutoff. These measures depend on the labels and query, not only the index algorithm.

Walk a prefix through ranked candidates

Hypothetical scenario. Normalize a suggestion prefix to bra. In a toy character trie, traverse the root through b, r and a; the reached node references candidate identities. Choose an explicit ranking rule: descending accepted-query count over the same completed reporting window, with normalized text as the tie-breaker. Counts here are selected teaching inputs, not reader or site usage.

Candidate evidence at one prefix node
CompletionSelected countCurrent eligibility
brass valve40Allowed
bracket30Withdrawn
brass fitting20Allowed

For a requested top two, the raw ranked candidates are brass valve and bracket. Filtering those two afterward returns only one result despite an eligible third candidate. Keep a bounded continuation or overfetch policy: examining all three in this example removes bracket and returns brass valve followed by brass fitting. A node storing only its raw top two cannot recover the omitted candidate without another lookup.

Now a versioned update changes brass fitting’s selected count from 20 to 45. The ranking becomes 45 > 40, so that completion moves first. A materialized prefix cache must carry the ranking generation and invalidate or rebuild every prefix entry affected by that completion. Old update deliveries must not overwrite the newer generation. Current withdrawals still govern display during cache lag. This small trie explains prefix lookup; it is a separate mechanism from the chapter’s PostgreSQL trigram similarity example, and large vocabularies need an explicit memory and update-work budget.

Evaluate the query the user intended

Known-item queries check whether the required record can be found without substituting another identity. Discovery queries assess ranked usefulness. Typo recovery asks whether the interface makes uncertainty clear. A single blended score cannot establish that all three paths preserve their contracts.

Retain labeled examples and query slices before changing the analyzer or ranking policy. Empty-result behavior also matters: a missing record can reflect ingestion lag, normalization, permission or the candidate budget. Diagnose those boundaries before concluding that a different relevance function is needed.

In the wild: a matching mechanism supplies candidates

PostgreSQL’s pg_trgm documentation specifies similarity operators and index support. It is a concrete mechanism for tolerant text matching. It does not decide whether Northwind may substitute a similar part number or reveal a restricted suggestion.

Approximate discovery becomes a confirmed identity

Hypothetical failure scenario. A buyer enters an exact part number that does not exist. Fuzzy matching finds a nearby identifier and the interface displays it as the confirmed requested item. Search latency is low and the candidate looks plausible, but the operation has silently changed meaning.

Preserve an exact identifier path and label alternatives as suggestions. Normalize fields according to their semantics rather than applying one analyzer to every string. Case, punctuation and token boundaries can carry product identity. A discovery convenience must not become an undocumented identity conversion.

Start with a bounded inspectable pipeline

Use typed fields, a versioned source projection and a query path chosen from explicit intent. An inverted index, ordered prefix structure or trigram mechanism can support different candidates. Select the actual technology after identifying operators and update needs, then evaluate it against the required slices.

Suggestions have their own request multiplier and access boundary. A client may emit many prefixes for one completed query. Bound short-prefix work and apply the same disclosure discipline to titles and snippets that the result page uses. The next page tests that boundary during analyzer changes and delayed withdrawal.

Challenge the proposed mechanism

Analyzer identity belongs to the index evidence used for both rebuild and result diagnosis.Analyzer identity belongs to the index evidence used for both rebuild and result diagnosis. Source record to Analyzer a2: 1 · revision-bound text; Analyzer a2 to Postings / prefixes: 2 · terms and candidate identities.Source recordAnalyzer a2Postings / prefixes1 · revision-bound text2 · terms and candidate identities
Analyzer identity belongs to the index evidence used for both rebuild and result diagnosis. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

An approximate match is relevant but not the requested exact identifier. Which metric should reveal the error?

Reveal the design reasoning

Exact-resolution correctness in its own cohort. Do not let a discovery relevance score hide an identifier failure. Preserve source and analyzer revision in diagnostic evidence and test eligible result coverage separately.

Decision and reconsideration: Keep matching contracts and evaluation cohorts distinct. Change an analyzer through a versioned index migration.

Defend query meaning

  1. A missing identifier has a close spelling match. May it be returned as the requested part?

    Keep identity exact

    Only an explicit product contract could authorize that substitution. The baseline preserves exact lookup and presents near-matches as alternatives.

  2. Three of four relevant records appear in the top five. What are precision and recall?

    Use the declared denominator

    Precision is three divided by five, or 0.6; recall is three divided by four, or 0.75. Both depend on the query’s labels and cutoff, and neither establishes permission.

  3. Eligibility removes thirty-five of forty candidates. Is a ten-item page guaranteed?

    Bound the next candidate fetch

    No. Five remain. Obtain more only under the declared work budget or return an explicit short result; do not relax eligibility to fill the page.

The baseline gives each query a meaning. Page 52 changes analysis and rebuilds the index, asking which evidence proves that the new view preserves source versions, permissions and exact identity.

Northwind decision log

Separate exact identity from tolerant candidate discovery.
Evaluate query families and authorize every disclosed representation.
Next, preserve these contracts through source and analyzer changes.

Go deeper: retrieval and feedback