Chapter 22 — Search Infrastructure: Inverted Indexes, Elasticsearch/OpenSearch, Relevance
Part IV · Data & Storage | Prerequisites: Ch 18–Ch 20 | Builds: full-text search over Pulsely clinical notes & patient records, kept in sync
For eighteen chapters you've been sharpening one instinct: the database is the authority, and you make it fast by understanding how it stores bytes and which structure answers which question. Earlier we ended on a teaser — the inverted index, the same "sorted structure pointing at records" idea, but keyed by a word instead of a column value. This chapter cashes that teaser, and in doing so it breaks a comforting assumption: that one well-indexed Postgres can answer every read your product needs. It can't.
The moment a clinician types metformin into a search box and expects Metformin HCl 500 mg tablet to come back — ranked above a discharge summary that merely mentions the drug in passing — you have left the world your B-trees live in. You have entered a different one: it has its own data structure, its own scoring math, and — the part that bites teams — its own consistency model, because the search index is no longer your source of truth.
By the end you'll be able to derive the inverted index from the problem, hand-score a query two different ways and watch the ranking change, stand up OpenSearch with mappings you actually understand, and — most importantly — keep that index honest about a Postgres that never stops changing underneath it. That last problem, keeping search in sync, is where most of the real engineering is, and it's where this chapter spends its hardest currency. In healthcare it is also where the stakes are highest: a stale or leaky clinical search isn't a bad demo, it's a clinician acting on the wrong chart.
1. The problem: when your database can't find words
Let me start where it usually starts: with a query that worked.
Pulsely's clinical search box launched with the simplest thing that could possibly work — a single SQL query behind GET /notes/search?q=...:
SELECT id, subject, encounter_id FROM clinical_notes
WHERE subject ILIKE '%' || $1 || '%'
ORDER BY authored_at DESC
LIMIT 20;
At ten thousand notes this is instant. Demos beautifully. Ships. Then the chart grows. At two million clinical notes across the tenant, the search page's p99 climbs to four seconds, a CPU core pins to 100% on every keystroke (because the front end fires a query per character), and when you open EXPLAIN to find the index you forgot to add, you discover the cruelest part: there's nothing to add. The planner is doing a sequential scan, reading every single row off disk and running a substring match on each subject line, and no index you create will change that.
Here's why, and it's worth understanding precisely rather than as folklore. A B-tree on subject stores subjects sorted by prefix — "Asthma" before "Bronchitis" before "Diabetes". That ordering is the entire source of its power: to find a subject you seek down the tree by leading characters, eliminating most of the table at each level. A query like subject ILIKE 'Diabetes%' (trailing wildcard) can use it — you have a prefix to seek on. But subject ILIKE '%diabetes%' (leading wildcard) gives the index no prefix to seek on. The matching subjects could be anywhere in sort order — "Type 2 diabetes follow-up", "Poorly controlled DIABETES", "h/o diabetes, now on insulin" — scattered across the whole tree. With no way to navigate, the engine falls back to reading everything. The index is sorted by exactly the wrong thing.
🧭 Mental model. A B-tree answers "which rows have a value that starts with / equals / falls in the range of X?" It is a structure organized around the whole value, left to right. Full-text search asks a different question — "which documents contain the word X, anywhere inside them?" — and a structure sorted by whole-value prefix simply cannot answer it efficiently. Wrong question for the index you have.
But the substring problem is the shallow half. Even if LIKE '%metformin%' were free, it would still be the wrong tool, because clinicians don't search for substrings — they search for concepts. Consider what a provider actually means when they type metformin:
- They expect
"Metformin HCl 500 mg tablet"and"Glucophage (metformin) ER"to match. (Brand and formulation variants of the same ingredient — the kind of thing RxNorm normalizes, but your raw text doesn't.) - They expect a med-list entry
"Metformin 500 mg BID"to rank above a 2,000-word discharge summary that happens to say "we discussed but deferred starting metformin." (A hit in a short field means more than a hit buried in a long body.) - They'd type
metforninon a rushed keyboard and still expect results. (Typos.) - They type
metformin renal doseand expect notes containing those words in any order, with some possibly missing — not the literal phrase.ILIKEforces you to hand-writeANDs of wildcards, which is both slow and brittle, and gives you no way to say "matched 2 of 3 words, rank it lower."
A substring engine has no notion of word boundaries, word forms, typo distance, or relevance. It returns a boolean: matched or not. But the clinical question is never boolean. It's "which documents are most relevant to this provider's fuzzy intent — ranked, and fast?" That is a fundamentally different question from the one a relational database is built to answer ("which rows exactly equal or range-match these predicates?"), and a different question demands a different data structure. That structure is the inverted index, and the system built around it is a search engine.
🚫 A framing this book rejects. "Search is just a
WHEREclause withLIKE." It's the most expensive sentence in this chapter, because it's true enough to ship and false enough to page you. Search and filtering are different operations: filtering is an exact, cacheable yes/no over structured fields (patient_id = X,note_type = 'discharge'); search is a ranked match over unstructured clinical text against the statistics of your whole corpus. Conflating them is how you end up sequential-scanning a clinician's search box at 2 a.m.
2. The mental model: invert the table, then run a pipeline
Two ideas carry this whole chapter. Hold both.
Idea one: invert the index. A normal database index maps row → its values — given a row, here are its column values, and the structure is sorted so you can find rows by value. A search index does the opposite: it maps term → the list of documents that contain it. That per-term list is called a postings list. Searching is then almost mechanical: take the query, break it into terms, look up each term's postings list, combine the lists (intersect for AND, union for OR), score the surviving documents, sort by score, and return the top results.
A NORMAL INDEX (sorted by value) AN INVERTED INDEX (keyed by term)
───────────────────────────────── ─────────────────────────────────────
value → row term → postings list
"Metformin dose increase" → doc 7 "metformin" → [3, 7, 12, 51, ...]
"Diabetes follow-up" → doc 3 "diabetes" → [3, 9, 88, ...]
"Renal function panel" → doc 9 "renal" → [7, 9, 41, ...]
"dose" → [3, 7, 88, ...]
query "metformin dose":
postings("metformin") = [3, 7, 12, 51]
postings("dose") = [3, 7, 88]
union/intersect → candidates {3, 7, 12, 51, 88}
score each → sort → return top N
🧭 Mental model. A normal index is a card catalog by title. An inverted index is the back-of-the-book index: pick a word, get the list of pages it appears on. Once you've internalized "search = look up each word's page-list, combine, rank," the rest of this chapter is filling in how each box works — how text becomes terms, and how candidates become a ranked order.
Idea two: a search engine is a pipeline, not a store. This is the reframe that prevents most beginner bugs. Text does not go into the index as-is. It flows through analysis — split into tokens, lowercase them, fold accents, reduce word forms — and the output terms are what's indexed. Crucially, the query runs through the same analysis. You search for terms, not for the raw string you typed.
INDEX TIME: "Metformin 500 mg tab" ──analysis──▶ [metformin, 500, mg, tab] ──▶ inverted index
QUERY TIME: "metformin" ──analysis──▶ [metformin] ──▶ postings lookup ──▶ score ──▶ rank
(same analyzer — this symmetry is load-bearing)
This is why "Metformin" in a med list matches a search for metformin: both sides were lowercased to the same term metformin before they ever met. And it's the source of the single most common "why does it return nothing?" bug — analyze the two sides differently and they never meet, even though to a human they're obviously the same word. We'll hit that pitfall hard in §6.
Three concerns live inside that pipeline, and a senior engineer keeps them mentally separate because they fail and tune independently:
- What gets matched — analysis (tokenization, normalization, stemming). Controls recall.
- How matches rank — scoring (TF-IDF, BM25, boosts). Controls ordering.
- How documents are distributed — shards and replicas. Controls scale and availability.
🔑 The derived-view invariant. A search index is not a system of record. It is a derived, disposable projection of your source of truth (Postgres, which owns the chart). You must be able to drop the entire index and rebuild it from Postgres at any time — treat it exactly like a cache you're allowed to lose, the single-source-of-truth invariant applied to search. Every design decision in §5 flows from refusing to let the index become a second authority for any clinical fact. In an EHR that refusal is not just tidiness: the chart is a legal record, and the search index must never be the only place a fact lives.
3. Theory & invariants
The inverted index, precisely
A postings entry is richer than "doc 7 contains this word." Formally, the index is a dictionary of terms, each mapping to a postings list of entries (docId, termFrequency, [positions...]):
"metformin" → [ (3, tf=2, pos=[1, 14]), (7, tf=1, pos=[2]), (12, tf=1, pos=[37]), ... ]
- Term frequency (tf) — how many times the term appears in that document. Feeds scoring (more occurrences → stronger signal, with limits).
- Positions — where in the document the term sits. This is what makes phrase queries (
"chest pain"as an exact phrase) and proximity queries ("these words near each other") possible: to match a phrase, the engine checks that the terms appear at adjacent positions in the same doc. Positions cost storage; you pay for them whether or not you use them, which is why some fields disable them.
🔑 The query/index symmetry invariant. A term in a query matches a term in a document only if both were produced by the same analysis. Index
"Metformin"as lowercasedmetforminbut search case-sensitively forMetformin, and you match nothing — silently, with a 200 OK and an empty list, the worst kind of bug because nothing errors. Whenever clinical search returns nothing it "obviously" should — the note is right there in the chart — your first hypothesis is analyzer mismatch, not a missing document.
Analysis: how text becomes terms
Tokenization splits a character stream into tokens. Sounds trivial; isn't. Whitespace-and-punctuation splitting handles English prose, but clinical text is a minefield: it mangles HbA1c (case and digits), COVID-19 (→ covid, 19), hyphenated 25-OH-vitamin-D, dosing like 500mg or b.i.d., and languages without spaces (Chinese/Japanese/Korean need dictionary- or n-gram-based segmentation). Lab codes, ICD-10 codes (E11.9), and drug strings each need a deliberate decision. Tokenization is the first place "obviously correct" fails on real chart data.
Normalization flattens variants so they collide on the same term:
- Lowercasing —
Metforminandmetforminbecome one term. - Accent/ASCII folding —
café→cafe, so a diacritic in a patient name still matches when the clerk didn't type it. - Stemming — chop word forms to a common root:
diabetic,diabetes→diabet;ulcers,ulceration→ulcer. Fast, rule-based, occasionally crude (universeanduniversitymay both stem tounivers). - Lemmatization — the smarter, dictionary-aware cousin that maps to real base forms (
better→good). More precise, more expensive; usually overkill for clinical free-text search. - Stop words — ultra-common words (
the,and,of). The old advice was to strip them to save space. The modern advice is usually keep them, because dropping them breaks real clinical queries —"vitamin A","hepatitis B","type A aortic dissection"all hinge on a single letter — and the scoring math (next) already deprioritizes common words far more gracefully than deleting them does.
Each of these is a recall/precision knob. Stemming raises recall (more forms match) but lowers precision (occasional wrong collisions). This tradeoff — recall (did we find everything relevant?) vs precision (is everything we found relevant?) — governs every analysis and scoring choice in the chapter. There is no setting that maximizes both; you choose where to sit per field and per product. (In healthcare, be conservative on fields where a wrong collision has clinical weight — more on that when we get to typo tolerance.)
Relevance scoring, from first principles
Matching gives you a set of candidate documents. Scoring gives you an order. Derive the order from three intuitions — don't memorize a formula.
-
Term frequency (TF): more is more relevant — but with diminishing returns. A note that says "metformin" five times is more about metformin than one that says it once. But the fifth mention adds far less than the second; relevance should saturate, not grow linearly, or a repetitive templated note wins over the concise one that actually matters.
-
Inverse document frequency (IDF): rare terms discriminate more than common ones. In a query
the diabetic patient, matchingtheandpatienttells you almost nothing (nearly every note has them); matchingdiabeticnarrows the field hard. So a term's weight should rise as it gets rarer across the whole corpus. IDF is computed from corpus statistics —idf ≈ log(totalDocs / docsContainingTerm)— which is exactly why scoring is a function of the corpus, not of a document in isolation. (It's also why keeping stop words is fine: IDF already crushesthe's contribution toward zero.) -
Field-length normalization: a hit in a short field beats a hit in a long one. The word "metformin" appearing in a 5-word medication line is a far stronger signal than the same word buried in a 5,000-word discharge summary. Score should be normalized by field length so short, dense matches rank above long, diluted ones.
TF-IDF is the naive combination: score = tf × idf, summed over query terms. It captures intuitions 1 and 2 but handles saturation and length crudely. BM25 (Best Match 25) is its saturating, length-normalized successor and the modern default in Lucene/Elasticsearch/OpenSearch. It adds two tunable parameters:
- k1 controls term-frequency saturation — how fast the benefit of repeated occurrences flattens (typical ~1.2). Low k1 = the second occurrence already barely helps.
- b controls how strongly length normalization applies (0 = ignore length, 1 = full; typical ~0.75).
You will feel the difference in §9's hand-scoring drill: on a long, term-repeating discharge summary, TF-IDF can rank it absurdly high while BM25's saturation + length penalty correctly pushes a clean med-list match to the top. That's why BM25 is the default and TF-IDF is a teaching tool.
📎 Borrowed on credit: corpus statistics in a distributed index. IDF needs
docsContainingTermacross the whole corpus — but in §4 we'll split the corpus across shards, each scoring with only its local statistics. That approximation is usually fine and occasionally skews ranking on small or skewed indices. There's a slower search mode (nameddfs_query_then_fetch) that gathers global term statistics first to correct it — file the name, skip the mechanics for now. The full reckoning with distributed statistics and consistency lives in Chapter 23. For now: scoring is locally exact, globally approximate.
Boolean retrieval beneath scoring
Underneath ranking sits a boolean layer with four operators you'll use constantly:
- must — the term must appear; contributes to score.
- should — the term may appear; if it does, it boosts score. (Pure-OR matching lives here.)
- must_not — the term must not appear; excludes.
- filter — must match, but contributes nothing to score and is cacheable. This is the home of structured constraints:
note_type = 'progress',encounter_date BETWEEN ...,status = 'signed', and — critically in an EHR —clinic_id = <caller's tenant>.
🔑 The filter-vs-query invariant. Filters answer yes/no and are cached; queries answer how-relevant and are scored. Put
encounter_date >= '2026-01-01'in a scoringmatchclause and you pay scoring cost and forfeit caching for a constraint that has nothing to do with relevance. Structured constraints go infilter; clinical text relevance goes inmust/should. Getting this split right is most of what separates a fast search from a slow one — and, as §8 shows,filteris exactly where your access-scope guard lives.
The consistency invariant — say it now, before it bites
🔑 The eventual-consistency invariant. A dedicated search index is, by construction, behind the source of truth. A note is signed in Postgres and only later becomes searchable. There is no free strong consistency between two separate datastores; what you get to choose is the staleness window, and your job is to make it small, bounded, and honest to the clinician — never to pretend it's zero. Every "I signed the note and search still shows the old version" ticket is this invariant, met by someone who assumed it away.
4. Under the hood: Lucene, segments, and the OpenSearch object model
Elasticsearch and OpenSearch are both distributed wrappers around the same engine — Apache Lucene — so understanding Lucene explains the behavior of both. (On the fork between them, see §7; at the engine level they're the same animal.)
Postings storage and immutable segments
Lucene stores the term dictionary compactly — often as an FST (finite-state transducer). In plain terms, an FST is a compact way to store a huge sorted word-list so that words sharing a start reuse the same stored prefix instead of repeating it — metformin, metformin ER, and metronidazole all share met, so met is stored once. Think of how a trie, or the autocomplete dropdown in your UI, collapses shared prefixes into one branch. That prefix-sharing is what lets millions of terms fit in memory and makes prefix lookups (autocomplete, wildcards) cheap. Postings lists are then delta-encoded and compressed: instead of [3, 7, 12, 51] it stores [3, +4, +5, +39], which packs into far fewer bytes. The result is a structure optimized for "scan these sorted doc-id lists and merge them fast."
The pivotal design choice: segments are immutable. A Lucene index is a set of self-contained mini-indices called segments, and a segment is never modified after it's written. This echoes the LSM-tree's append-and-merge bias you met in the storage chapter, and the mechanics rhyme:
write ──▶ in-memory buffer + translog (durability)
│ (refresh, ~1s)
▼
new immutable SEGMENT ◀── searchable now
│
│ background MERGE (combines small segments,
▼ drops tombstoned docs, reclaims space)
fewer, larger segments
- A write lands in an in-memory buffer plus a durable translog (so an un-flushed write survives a crash).
- A refresh turns the buffer into a new immutable segment — and only now is the doc searchable.
- Background merges combine many small segments into fewer large ones (fewer sorted lists to scan = faster search) and physically purge deleted docs.
Because segments are immutable, there is no in-place update. Deleting a doc just writes a tombstone marking it deleted; the bytes vanish only at the next merge. Updating a doc is delete-then-reindex — a new version in a new segment, old version tombstoned. Two consequences you must internalize: (1) a high update rate is expensive, because it generates tombstones and merge IO — and clinical charting is write-heavy at the end of a clinic day; (2) merges are background work that competes for CPU and disk with your live queries — "search got slow at 5 p.m." is often a big merge colliding with the end-of-day charting rush.
The near-real-time gap
That refresh step is where the eventual-consistency invariant becomes a concrete number. By default refresh_interval is 1 second: a successful index write is not searchable until the next refresh, up to ~1s later. You can force it:
refresh=wait_foron a write — block the response until the next scheduled refresh makes it visible (read-your-writes for that one write, without forcing extra refreshes).refresh=true— force an immediate refresh now.
Resist the urge to set refresh=true on every write. Each forced refresh creates a tiny segment, and a flood of tiny segments means a flood of merges — forcing per-write refresh can collapse indexing throughput. Use wait_for surgically on the rare write that genuinely needs read-your-writes (a clinician who just signed a note and immediately searches for it); leave the rest to the 1s default and tell the user the truth about staleness.
Index → shard → replica
The distribution model has exactly three nouns, and you must hold them precisely:
INDEX "pulsely_notes" (a logical collection of documents)
├── primary shard 0 ──── replica 0 (a Lucene index; the unit of distribution + parallelism)
├── primary shard 1 ──── replica 1
└── primary shard 2 ──── replica 2
(each shard is a full, independent Lucene index on some node)
- An index is a logical collection of documents (Pulsely's clinical notes, say) — not a Lucene index; that's the next level down.
- A shard is a Lucene index — the actual unit of storage, distribution, and parallelism. An index is split across N primary shards; a query fans out to all of them in parallel and merges the results. More shards = more parallelism, but also more per-query coordination overhead.
- A replica is a full copy of a primary shard, on a different node. Replicas give you high availability (lose a node, a replica is promoted) and read throughput (queries can hit replicas).
The trap that defines half of all OpenSearch incidents: primary shard count is fixed at index creation. You cannot reshard a live index in place — changing shard count means reindex into a new index. So shard count is a capacity decision you make up front (rule of thumb in §5: aim for ~10–50 GB per shard, and prefer too few over too many — over-sharding is the more common and harder-to-undo mistake). Replicas, by contrast, you can change anytime.
Mappings: the schema you must own
OpenSearch will infer a schema from your first document ("dynamic mapping"). In production you turn that off and define mappings explicitly, because the single most consequential decision in the whole chapter hides here: text vs keyword.
text— the field is analyzed (tokenized, stemmed) and indexed for relevance. You canmatchit. You cannot efficiently sort, aggregate, or exact-filter on it (its value was shredded into terms; "the original string" no longer exists as a unit).keyword— the field is stored whole, un-analyzed, as a single exact token. You can filter, sort, and aggregate on it. You cannot do relevance matching on its internal words.
This is not abstract in an EHR — it decides how each field must behave. A patient's name wants text (fuzzy, partial, "Jon" finds "John"). A patient's MRN and date of birth want keyword: an MRN lookup must be exact — you never want MRN 100455 to fuzzily match 100456 and pull up the wrong patient. So patient search is a two-field affair: keyword for the identifiers you match precisely, text for the names you match loosely.
The canonical, painful bug: you map note_type as text, ship, and discover you can't build the note-type facet (an aggregation) or filter cleanly on it, because text fields don't have the columnar doc-values that aggregations need. The fix is the multi-field — index the same source field two ways:
"subject": {
"type": "text", // analyzed → great for `match` relevance
"analyzer": "pulsely_text",
"fields": {
"keyword": { "type": "keyword", "ignore_above": 256 } // exact → sort/aggregate/exact-filter
}
}
// → query `subject` for relevance, `subject.keyword` for exact sorting/faceting
🛑 What we deliberately did not explain. Doc values — the on-disk columnar store (column-stride, like columnar OLAP layouts) that makes sorting and aggregations on
keyword/numeric fields fast without loading everything into heap — get named, not dissected, here. The same goes for the precise FST encoding of the term dictionary. The load-bearing takeaway is the rule: aggregate/sort/exact-filter onkeywordand numerics (doc-values), relevance-match ontext. The byte-level layout is a rabbit hole the rule lets you skip.
Building Pulsely's analyzer
An analyzer is a three-stage pipeline: char filters (operate on the raw character stream — strip HTML, map characters) → tokenizer (split into tokens) → token filters (transform the token stream — lowercase, fold, stem). For Pulsely clinical notes:
"analysis": {
"analyzer": {
"pulsely_text": {
"char_filter": ["html_strip"],
"tokenizer": "standard",
"filter": ["lowercase", "asciifolding", "english_stop", "english_stemmer"]
}
}
}
A subtle, important rule: some filters belong only at index time. For autocomplete you'd add an edge_ngram filter (so met → m, me, met to match prefixes) — but you apply it to the index analyzer only, with a plain search_analyzer at query time. If you ngram both sides, searching met becomes searching m OR me OR met against an index of ngrams, and relevance turns to mush. OpenSearch lets you set analyzer (index) and search_analyzer (query) separately precisely for this.
One clinical caution worth building into the analyzer decision: code systems are their own kind of text. ICD-10 (E11.621), CPT (99213), LOINC (4548-4), and RxNorm ingredient names are structured reference data, not prose. If you want to search the code catalogs by description ("diabetes with foot ulcer" → E11.621), index the descriptions as text; but keep the code itself as a keyword so E11.9 is matched exactly and never stemmed into fragments. A common Pulsely index blends both: free-text clinical prose analyzed for relevance, plus the coded fields kept exact for filtering and precise lookup.
Querying and aggregations
The query DSL is a structured JSON object — and the fact that it's structured, never string-concatenated, is the security spine of §8. The workhorses:
match— analyze the query text and match terms;operator: and|orandminimum_should_matchtune AND-vs-OR strictness.match_phrase— uses positions; terms must be adjacent (the phrase query from §3).multi_match— one query string across several fields with per-field boosts:subject^3means a hit in the note's subject line counts triple a hit in the body (encoding "short field = stronger signal" as a deliberate clinical weight).bool— composesmust/should/must_not/filter(§3's boolean layer made concrete).function_score— multiply the relevance score by business signals: recency decay (a recent encounter is usually more relevant than a three-year-old one), a boost for signed over draft notes. Relevance is clinical relevance, not just textual similarity.fuzziness— typo tolerance via Levenshtein edit distance (fuzziness: AUTOallows ~1–2 edits by term length), sometforninfindsmetformin. It's powerful, expensive (each fuzzy term expands to many candidates), and — a genuine clinical hazard — dangerous on drug and condition names, whereAUTOcan turnmetformininto a match formetronidazole, a completely different medication. Cap it hard, and consider disabling it entirely on the medication field.
A real Pulsely clinical-notes query, assembled:
{
"query": {
"bool": {
"must": [
{ "multi_match": {
"query": "metformin renal dose",
"fields": ["subject^3", "body", "problems^2"],
"fuzziness": "AUTO"
}}
],
"filter": [ // no scoring cost, cacheable
{ "term": { "note_type": "progress" } },
{ "range": { "encounter_date": { "gte": "2025-01-01" } } },
{ "term": { "status": "signed" } },
{ "term": { "clinic_id": "clinic_42" } } // server-enforced access scope — see §8
]
}
},
"aggs": { // faceting in the SAME round-trip
"by_note_type": { "terms": { "field": "note_type", "size": 10 } },
"by_month": { "date_histogram": { "field": "encounter_date", "calendar_interval": "month" } }
},
"size": 20,
"sort": [ "_score", { "encounter_date": "desc" } ]
}
Aggregations are how you power faceted search — "Progress notes (412), Discharge summaries (88)" and an encounters-per-month histogram — computed in the same request as the results. Note they run on note_type (a keyword, doc-values) and encounter_date (a date), never on a text field. That's the text-vs-keyword rule paying off.
The Node path (and a JVM aside)
The primary lane is @opensearch-project/opensearch (the @elastic/elasticsearch client is near-identical):
import { Client } from '@opensearch-project/opensearch';
const os = new Client({ node: process.env.OPENSEARCH_URL });
// Bulk index — one request, many docs. NEVER one HTTP call per doc.
const ops = notes.flatMap(n => [
{ index: { _index: 'pulsely_notes', _id: String(n.id), version: n.updated_ms, version_type: 'external' } },
{ subject: n.subject, body: n.body, problems: n.problems, note_type: n.note_type,
encounter_date: n.encounter_date, status: n.status,
patient_id: n.patient_id, provider_id: n.provider_id, clinic_id: n.clinic_id },
]);
const { body } = await os.bulk({ refresh: false, body: ops });
// CRITICAL: a 200 OK can still contain per-item failures.
if (body.errors) {
const failed = body.items.filter((it: any) => it.index?.error);
// dead-letter `failed` for retry — do NOT assume success from HTTP 200
}
// Pagination: search_after, NOT deep from/size.
const page = await os.search({ index: 'pulsely_notes', body: {
query: { match: { subject: 'metformin' } },
sort: [ { _score: 'desc' }, { id: 'asc' } ], // a tiebreaker sort is required
search_after: lastSortValues, // cursor from the previous page's last hit
size: 20,
}});
📎 Borrowed on credit: keyset pagination.
search_afteris the exact same keyset-cursor idea as the relational keyset pagination from Chapter 11 — carry the last row's sort key as a cursor instead of an offset. Deepfrom/sizemakes every shard collect and sortfrom + sizehits to discardfromof them — O(n) work that OpenSearch caps atindex.max_result_window(default 10,000) for self-protection. The principle is the contract chapter's; here it's just spelledsearch_after.
☕ Skippable JVM aside. On the JVM, Spring Data Elasticsearch gives you repository abstractions that hide the mapping and query DSL — convenient until you need a custom analyzer or
function_score, at which point the abstraction leaks and you drop to the native query builder anyway. You don't need the Java vocabulary; the transferable payoff is the recurring one: the engine concepts (mappings, analyzers, BM25, shards) are language-agnostic; the client is incidental. Learn the engine, and any client — Node, Java, anything — is a thin skin over it.
5. In production: keeping search honest about a moving Postgres
Standing up OpenSearch is the easy day. The hard, ongoing job — the one this section exists for — is keeping a derived index faithful to a Postgres that is mutating every second (every signed note, every amended problem list, every added medication), without lying to clinicians and without coupling your charting write path's correctness to a second system's uptime. This is the heart of the chapter.
Source-of-truth discipline
Reassert the invariant operationally: Postgres owns every clinical fact; OpenSearch holds a derived projection. Make that physical:
- Every document carries its Postgres primary key as
_id, so writes are upserts (idempotent: re-indexing the same note overwrites cleanly, never duplicates). - Every document carries a version —
updated_atas epoch millis, or a row version column — indexed withversion_type: external. OpenSearch then rejects a write whose version is ≤ the stored one. This is your guard against the nastiest sync bug: a delayed retry of an old update arriving after a newer one and stomping it. Picture an amended note reverting to its pre-amendment text because a stale retry landed last — in a chart, that's a clinical-safety event, not a cosmetic glitch. Out-of-order delivery is a when, not an if, so version every write.
The sync problem, stated honestly
The naive approach — "write Postgres, then write OpenSearch, in the same request handler" — is a distributed transaction you didn't design and can't honor. Walk the failure modes:
- Postgres commit succeeds, OpenSearch write fails (network blip, cluster busy,
429) → the index is permanently wrong and nothing retries it. The signed note never becomes findable. - OpenSearch write succeeds, the surrounding Postgres transaction rolls back → the index now shows a note that doesn't exist in the chart.
- OpenSearch is slow → your clinician-facing charting latency now includes OpenSearch's p99, and if OpenSearch is down, your note-signing endpoint is down — you've made a read-optimization a write-path dependency. A search outage must never stop a clinician from documenting care.
There is no ordering of two independent writes that fixes this, because either can fail after the other succeeds, with no shared transaction to roll both back. (This is the dual-write hazard, and it's an instance of the general delivery-semantics problem.)
The indexing pipeline, worst to best
✗ SYNCHRONOUS DUAL-WRITE
handler ──▶ Postgres COMMIT ──▶ OpenSearch index
▲ either leg can fail after the other; no atomicity; latency coupled
✓ TRANSACTIONAL OUTBOX (recommended default for Pulsely)
handler ── BEGIN ─ UPDATE clinical_notes … ; INSERT INTO outbox(…) ── COMMIT (one Postgres txn = atomic)
│
relay ──tail outbox──▶ OpenSearch _bulk (versioned upsert, retries)
✓ CHANGE-DATA-CAPTURE (CDC) (heavier infra, captures EVERY change)
Postgres WAL ──Debezium──▶ Kafka ──▶ indexer ──▶ OpenSearch
🛟 PERIODIC FULL RECONCILE / REINDEX (safety net under ALL of the above)
nightly: scan Postgres, re-upsert into OpenSearch, prune orphans
Transactional outbox is the workhorse and the right default for Pulsely. The move: in the same Postgres transaction that mutates a note, INSERT a row into an outbox table describing the change. Because it's one transaction, the outbox row is committed atomically with the data change — if the note write rolls back, so does the outbox entry; they cannot disagree. A separate relay process then reads unprocessed outbox rows and indexes them into OpenSearch with retries, marking each done on success. You've converted "two systems must both succeed at once" into "one atomic local write, then an at-least-once delivery I can retry forever" — and at-least-once is safe here precisely because your version-guarded upserts make re-delivery idempotent.
-- Inside the chart-write transaction (atomic with the data change):
BEGIN;
UPDATE clinical_notes SET subject = $1, body = $2, status = 'signed', updated_at = now() WHERE id = $3;
INSERT INTO outbox (aggregate, aggregate_id, op, payload, created_at)
VALUES ('clinical_note', $3, 'upsert', row_to_json(...), now());
COMMIT;
-- A relay process: SELECT … FROM outbox WHERE processed_at IS NULL ORDER BY id
-- → bulk-index to OpenSearch (versioned) → mark processed.
Change-Data-Capture (CDC) is the heavier alternative: a tool like Debezium tails the Postgres WAL and streams every row change to Kafka, where an indexer consumes them into OpenSearch. Its superpower is that it needs zero app code in the write path and captures changes made outside your app — a manual psql correction, a batch coding job, a data migration. Its cost is real infrastructure (Kafka, Debezium, connectors) and operational weight. Choose CDC when you have many writers you don't fully control (a common EHR reality: interface engines, HL7 feeds, and back-office tools all touch the chart), or you're already running Kafka; choose outbox when your app is the writer and you want minimal new infrastructure.
📎 Borrowed on credit: the outbox relay and the WAL tail. The mechanics of the outbox relay — at-least-once delivery, retries, dead-lettering, processing order — are the background-jobs/queue machinery of Chapter 26, and the transactional-outbox pattern is developed in full there. The mechanics of tailing the WAL into an event stream — logical decoding, Debezium, Kafka topics, offsets — are the change-data-capture and event-streaming material of Chapter 27. This chapter establishes why search needs one of them and what guarantees it must provide (atomic-with-source, idempotent, replayable); those chapters build the engines.
And whichever you pick: run a periodic full reconcile anyway. A nightly job that re-projects Postgres into OpenSearch and prunes orphans is your backstop against every bug the streaming path will eventually have. The index is disposable (the derived-view invariant) — lean on that.
Bulk, not trickle
Index with the _bulk API in batches (hundreds to low-thousands of docs per request, tuned by doc size), never one HTTP round-trip per document. And — the trap from §4 — a bulk response is HTTP 200 even when individual items failed. You must inspect errors: true and each item's status, retry the retryable ones, and dead-letter the rest. Treating a 200 as "all indexed" is how a reindex "succeeds" with thousands of notes silently missing from search — and a note you can't find is, to the clinician at the point of care, a note that doesn't exist.
Reindexing without downtime
Mappings are largely immutable — you can't change an analyzer on a live field. So changing analysis or shard count means building a new index and switching to it. Do it behind an alias:
app always queries the alias "pulsely_notes" ──▶ (currently) pulsely_notes_v1
1. create pulsely_notes_v2 with the new mapping
2. reindex / re-project all data into v2
3. atomically repoint the alias: v1 → v2 (one atomic alias swap; zero downtime)
4. delete v1 once confident
The application reads through the alias and never knows the swap happened. This is the single most useful operational pattern in the chapter; design for it from day one by never letting the app name a concrete index.
Operational baseline and relevance as a process
The numbers worth memorizing: target ~10–50 GB per shard; keep OpenSearch JVM heap ≤ 50% of RAM and under ~31 GB; take snapshots for backup; and watch four signals — indexing rate, merge pressure, search latency, and rejected requests (429, the threadpool saying "I'm saturated, back off").
☕ Skippable JVM aside — the 31 GB ceiling. Why 31 GB and not "as much as you've got"? In plain terms: below ~31 GB the JVM can address objects with short, compressed pointers; cross that line and every pointer doubles in size, so a bigger heap can actually hold less usable data — counterintuitively, more RAM assigned = less usable. You don't need the internals. Just treat ~31 GB as a hard ceiling and don't cross it.
Finally, relevance is iterative, not a config you set once. Use the _explain API to see exactly how a score was computed for a given doc/query. Build a small set of golden queries with clinician-judged "right" results — the terms providers actually type — then A/B your field boosts and BM25 k1/b against them. Relevance tuning is data-driven measurement: measure, change one knob, measure again — the same instinct you'll bring to performance work later.
🏭 Treat the OpenSearch cluster like cattle, not a pet. It holds no original clinical data (the derived-view invariant), so its disaster-recovery plan is gloriously simple: rebuild from Postgres. That single property — "I can always reconstruct it" — is what lets you reindex fearlessly, swap aliases, and run reconciles. The day someone starts treating the search index as the only place some clinical fact lives, you've lost that freedom and bought both a backup problem and a compliance problem, because the legal record now depends on a disposable projection.
6. Common pitfalls
Analyzer mismatch (the silent-empty-results bug). Signature: a query you know should match a note that's plainly in the chart returns nothing, no error, 200 OK. Fix: index-time and search-time analysis disagree (e.g., stemming one side, not the other; ngramming both sides; case mismatch). Run the _analyze API on both the field and the query string and compare the token lists — they must produce the same terms. This is the first thing to check on any "search finds nothing" report.
text where you needed keyword. Signature: "can't aggregate on this field," a fielddata memory blowup, or sorts that order by relevance instead of value — or, worse, an MRN that fuzzily matches the wrong patient because you analyzed it. Fix: the field is text (analyzed, no doc-values) but you're faceting/sorting/exact-filtering on it, or it's an identifier that must be exact. Add a .keyword multi-field and target that. Never enable fielddata: true on a text field to paper over it — it loads every term into heap and is a memory time-bomb.
Treating the index as strongly consistent. Signature: "I signed the note and search still shows the old version for a second." Fix: it's the near-real-time refresh + eventual-consistency invariant, working as designed. Set clinician expectations, drive sync through outbox/CDC, and use refresh=wait_for only on the specific write that needs read-your-writes. Don't force global refresh to "fix" it — you'll wreck indexing throughput.
Deep from/size pagination. Signature: page 500 times out or errors past max_result_window. Fix: switch to search_after (keyset cursor) for user pagination, or scroll/PIT for full exports. Deep offset paging is O(offset) per shard and rightly capped.
Ignoring partial bulk failures. Signature: a reindex "succeeded" (HTTP 200) but notes are missing or stale. Fix: a _bulk response is 200 even with per-item failures; inspect errors: true, handle each failed item, dead-letter the unrecoverable ones. A 200 from _bulk means "the request was received," not "every doc indexed."
Out-of-order writes clobbering newer data. Signature: a note reverts to an older version after appearing correct. Fix: a delayed retry of an old version overwrote a new one. Stamp every doc with updated_at/external version and use version_type: external so OpenSearch rejects stale writes. Never index without a version guard in an at-least-once pipeline.
Dual-write divergence. Signature: the index slowly drifts from Postgres — notes that were amended still showing old text, entries that were retracted still findable, with no obvious cause. Fix: synchronous dual-write where one leg silently failed. Move to outbox or CDC and run a scheduled full reconcile to catch whatever still slips.
Over-aggressive stop-word removal. Signature: "vitamin A", "hepatitis B", "type A aortic dissection" return garbage or nothing. Fix: don't strip stop words; keep them and let BM25's IDF naturally deprioritize common terms. Stripping is a 1990s space optimization that breaks real clinical queries.
Reckless fuzziness on clinical terms. Signature: a search for metformin also surfaces notes about metronidazole; a drug or condition name matches a dangerously similar one. Fix: fuzziness: AUTO on medication and diagnosis fields is a clinical-safety hazard, not just a precision annoyance. Cap edit distance tightly or disable fuzzy matching on those fields; reserve loose typo tolerance for names and free-text prose.
Over-sharding. Signature: cluster goes yellow/red, aggregations are slow, heap is stressed, all on a small corpus. Fix: too many shards = per-shard overhead and coordination cost that swamp a small dataset; and shard count is fixed at creation, so the fix is a reindex. Size for ~10–50 GB/shard and prefer too few; you can always add replicas, but you can't reshard in place.
7. Tradeoffs
Postgres full-text vs a dedicated search service — the chapter's central decision (and ADR). Postgres FTS (tsvector + a GIN index, with ts_rank for ranking) is a genuine full-text engine living inside your transactional database. Its decisive advantage is that there is no sync problem and no eventual consistency — search is just another query in the same transaction, always perfectly current, with one system to operate. For an EHR that is a real safety property: the chart and its search never disagree, and you never index PHI into a second datastore you also have to secure. It's sufficient for moderate corpora and modest relevance needs. What you give up versus OpenSearch: BM25-grade relevance and rich analyzers, first-class typo tolerance (fuzziness), facet aggregations, and horizontal scale-out. A dedicated service buys all of those — at the cost of a second datastore, a sync pipeline, the eventual-consistency tax, and a second PHI-bearing system to lock down. The decision drivers: corpus size, query volume, how much relevance/typo-tolerance/faceting the product actually needs, and your team's appetite for operating a stateful distributed cluster under HIPAA.
You should be ready to reverse the choice in either direction. Started on OpenSearch for a small note corpus and found the sync-and-ops cost dwarfs the value? Collapse back to Postgres FTS — fewer PHI-bearing systems is a feature. Started on Postgres and hit a relevance/facet/scale wall (the §1 sequential-scan cliff, or "clinicians can't find notes because we have no typo tolerance")? Move out to a dedicated service. The senior move is naming the threshold that flips it before you're forced across it at 2 a.m. (That threshold, named in the ADR, is the deliverable — not the choice itself.)
Sync pipeline: outbox vs CDC vs dual-write. Dual-write is rejected — un-atomic and latency-coupling, and in an EHR it couples note-signing availability to search availability. Outbox is simple and atomic-with-the-source but couples to app write paths (only changes your app makes are captured). CDC is decoupled and captures every change including out-of-band edits from interface engines and batch jobs, but is heavy infrastructure. Default outbox; reach for CDC when writers are many or out of your control.
Recall vs precision knobs. Stemming, fuzziness, match OR-vs-AND, and minimum_should_match each trade recall against precision. Loosen them and search "finds more" but surfaces junk (low precision); tighten them and results are clean but "it didn't find the note I meant" (low recall). Every knob has a user-facing symptom — learn to read the symptom back to the knob. In clinical search, weight the tradeoff toward precision on anything a provider might act on.
Refresh interval. Low (e.g. 1s) = fresher results, more segments, more merge pressure. High (e.g. 30s on a bulk-load or backfill index) = far better indexing throughput, staler reads. Tune per index, not globally.
Shard count. More shards = parallelism and future headroom but per-query overhead and slower aggregations; fewer = lean and fast for now but a reindex to grow. Over-sharding is the more common and harder-to-undo error; bias toward fewer.
Managed vs self-hosted. Elastic Cloud / AWS OpenSearch Service trade money and some lock-in for not operating a stateful distributed system at 3 a.m. — and, with a signed BAA, they take on part of the HIPAA operational burden. Self-hosting trades operational burden for control and cost. For most teams without a dedicated search/infra group, managed (with a BAA in place) is the right default — running a stateful, PHI-bearing cluster well is a real, ongoing job.
🚫 A framing this book rejects. "Use Elasticsearch for everything search-shaped." A second stateful, PHI-bearing datastore with its own consistency model, sync pipeline, capacity planning, access controls, and on-call burden is a large standing cost. Plenty of clinical products are best served by Postgres FTS for years; some never outgrow it. The senior question isn't "Postgres or OpenSearch?" — it's "what does this product's search actually require, and what's the cheapest correct system that delivers it?"
On the Elasticsearch-vs-OpenSearch fork: they split over a licensing change (Elastic moved off the open-source Apache 2.0 license; OpenSearch is the Apache-2.0 fork AWS leads). They're API-compatible today and diverging slowly. Decide on license posture and managed-offering fit, not feature folklore — at the engine level (Lucene, BM25, mappings, shards) everything in this chapter applies to both.
8. Security & scale notes
Never expose the cluster to the internet. OpenSearch's query DSL is, by design, an extremely powerful database API with no application-level authorization. Anyone who can reach it can read every document and craft a query that takes the cluster down. When those documents are clinical notes, "anyone who can reach it can read every document" means every patient's chart is one open port away — a catastrophic, reportable breach. So the cluster lives on a private network, behind your API, full stop. Your service receives a clinician's search params, builds a structured query object, and only then talks to OpenSearch. The cluster is never reachable from a browser; the browser never sees the query body.
Authorize at search time — never trust a client filter. Pulsely must not return another clinic's patients, a chart outside the caller's care relationship, or a record their role doesn't permit. Two complementary defenses: (1) don't index what must never be searchable into a broadly-queryable index; and (2) for everything else, your server injects the access-scope filter clauses (clinic_id = <caller's tenant>, and the minimum-necessary scope — care-team, panel, or assigned-provider) into the query, derived from the authenticated session, never from a client-supplied value. A filter the client controls is an IDOR-class data-leak hole — and here the leaked object is a patient's chart served to the wrong clinician. This is the trust-boundary discipline restated for search: re-derive authorization from server-side state, every request.
🔑 HIPAA is a first-class requirement of the search path, not an afterthought. Three obligations ride on every clinical query, and none is optional:
- Minimum-necessary access — the injected scope filter is the enforcement point. A broken or missing scope filter is not a bug ticket; it is a reportable HIPAA breach.
- Break-glass — emergency access can widen the scope (a covering provider who needs a chart they don't normally see), but only with a mandatory, recorded justification, and the widening is itself logged.
- Audit every access, including reads. In an EHR the immutable audit log must record not just writes but who searched for what and which records came back — search is a view of PHI. "Who accessed this patient's record?" is a required report, and your search API is one of the surfaces that has to answer it. Log the caller, the query, and the returned record IDs to the append-only audit store, every time.
The query-DSL injection analog. If you build the query by concatenating user input into a JSON string, you've recreated SQL injection in a new venue — a crafted input can inject clauses, widen the search past its access scope, or escalate to a denial-of-service query. The structural fix is the same as parameterized SQL: build a structured query object (the client serializes it safely), put user text only in value positions, and constrain which fields a user may target. Never let user input choose the field, the script, or the operator — in a PHI store, an attacker choosing the field is an attacker choosing which chart to read.
Query-of-death / DoS surface. Search has many expensive knobs an attacker (or a careless feature) can abuse: unbounded terms aggregations, deep from/size, wide fuzziness, leading-wildcard or regex queries, scripted scoring. Cap and validate every one: set search.max_buckets, terminate_after, per-request timeout, and reject queries that exceed sane bounds before they reach the cluster. Assume every knob will eventually be pointed at you.
PII/PHI and leakage. A text field is fully reconstructable from its index — what you index is extractable. Mind what goes in: don't index SSNs or PHI you don't need for search, encrypt snapshots at rest (they're PHI-at-rest), enforce TLS in transit, and remember that highlighting and _explain can leak adjacent field content — a snippet meant to show why a note matched can spill a neighboring line of the chart you never meant to surface. Treat every response the index can produce as a potential disclosure surface.
Scale behavior. Search is CPU- and heap-bound — scoring and segment merges both burn CPU, and indexing and querying contend for the same threadpools. Heavy end-of-day charting will degrade search latency unless you isolate the workloads or scale read replicas. And the tail is unforgiving: a query fans out to all shards and waits for the slowest one, so a single hot or oversized shard sets your p99 — tail latency driven by shard skew. Even shard sizing isn't only hygiene — it's a p99 lever.
Capacity reality. Index size roughly tracks corpus size × analysis expansion — and that multiplier can be large: positions, and especially edge-ngrams for autocomplete, can multiply on-disk size severalfold. Plan disk, heap, and replica count from real note count and update rate (which spikes predictably around clinic hours), not from a guess, and re-plan when the corpus grows an order of magnitude.
9. Interview lens & exercises
Interview questions
"Why can't a B-tree index serve LIKE '%term%', and what structure does?"
- Junior answer: "It's slow, just use Elasticsearch."
- Senior answer: a B-tree is sorted by whole-value prefix, so a leading wildcard has nothing to seek on and degrades to a full scan; the right structure is an inverted index (term → postings list) fed by an analysis pipeline, which also adds the dimension a DB index lacks entirely — relevance ranking. Names the data structure and the missing dimension.
"How do you keep a search index in sync with your primary database?"
- Junior: "write to both in the request handler."
- Senior: rejects naive dual-write as an un-atomic distributed transaction (either leg fails independently; latency couples note-signing to search uptime), then reasons about transactional outbox (atomic with the source, replayable) vs CDC (decoupled, captures all changes, heavier), insists on idempotent versioned upserts for out-of-order safety, and adds a periodic reconcile as a backstop. This question is the chapter's whole §5 in one answer.
"TF-IDF vs BM25 — what does BM25 actually fix?"
- Junior: "BM25 is newer and better."
- Senior: TF-IDF grows linearly with term frequency and handles length crudely; BM25 saturates term frequency (the
k1knob) so a repetitive templated note stops winning, and normalizes by field length (thebknob) so a hit in a short med list beats a hit buried in a long discharge summary — which is exactly what clinical documentation needs.
"When is Postgres full-text enough, and when do you reach for a search service?"
- Junior: "always use Elasticsearch."
- Senior: Postgres FTS wins when you value one system, no sync, perfect consistency, one PHI store and need only moderate scale/relevance; you move to a dedicated service when corpus size, query volume, relevance/typo/facet needs cross a threshold — and names the threshold, plus the cost of a second PHI-bearing system, plus the conditions under which they'd reverse the call.
"A clinician signs a note and doesn't see it in search for a second — bug or design?"
- Junior: "it's a bug."
- Senior: by design — the near-real-time refresh gap and the structural eventual-consistency of a derived index; explains
refresh=wait_forfor read-your-writes on the writes that need it, and why you don't force global refresh (it destroys indexing throughput). Treats consistency as a chosen staleness window, not an accident.
Exercises & the Pulsely increment
-
Build the index by hand. Take five clinical-note subject lines. On paper, run them through tokenize → lowercase → stem, write out the inverted index with postings
(docId, tf, positions), then hand-score the querymetformin dosetwice — once withtf × idf, once with BM25 — and watch a long, term-repeating discharge summary that TF-IDF over-ranks get correctly demoted by BM25's saturation and length normalization. Feel the formula. -
Stand up the real thing (Pulsely increment). Run OpenSearch in Docker. Define explicit mappings: a
pulsely_notesindex withsubject/body/problemsastext(custompulsely_textanalyzer) plus.keywordmulti-fields,encounter_dateas a date,note_type/status/clinic_id/provider_id/patient_idaskeyword; and apulsely_patientsindex overname(text, with capped fuzziness) plus exactkeywordmrnanddob. Bulk-load from Postgres. Implement amulti_matchsearch with field boosts (subject^3), fuzziness capped (and off on medication terms), a server-injectedclinic_id+status='signed'access-scope filter, and a note-type + date-histogram facet via aggregations returned in the same request. -
Build the sync pipeline (Pulsely increment). Implement the transactional outbox: write an
outboxrow inside the note-mutation transaction; build a relay that bulk-indexes with versioned idempotent upserts (version_type: externalfromupdated_at) and retries with dead-lettering; add a nightly full-reconcile job. Prove correctness the only way that counts: kill the relay mid-batch, restart it, and show the index converges with zero duplicates and zero lost updates — because an amended note that reverts is a clinical-safety event. -
Write the ADR. Prototype the same Pulsely search on Postgres
tsvector+ GIN alongside the OpenSearch version. On a ~1M-note dataset, measure relevance (against a clinician-judged golden query set) and p99 for both. Record the decision in ADR-022 "Postgres FTS vs OpenSearch for Pulsely clinical & patient search": the choice, the rejected option, the volume/latency/relevance/facet thresholds that flip it in either direction, and the operational cost (a second PHI-bearing datastore, a sync pipeline, eventual consistency, extra HIPAA surface) you're signing up for.
Key takeaways
- A B-tree is sorted by whole-value prefix, so
LIKE '%term%'has nothing to seek on and degrades to a full scan — and even free substring matching can't answer the real question, which is ranked relevance over a clinician's fuzzy intent. Different question, different structure. - The structure is the inverted index: term → postings list
(docId, tf, positions). Search = analyze the query, look up each term's postings, combine, score, sort. - A search engine is a pipeline, and the query is analyzed the same way the document was — break that symmetry and you silently match nothing.
- BM25 beats TF-IDF by saturating term frequency and normalizing by field length — it's the modern default. Put structured constraints (including your access-scope filter) in a cacheable, non-scoring
filter; put relevance inmust/should. - In OpenSearch: index → shards (fixed at creation) → replicas; segments are immutable (updates are delete+reindex); mappings are the schema you own, and
text(analyze, relevance) vskeyword(exact — MRN, DOB, codes) is the decision that bites hardest. - The search index is a derived, disposable projection of Postgres — never a system of record, and never the only place a clinical fact lives. You must be able to rebuild it from the source at will.
- Keep it in sync with the transactional outbox (atomic with the source write, replayable) or CDC, never naive dual-write; make every write a versioned idempotent upsert; and run a periodic reconcile as a backstop. The index is eventually consistent — choose the staleness window, and tell the truth about it.
- Search over PHI raises the security floor: the cluster is private, authorization is re-derived server-side and injected as a filter (a broken scope is a reportable breach), fuzziness is dangerous on drug names, and every access — including reads — is audit-logged to the immutable store.
- Postgres FTS — one system, no sync, perfect consistency, one PHI store — is enough until corpus/relevance/facet/typo needs cross a threshold you should name before you're forced across it.
← Previous: Ch 21 — Redis Beyond Caching · Up: Part IV overview · Master TOC · Next: Ch 23 — Distributed Systems Theory I →