Written by Technical Team | Last updated 04.12.2026 | 22 minute read
A retrieval-augmented generation (RAG) pipeline operating on clinical data needs to do considerably more than retrieve semantically similar text from a vector database. Patient records contain structured observations, coded diagnoses, medication histories, clinical documents, referral information and relationships between resources that carry meaning independently of their textual representation. Flattening these records into text, generating embeddings and retrieving the nearest matches produces an architecture that can lose clinically significant information before a large language model (LLM) receives its first prompt.
FHIR provides a useful foundation for addressing this problem because it represents healthcare data through a combination of structured resources, standardised terminology, explicit references and machine-readable metadata. A FHIR-native RAG pipeline uses these characteristics throughout the retrieval process, rather than treating FHIR simply as an upstream data source from which text is extracted.
In practical terms, this means combining deterministic FHIR queries, terminology-aware filtering, semantic search, resource relationship traversal and structured context assembly within a single retrieval architecture. The LLM operates downstream of these components, receiving a carefully selected representation of the clinical record instead of being relied upon to reconstruct clinical meaning from loosely associated text fragments.
Why FHIR-native RAG matters in healthcare: Unlike conventional vector-based RAG, a FHIR-native RAG pipeline combines structured clinical data retrieval, terminology-aware search and semantic similarity to preserve the meaning, relationships and provenance of patient records. This helps reduce the risk of LLM hallucinations, improve clinical accuracy and support traceable, evidence-based generative AI applications in healthcare.
The starting point is to establish a clear separation between the clinical data layer, the retrieval layer and the generation layer. The FHIR server or underlying electronic patient record (EPR) system remains the authoritative source of clinical information. Search indexes, vector databases and relationship stores are derived representations optimised for retrieval, while the LLM acts as a consumer of the assembled clinical context.
A production implementation might use HAPI FHIR or Firely Server as the FHIR persistence layer, PostgreSQL with pgvector for embedding storage, OpenSearch for lexical retrieval and a terminology service for clinical concept resolution. A Python or .NET orchestration service coordinates retrieval, enforces access controls, assembles context and manages interactions with the selected language model.
There is no inherent requirement to deploy a separate database for every retrieval mechanism. PostgreSQL can support structured queries, full-text search and vector similarity within the same database, making it a reasonable starting point for many healthcare applications. Larger implementations may benefit from separating these workloads where indexing throughput, query concurrency or operational requirements justify the additional infrastructure.
The resource types included in the retrieval architecture should be determined by the clinical workflows the application supports. A longitudinal patient summarisation application, for example, might work primarily with Condition, Observation, MedicationRequest, MedicationStatement, AllergyIntolerance, Encounter, DiagnosticReport, Procedure, Composition and DocumentReference resources. Other resources, including Practitioner, Organization, Specimen and Provenance, provide supporting context.
Each indexed representation should retain sufficient metadata to resolve it back to its originating resource. A practical index schema would include:
Preserving this metadata allows the retrieval service to constrain searches before applying semantic similarity. It also supports incremental index updates, resource-level evidence tracking, access control enforcement and the removal of superseded clinical information.
FHIR logical resource IDs should not be treated as globally unique. Two independent FHIR servers can legitimately contain resources with the same resource type and ID, referring to entirely different clinical entities. Index keys therefore need to incorporate the originating system or an equivalent namespace. Patient identity resolution must similarly take place before indexing or retrieval across multiple EPR systems, using an established identity service rather than assumptions based on matching resource identifiers.
FHIR version differences introduce another architectural consideration. An NHS implementation may need to consume both STU3 and R4 resources alongside proprietary clinical APIs. Normalising these into a consistent internal representation simplifies downstream retrieval, but the transformation must preserve the original resource, clinically meaningful extensions, identifiers and source metadata. A canonical model that discards information to achieve consistency can introduce problems that are difficult to detect during generation.
The internal retrieval model does not need to reproduce the complete FHIR specification. It should expose the clinical attributes required for efficient searching while maintaining a reliable route back to the original resource for verification and context expansion.
Embedding complete FHIR JSON resources is rarely the most effective approach to semantic retrieval. Raw resources contain considerable structural information that contributes little to embedding quality, including internal identifiers, namespace URLs, extension definitions and repetitive field names. Conversely, extracting only narrative text can remove the clinical attributes needed to interpret the information correctly.
A better approach is to implement resource-specific transformation functions that generate semantically meaningful, clinically faithful representations of each resource.
Consider an Observation representing a glycated haemoglobin measurement. The transformation should extract the observation code and display name, measurement value, unit, effective date, interpretation, reference range and result status. Where available, it should also retain relevant specimen information and associated diagnostic reports.
The resulting embedding input might resemble the following:
Resource: Laboratory observation
Test: Haemoglobin A1c (HbA1c)
LOINC code: 59261-8
Result: 58 mmol/mol
Effective date: 2025-09-12
Status: Final
The numerical result, unit and date should also be stored as independently queryable fields. An embedding is not a reliable mechanism for comparing numerical values, identifying thresholds or calculating changes over time. These operations belong in the structured retrieval layer.
The transformation logic needs to accommodate the polymorphic nature of FHIR resources. An Observation may express its value through valueQuantity, valueCodeableConcept, valueString, valueBoolean or several other data types. Multi-component observations, such as blood pressure measurements, require component-level extraction without losing the relationship between the constituent measurements.
Handling absent data requires particular care. An observation containing dataAbsentReason must not be transformed into a normal result with an empty or zero value. Likewise, a condition with a verification status of refuted should not be represented as an established diagnosis. These distinctions should survive every stage of the pipeline, from ingestion to the final context supplied to the model.
Medication resources present similar challenges. A MedicationRequest represents an order or prescribing intention, whereas a MedicationDispense records a dispensing event and a MedicationAdministration records an administration event. A MedicationStatement may represent reported medication use. Combining these resources into an undifferentiated medication history risks presenting prescribed treatments as treatments that the patient has definitely received.
Resource-specific transformation functions should therefore use language that accurately reflects the semantics of the underlying resource, including its status, intent and relevant dates.
Clinical documents require a different indexing strategy. A DocumentReference may point to a discharge summary, referral letter, PDF, pathology report or another clinical document stored externally or within a FHIR Binary resource. The ingestion pipeline must resolve the attachment securely, extract its content, identify the document structure and generate searchable chunks.
Conventional fixed-length chunking, where a document is divided into blocks of 500 or 1,000 tokens, is not particularly well suited to clinical documentation. It can separate a medication from its dosage instructions, a diagnosis from its negation or a clinical finding from the qualification that changes its meaning.
Section-aware chunking generally produces a more useful representation. A discharge summary might be divided into presenting complaint, clinical findings, investigations, treatment, discharge medications and follow-up arrangements. Each chunk inherits the parent document’s metadata, including document type, author, clinical encounter, creation date and source identifier.
For lengthy sections, smaller overlapping chunks can be generated while retaining the original section heading and parent document relationship. The retrieval service can then expand a matching chunk into its surrounding context when necessary, rather than passing an isolated fragment to the LLM.
Structured FHIR documents containing a Composition and associated resources should be processed using their existing section hierarchy and references wherever possible. Reconstructing that hierarchy from rendered narrative introduces unnecessary ambiguity.
Terminology normalisation should take place during ingestion as well as retrieval. NHS clinical systems commonly contain combinations of SNOMED CT, dm+d, ICD-10, legacy Read codes and locally defined coding schemes. Equivalent clinical concepts may be represented using different codes, descriptions and abbreviations across source systems.
A terminology service can resolve preferred descriptions, validate coding, expand value sets and apply explicitly maintained concept maps. FHIR terminology operations such as $lookup, $expand, $validate-code and $translate provide standardised interfaces for these functions.
Mapping must not assume that every source code has an exact equivalent in the target terminology. The original coding should be retained alongside mapped concepts, including information about the mapping relationship and terminology version. Where equivalence cannot be established, the original clinical expression remains available for lexical and semantic retrieval.
Keeping the index synchronised with the clinical record is equally significant. Depending on the capabilities of the source system, updates can be captured through FHIR Subscriptions, integration engine events, database change data capture or periodic polling using _lastUpdated. Population-scale ingestion may use FHIR Bulk Data export, receiving newline-delimited JSON files that can be processed through parallel ingestion workers.
Incremental indexing should be idempotent. Reprocessing the same resource version must not create duplicate clinical evidence, and updates should replace or deactivate superseded index entries. Deletions, entered-in-error records, patient merges and document replacements need explicit handling. Polling current resources alone will not reliably identify hard deletions, so the integration requires a deletion feed, supported history mechanism or periodic reconciliation process.
Where embeddings are generated asynchronously, it is useful to decouple structured indexing from embedding generation. A newly received laboratory result can become available through deterministic retrieval immediately, even if the embedding service is temporarily unavailable. For structured observations, this is often preferable to delaying clinical visibility until a vector representation has been generated.
A FHIR-native RAG pipeline should determine how information is retrieved according to the nature of the request. Treating every clinical question as a semantic similarity problem introduces avoidable errors and unnecessary computational overhead.
A request to retrieve the latest serum creatinine measurement is fundamentally different from a request to identify documentation discussing a patient’s difficulties adhering to their medication regimen. The former can be resolved through coded observation retrieval and temporal ordering; the latter is likely to require searching unstructured clinical notes and correspondence.
Consider a clinician asking:
How has this patient’s renal function changed over the past twelve months, and have there been any relevant medication changes or documented concerns?
The retrieval orchestration service needs to identify the clinical concepts, resource types, time constraints and relationships required to answer the question. It might issue a series of structured FHIR queries for renal function observations, medication orders and relevant encounters, alongside semantic searches for clinical documentation discussing renal impairment, treatment changes or medication-related concerns.
An illustrative FHIR R4 query for serum creatinine observations could take the following form:
GET /Observation
?patient=Patient/12345
&code=http://loinc.org|2160-0
&date=ge2024-10-01
&date=lt2025-10-01
&_sort=-date
&_count=100
In an actual HTTP request, the parameters would be appropriately URL-encoded. The query assumes that the FHIR server supports the specified search parameters and that the observations use the relevant LOINC code. A production implementation would typically resolve a maintained value set covering the appropriate clinical concepts rather than relying on a single hard-coded identifier.
The retrieval service must also inspect pagination links in the returned FHIR Bundle. The _count parameter requests a page size rather than guaranteeing that all matching resources will be returned. Ignoring subsequent pages can produce an incomplete clinical timeline without generating an obvious application error.
FHIR servers differ considerably in their support for search parameters, chained queries, sorting and terminology-based search modifiers. The server’s CapabilityStatement, available through the /metadata endpoint, provides an initial indication of supported functionality, although integration testing is still necessary to establish actual behaviour.
An orchestration layer can maintain a capability registry for each connected FHIR endpoint. Where an upstream system cannot support a particular query efficiently, the retrieval service can execute the equivalent operation against an authorised local structured index.
FHIR resource references provide another mechanism for expanding retrieved context. A matching DiagnosticReport may reference multiple observations, a specimen, a practitioner and an encounter. Retrieving the associated resources can reveal information that would not necessarily appear among the highest-ranked vector search results.
FHIR search operations support _include and _revinclude for retrieving related resources where the server implements the necessary reference search parameters. For example, including the observations referenced by a diagnostic report can provide the underlying measurements alongside the report’s clinical interpretation.
In a locally indexed architecture, these relationships can be represented through a relational edge table containing source resource identifiers, reference paths and target resource identifiers. A graph database is an option for applications requiring complex multi-hop queries, but ordinary relational joins are sufficient for many FHIR retrieval workflows.
Relationship expansion should be bounded. Recursively resolving every reference associated with an encounter could retrieve thousands of resources, many of which have little relevance to the question. The orchestration service should define permitted relationship paths, traversal depth and resource limits according to the retrieval task.
For unstructured clinical information, hybrid search combines lexical retrieval with embedding-based similarity. Lexical search is particularly useful for clinical abbreviations, medication names, specific diagnoses, laboratory identifiers and unusual terminology. Semantic search can identify related concepts expressed using different language.
A practical implementation might use PostgreSQL full-text search or OpenSearch to generate lexical candidates, alongside pgvector or another vector search engine to retrieve semantically similar document chunks. Reciprocal rank fusion can combine the independently ranked result sets without requiring their underlying relevance scores to be directly comparable.
For more complex requests, a cross-encoder reranking model can assess the relevance of each candidate against the original question. This is computationally more expensive than embedding similarity, so it is generally applied to a limited candidate set rather than the entire clinical record.
Patient-level filtering has implications for vector index design. Approximate nearest neighbour indexes, including HNSW indexes, can perform poorly when a highly selective metadata filter excludes most of the candidates discovered during traversal. A search across millions of clinical document embeddings restricted to one patient may return fewer relevant results than expected.
For many patient-specific queries, a conventional database index on the patient and tenant identifiers, followed by exact vector distance calculation over the matching records, is both efficient and predictable. Approximate vector indexes become more useful when searching larger authorised datasets. Where they are used, iterative scanning, appropriate partitioning and adjusted search parameters can improve recall.
The retrieval planner should never rely exclusively on a single combined relevance score. An active allergy record may need to be included because of the clinical workflow, regardless of its semantic similarity to the user’s question. Mandatory evidence requirements should be defined explicitly and applied independently of ranked retrieval.
Once the retrieval pipeline has collected candidate resources, the context assembly service must convert them into an input that the language model can interpret accurately. Sending the complete FHIR JSON representation of every matching resource is inefficient and can obscure the clinically significant information within hundreds of irrelevant fields.
A structured context envelope can organise evidence by resource type, clinical concept, encounter and effective date. Each item receives a stable evidence identifier linked to the originating resource and its version.
For a renal function review, a simplified context item could look like this:
{
"evidence_id": "E014",
"resource_type": "Observation",
"resource_id": "obs-78421",
"resource_version": "3",
"clinical_concept": "Serum creatinine",
"coding": {
"system": "http://loinc.org",
"code": "2160-0"
},
"effective_date": "2025-09-12",
"value": 118,
"unit": "umol/L",
"status": "final"
}
The generation service can require the LLM to associate clinical statements with evidence identifiers. The application then resolves these identifiers to the relevant FHIR resources, enabling users to inspect the original clinical information rather than relying solely on the generated summary.
Evidence identifiers also enable automated output validation. If the model refers to an identifier that was not included in the supplied context, the application can reject the response. Where the output contains structured claims about numerical results, dates or medication names, these can be checked against the retrieved evidence programmatically.
An existing evidence identifier does not, by itself, establish that the associated statement is supported. A model can reference a valid observation while misrepresenting its value or drawing a conclusion that the observation does not justify. Validation therefore needs to consider the relationship between the claim and the evidence, not simply the presence of an identifier.
Calculations should generally be performed outside the language model. Changes in laboratory results, medication durations, time intervals and other numerical comparisons can be calculated deterministically by the orchestration service and supplied as additional context.
Before comparing observations, the calculation service must establish that they represent sufficiently equivalent measurements, accounting for units, specimen type, measurement method and other relevant clinical attributes. Unit conversion should use validated conversion rules, including UCUM representations where available, rather than relying on the model’s interpretation of unit strings.
Temporal reasoning requires particular attention. FHIR distinguishes between when a clinical event occurred, when information was recorded, when a result was issued and when a resource was updated. A laboratory result imported into a new EPR system yesterday may relate to a specimen collected several years ago. Sorting by meta.lastUpdated would place this result at the beginning of a supposedly current clinical timeline.
The context assembly service should use resource-specific clinical dates and preserve uncertainty when only partial dates or date ranges are available. A Condition may contain an onset date and a recorded date, whilst a MedicationRequest contains an authored date that does not necessarily establish when the patient began taking the medication.
Conflicting records should remain visible to the model where the conflict cannot be resolved reliably. If one clinical system records a medication as active and another records it as discontinued, the retrieval service should retain both records, their respective dates and their provenance. Automatically selecting the most recently updated resource may produce an incorrect representation of the patient’s medication status.
Context window management is another engineering concern. Although contemporary language models can accept substantial input volumes, larger context windows do not remove the need for selective retrieval. Excessive input increases inference costs, response latency and the possibility that relevant clinical details will be overlooked.
Allocating context budgets by evidence category is often more effective than applying a single global token limit. Relevant structured observations can be represented compactly as a time series, leaving more space for clinical narratives that cannot be reduced without losing meaning. Older documents may be included selectively, whilst mandatory safety-related evidence receives a reserved allocation.
The output contract should reflect the intended clinical workflow. Rather than requesting unrestricted prose, the generation service can require a structured response containing the generated summary, supporting evidence, unresolved conflicts, missing information and any limitations affecting interpretation. A JSON Schema or model-supported structured output mechanism can enforce the expected shape, with additional application-level validation enforcing the clinical constraints.
The pipeline must distinguish between an absence of evidence and evidence of absence. If no allergy records are returned, that could indicate that the patient has no recorded allergies, that the source system does not expose allergy information, that access has been restricted or that the relevant query failed. The generation service needs explicit information about retrieval coverage to avoid presenting an incomplete record as a definitive clinical finding.
A healthcare RAG system introduces additional copies and representations of sensitive clinical information. Embedding stores, document indexes, orchestration caches, model requests, conversation histories and observability platforms all become part of the application’s information governance boundary.
Embeddings should be treated as potentially sensitive derived patient data. Converting clinical text into a numerical vector does not automatically anonymise the information, and associated metadata can make the relationship between an embedding and an individual explicit. Storage, encryption, retention and deletion policies should account for both the original clinical content and its derived representations.
For applications embedded within an EPR, SMART on FHIR can provide an authenticated user session and patient context, where supported by the clinical system. Backend ingestion services may use separate system-level authorisation to synchronise permitted resources. NHS integrations may also require API-specific authentication and authorisation mechanisms.
The permissions granted to an ingestion service must not automatically become the permissions available to an end user. An ingestion service may legitimately have access to an organisation-wide dataset, whilst an individual clinician is only authorised to access particular patients or categories of clinical information.
Authorisation should be enforced within the retrieval service before clinical candidates are passed to reranking or generation components. Tenant isolation, patient-level access, organisational permissions, purpose of use and applicable consent restrictions need to be evaluated independently of semantic relevance.
The LLM must not be responsible for determining which patient records the user is entitled to access. If the application supports model-generated retrieval plans or FHIR tool calls, these should pass through a controlled execution layer that validates resource types, search parameters, patient scope, permissions and request limits. The model should not receive unrestricted access to a FHIR endpoint or a general-purpose database query interface.
Clinical documentation should also be treated as untrusted input. A referral letter, imported PDF or externally generated clinical note could contain text that attempts to influence the model’s behaviour. Indirect prompt injection becomes particularly concerning where the LLM can initiate additional retrieval operations or interact with external services.
Separating retrieved evidence from system instructions is useful, but prompt formatting alone is not a sufficient security control. Tool permissions, restricted network access, validated arguments, read-only retrieval interfaces and independently enforced authorisation provide stronger boundaries. Any clinical writeback capability should be implemented as a separate, explicitly authorised workflow with appropriate validation and human oversight.
Evaluation needs to cover the complete pipeline rather than concentrating exclusively on the quality of generated text. A fluent clinical summary may conceal serious retrieval failures, incorrect terminology mappings or missing source records.
A meaningful evaluation framework should measure:
Standard information retrieval metrics such as recall@k, precision@k, mean reciprocal rank and normalised discounted cumulative gain are useful during development. However, relevance judgements in healthcare need to account for clinical significance. Missing a critical allergy record cannot reasonably be treated as equivalent to missing a routine administrative note.
Evaluation datasets should contain representative FHIR resources and realistic clinical questions, together with clinician-reviewed expected evidence sets. Synthetic patient records are useful for constructing reproducible test cases, particularly those involving uncommon resource combinations, deliberately conflicting information and clinical edge cases. Appropriately governed real-world datasets can provide additional evidence about how the pipeline performs against the inconsistencies found in operational clinical systems.
Regression tests should cover corrected laboratory results, discontinued prescriptions, refuted diagnoses, patient merges, incomplete dates, incompatible measurement units, inaccessible attachments and source system outages. Each of these conditions can change the correctness of a generated response without necessarily causing a conventional software exception.
Operational monitoring should instrument ingestion, terminology resolution, structured retrieval, vector search, reranking, context assembly, model inference and output validation as separate stages. Distributed tracing through OpenTelemetry can help identify whether increased response latency originates from an upstream FHIR server, a terminology service, an inefficient vector query or the model endpoint.
Index freshness should be measured at source system and resource-type level. A healthy embedding service is of limited value if the underlying medication index is several hours behind the EPR. The application should maintain ingestion watermarks, reconciliation statistics and explicit freshness thresholds appropriate to the clinical workflow.
If a source system becomes unavailable, the retrieval service should communicate that failure through the context envelope and application interface. It should not silently convert an upstream timeout into an empty result set. Depending on the intended use, the application may operate with clearly identified cached data, produce a partial summary or decline to generate a response until the necessary clinical information becomes available.
Reproducibility requires versioning more than the language model. Embedding models, terminology releases, resource transformations, chunking strategies, retrieval parameters, reranking models, prompt templates and context assembly logic can all influence the output. Changing the embedding model may require rebuilding the vector index, whilst changes to terminology mappings may alter which resources qualify for structured retrieval.
Maintaining versioned pipeline configurations and evidence manifests enables engineering teams to investigate historical outputs and compare alternative implementations. Audit records can capture the resources accessed, their versions, the requesting identity, the retrieval configuration and the generation outcome without routinely duplicating entire patient records into application logs.
For NHS deployments, these engineering controls should feed into the clinical risk management process associated with DCB0129 and DCB0160, where applicable. Hazards such as cross-patient information leakage, omitted clinical evidence, stale medication data and incorrect attribution should have identifiable software controls, verification tests and operational monitoring. Applications with an intended medical purpose may also require assessment under medical device regulations.
The most dependable implementation is one in which the language model remains a replaceable component rather than the foundation of the clinical data architecture. Patient identity, terminology, access control, temporal ordering, numerical calculations and evidence traceability should continue to function independently of the model. This allows the engineering team to improve retrieval quality, change inference providers and extend clinical workflows without repeatedly reconstructing the mechanisms that establish the accuracy and integrity of the underlying clinical information.
Is your team looking for help with healthcare AI and software development? Click the button below.
Get in touch