Blog

    FHIR Search Optimization: Query Patterns Developers Get Wrong

    By GauravAugust 18, 20269 mins read
    On this page

    FHIR search optimization starts with fixing the query patterns developers get wrong: a token parameter sent as a string, a chained path the server never published, or related resources fetched one by one instead of with _include or _revinclude. HL7 FHIR R4 search is the specification to write against, not a vendor's sample screen.

    Written for digital health founders and hospital CTOs whose apps read from EHR FHIR APIs, it covers each pattern, paging, ignored parameters, tests and logging.

    Which FHIR search query patterns do developers get wrong?

    The FHIR search query patterns developers most often get wrong are sending a token as a string, guessing a chained path, and leaving out _include or _revinclude when the screen needs the referenced resources. Agnotic Technologies writes each search against HL7 FHIR R4 and the server's CapabilityStatement, never against a query copied from another EHR.

    FHIR searches returning the wrong patients or empty bundles?

    We use token for codes, chained search only on published paths, and _include or _revinclude for related resources.

    • Token: coded values, with the system when the server requires it. String is text, not a code.
    • Chained search: a path the CapabilityStatement lists, such as subject.name. An unpublished chain is a guess.
    • _include: resources the matching row already references.
    • _revinclude: resources that reference the matching row. It is not a second search you invent in a loop.

    Read the server's CapabilityStatement before writing the query, because it lists the search parameters, chains and includes that server supports. Exports of a whole population belong to Bulk Data, not to interactive search.

    What must the client not do?

    The client must not paginate by guessing _count, and it must not follow every link in a bundle as if it were an include. Agnotic follows next links the server sent, and only includes what _include or _revinclude named.

    • Do: send token parameters for codes, with system|code when required.
    • Do: name _include or _revinclude for related resources you will display.
    • Do not: GET each referenced id in a loop after a search that could have included them.

    Why does a string search return patients you did not ask for?

    A string search matches the start of a value and ignores case and accents by default, so name=Eve also returns Evelyn. That is specified behaviour, not a server bug.

    In FHIR R4, string search ignores case and accents and matches values that equal or start with the input; the :exact and :contains modifiers change that. Token matching is literal, not based on subsumption. A server SHALL reject a search that uses a modifier it does not support for that parameter.

    • Default: family=smith matches Smith, Smithson and SMITH.
    • :exact: family:exact=Smith matches only that spelling and casing.
    • :contains: family:contains=smi matches the text anywhere in the value, which is broader still.

    A rejected modifier tells you something about the server. Do not retry the search without the modifier and present the wider result as if it were the narrow one.

    How should a token parameter carry the system and the code?

    A token parameter should carry system|code whenever the code could exist in more than one code system. A bare code matches that code in any system, which is how a lab search picks up an unrelated local code.

    Token forms for a code parameter
    FormMatchesWhen to use it
    code=[system]|[code]That code in that system onlyDefault for clinical codes such as LOINC or SNOMED CT
    code=[code]That code in any systemOnly when the server documents one system for the element
    code=|[code]That code where no system is recordedRare; legacy data without a system
    code=[system]|Any code in that systemFiltering by code system, not by concept

    Because token matching is literal, a search for a parent concept does not return its children. Expand the value set first and send the codes, or use a subsumption modifier only where the server lists one.

    Which chained searches are safe to send?

    A chained search is safe when the server supports the reference parameter, the target type and the parameter on the target. When a reference can point to more than one type, name the type in the chain.

    • Typed chain: DiagnosticReport?subject:Patient.name=peter, because subject can also point at a Group, Device or Location.
    • One hop: prefer a single chain level. Each extra level is another join on the server and another place where support varies.
    • Reverse chain: Patient?_has:Observation:patient:code=[system]|[code] selects patients by properties of resources that point at them.

    If a chain is not supported, the fallback is two searches: find the target ids first, then search with those ids. That is explicit and testable, unlike a chain the server might drop.

    When should you use _include and when _revinclude?

    Use _include when the matching resource holds the reference you want to follow, and _revinclude when other resources hold a reference back to the match. The direction of the reference decides it, not which resource feels primary.

    Picking the right include
    NeedParameterExample
    The practitioner who wrote each MedicationRequest_includeMedicationRequest?patient=[id]&_include=MedicationRequest:requester
    Provenance records that point at each match_revincludeCondition?patient=[id]&_revinclude=Provenance:target
    References inside included resources_include:iterateOnly where the server lists iterate support

    Included entries come back with search mode 'include'. Any code that counts results should count only entries in search mode 'match'.

    Why is _count a ceiling and not a page size you can rely on?

    _count is a ceiling: the server must not return more than you asked for, but it may return fewer. A short page does not mean you reached the end; only a missing next link means that.

    _count tells a FHIR R4 server how many resources to return per page. The server SHALL NOT return more than requested but may return fewer, and _count does not cover included resources. If an included resource cannot be retrieved, it is omitted and no error is returned.

    • Follow the next link exactly as the server returned it. Do not rebuild it with your own offset.
    • Stop when there is no next link, not when a page is shorter than _count.
    • Do not compare entry counts with Bundle.total, because included resources are not part of the total.

    Agnotic wraps paging in one client function so every screen collects results the same way. A screen then receives a complete list or an explicit error, never a silent first page.

    What happens when the server ignores a parameter you sent?

    By default a server should ignore parameters it does not recognise or support and answer as if they were never sent. The self link in the response shows which parameters it actually applied.

    FHIR R4 servers SHOULD ignore unknown or unsupported search parameters. The client can see which parameters were applied in the self link of the returned bundle, and can send Prefer: handling=strict to ask for an error instead.

    • Compare: parse the self link and check that every parameter you sent is present.
    • Strict mode: send Prefer: handling=strict in testing so unsupported parameters fail loudly.
    • Production: if a parameter is missing from the self link, stop and log instead of showing the broader result as if it were filtered.

    This check catches the worst kind of wrong bundle: one that looks correct but holds every patient instead of one.

    A worked example: medications and prescribers for one patient

    A worked example: a clinician-facing app needs a patient's active medication requests and the prescriber for each. The first draft searched MedicationRequest by patient, then fetched each Practitioner by id in a loop.

    The revised search sends patient as a reference, status=active as a token, and _include=MedicationRequest:requester. One bundle now carries the matches and the prescribers, each marked by search mode.

    The client follows next links until none remain, checks the self link for status and the include, and counts only match entries for the list badge. Where a requester could not be resolved, the row shows the reference without a name instead of failing the page.

    How do you test that a search returns the right bundle?

    Test against a fixed set of test resources where you already know which ones should match. Assert on the bundle's contents and its self link, not only on the HTTP status.

    • Positive: the known matches are present, by id, in match mode.
    • Negative: a near miss, such as the same code in a different system, is absent.
    • Paging: a result larger than one page is fully collected by following next links.
    • Ignored parameters: every parameter you send appears in the self link.
    • Includes: each included resource appears once and is not counted as a match.

    Run the suite against every EHR the client connects to. The same query can pass on one server and return a broader bundle on another.

    Log the search shape, the self link the server returned, and the counts by search mode. Do not log raw parameter values that identify a patient.

    • Resource type and parameter names sent, with values masked where they identify a person.
    • Parameter names present in the self link, and any that were missing.
    • Pages fetched, matches, includes, and any OperationOutcome entries.
    • Server and FHIR version, so one EHR's behaviour is not mistaken for another's.

    Parameters in a GET URL can end up in proxy and server logs. Where the server supports it, a POST to [type]/_search keeps them in the request body.

    Which search mistakes only show up with production data?

    Mistakes that pass on a small sandbox often fail on real volumes and real coding. These are the ones Agnotic checks for before go-live.

    • Mixed code systems: production data carries local codes beside standard ones, so a bare token matches both.
    • Missing values: resources without the searched element are left out, which can drop records a clinician expects. The :missing modifier finds them.
    • Large includes: a broad _revinclude on a busy patient returns far more resources than the screen needs.
    • Sort assumptions: without _sort, the server's default order is not a clinical order.
    • Stale paging: some servers stop honouring old next links, so a failed page means restarting the search, not skipping ahead.

    Agnotic reads each server's CapabilityStatement, writes token, chain and include parameters against that list, wraps paging and self-link checks in one client function, and runs the same search tests against every EHR the client connects to.

    Token, chain, include, then the next link

    HL7 search first. CapabilityStatement second. No guessed chains.

    Related reading on Agnotic

    Reading what the EHR API supports, paging, mapping challenges and SMART scopes.

    Sources

    Frequently Asked Questions

    Often the parameter is a token and was sent as a string, or the system was omitted on a server that requires it.

    Talk to an engineer about your project

    Send the search that is failing. We will recast token, chain, and include against HL7 R4 and the server's CapabilityStatement.