Section: 14

references.html

Resource References

Maturity Level: NormativeStandards Status:Normative

Many of the defined elements in a resource are references to other resources. Using these references, the resources combine to build a web of information about healthcare.

References are always defined and represented in one particular direction - from one resource (source) to another (target). The corresponding reverse relationship from the target to the source exists in a logical sense, but is not typically represented explicitly in the target resource. For external references, navigating these reverse relationships requires some external infrastructure to track the relationship between resources (the REST API provides one such infrastructure by providing the ability to search the reverse relationship by naming search parameters for the references and by providing support for reverse includes).

Because resources are processed independently, relationships are not considered to be transitive. For example, if a Procedure resource references a particular Patient as its subject, and has a Procedure resource as its reason, there is no automatic rule or implication that the condition has the same patient for its subject. Instead, the subject of the condition must be established directly in the Condition resource itself. Another way to state this is that the context of the subject is not "inherited", nor does it "conduct" along the relationship to condition. The only exception to this is the case of contained resources (see below). Note that in practice, the relationships need to describe a logical and coherent record, and in the case of the Condition and Procedure described here, they would usually be required to have the same patient for their subjects. Profiles and/or implementation guides may make rules about this (also see GraphDefinition).

This specification describes the use of references to other resources that have the same FHIR version as the source of the reference. Expected behavior for references across FHIR versions is presently undefined.

References are made to resource based on their identity; there are several different identities to refer to.

Resources contain two types of references to other resources:

For canonical references, see below. The general references are handled by the Reference type. which contains at least one of a reference (literal reference), an identifier (logical reference), and a display (text description of target). In addition, it may a contain a target type.

 

Constraints

At least one of reference, identifier and display SHALL be present (unless an extension is provided).

Target Type

In resources, a Reference always point to another resource, which has a fixed and known type. If appropriate, this type can be specified in the reference itself. In principle, the type of the target reference can be determined by resolving the reference (using the approaches described below), and examining the content returned to determine the type; for this reason specifying the type is almost always duplication of information. However resolving references may be a very slow operation, or impossible in practice due to various practical concerns. For this reason, the reference may indicate directly the target resource type:

 "subject": {
   "reference" : "http://someserver/some-path",
   "type" : "Patient"
 }

When the type is provided directly, it SHALL agree with the type determined by resolving the resource.

Note that in practice, it is often not necessary to know the type of the target resource is, unless it's going to be resolved anyway, so in many cases, specifying the type of the target resource is unnecessary.

In order to support Logical Models, the type element has the type of "uri". Whenever type appears in resources, the uri is represented relative to the base URI http://hl7.org/fhir/StructureDefinition/. For resources, then, the value is simply a code that is the type of resource - e.g. "Patient".

Literal References

The reference is the key element - resources are identified and addressed by their URL. It contains a URL that is either

Notes:

A relative reference to the Patient "034AB16" in an element named subject on a FHIR RESTful server:

  <subject>
    <reference value="Patient/034AB16" />
  </subject>

An absolute reference to a Structure Definition in an element named profile:

{
  "profile" : {
    "reference" : "http://fhir.hl7.org/svc/StructureDefinition/c8973a22-2b5b-4e76-9c66-00639c99e61b"
  }
}

Note that in a bundle during a transaction, reference URLs may actually contain logical URIs (e.g. OIDs or UUIDSs) that resolve within the transaction. When processing the transaction, the server replaces the logical URL with what is the correct literal URL at the completion of the transaction.

References are allowed to be version specific - that is, a reference may point to a specific version of a resource. e.g. :

  <target>
    <reference value="http://example.org/fhir/Observation/1x2/_history/2" />
  </target>

This is usually associated with audit trail or provenance information where it is important to reference a particular version of a record, not the most current information.

Logical References

In many contexts where FHIR is used, applications building a resource may know an identifier for the target of the reference, but there is no way for the application to convert this to a literal reference that directly references an actual resource. This situation may arise for several reasons:

For further discussion of the use of identifiers on resources, see Consistent Resource Identification. In these cases, the source application may provide the identifier as a logical reference to the entity that the target resource would describe.

A logical reference to the Patient with an SSN of 000111111:

  <patient>
    <identifier>
      <system value="http://hl7.org/fhir/sid/us-ssn" />
      <value value="000111111" />
    </identifier>
  </patient>

There is no requirement that a Reference.identifier point to something that is actually exposed or exists as a FHIR instance (except, of course, that the reference will need to be resolved to a target resource if any information from it is required in a FHIR context). The reference SHALL point to a business concept that would be expected to be exposed as a FHIR instance, and that instance would need to be of a FHIR resource type allowed by the reference For example, it would not be legitimate to send the identifier for a drug prescription if the type were Reference(Observation|DiagnosticReport). One of the use-cases for Reference.identifier is the situation where no FHIR representation exists (where the type is Reference (Any).

When processing a resource, an application may be able to use the identifier directly, on the grounds that all it needs is the identifier, or it may be able to resolve the identifier directly. Alternatively, it may be able to use a server to resolve the logical reference to a literal reference to a resource.

Irrespective of how the resolution occurs, any system processing a logical reference will only be able to resolve the identifier to a reference if it understands the business context in which the identifier is used. Sometimes this is global (e.g. a national identifier) but often it is not.

For this reason, none of the useful mechanisms described for working with references (e.g. chaining, includes) are possible, nor should servers be expected to be able to automatically resolve the reference. Servers may accept an identifier based reference untouched, resolve it, and/or reject it - see CapabilityStatement.rest.resource.referencePolicy.

When both logical and literal references are provided, the literal reference is preferred. Applications processing the resource are allowed - but not required - to check that the identifier matches the literal reference, if they understand how to resolve the logical reference.

Applications converting a logical reference to a literal reference may choose to leave the logical reference present, or remove it.

Reference Description

Irrespective of whether a literal and/or logical reference is provided, or neither, the display element may be used to provide a very short description of the target resource.

  <custodian>
    <reference value="Organization/123" />
    <display value="HL7, Inc" />
  </custodian>

This text can be used by any application that cannot resolve the reference to fill out the text portion of a hyperlink referring to the target resource, for instance. It can also save time fetching a target resource, and determining how to convert it to a very short textual description.

In general, the display, if populated, does not have identical content to the Resource.text of the referenced resource. The purpose is to identify what's being referenced, not to more fully describe it.

Canonical URLs

Many resource types have a defined element "url" which is the canonical URL that always identifies the resource across all contexts of use. Typically, terminology, conformance or knowledge resources have canonical URLs. The canonical URL is the preferred way to reference a resource instance for the resource types on which it is defined. See Canonical Resource Identity for further information.

References to canonical URLs use the canonical type to refer to the url element on the conformance/knowledge resources (which has the type uri):

<valueSet value="http://hl7.org/fhir/ValueSet/my-valueset"/>

References of type canonical may include a version, in order be precise about which version of the resource is being referred to. To do this, append the version to the reference with a '|' like this:

<valueSet value="http://hl7.org/fhir/ValueSet/my-valueset|0.8"/>

This is a version specific reference to a value set. Note that this refers to the ValueSet.version not the ValueSet.meta.versionId. Searching for this on a FHIR server would look like this:

GET fhir/ValueSet?url=http://hl7.org/fhir/ValueSet/my-valueset&version=0.8

Note that if a References to a canonical URL does not have a version, and the server finds multiple versions for the value set, the system using the reference should pick the latest version of the target resource and use that. Servers SHOULD support version specific searching for canonical URLs by automatically detecting the presence of a |[version] and performing the appropriate search. Additional notes about searching on versioned references to canonical URLs:

Systems resolving references to canonical URLs SHOULD first try to resolve the reference using the canonical reference (e.g. search on a known registry of terminology, conformance, or knowledge resources as appropriate), and then fall back to direct resolution using the URL as a literal reference if a local version of the canonical resource cannot be found. This approach is safe because the approaches must refer to the same artifact, though implementations will need to make appropriate arrangements regarding the version and/or currency of their local copy of the artifact.

The following resources have canonical URLs and are allowed to be the target of a references to a canonical URLs:

A few elements that have references to canonical URLs have a targetProfile of http://hl7.org/fhir/StructureDefinition/Resource, which is shown as canonical(Any) in this specification. Such references SHALL only reference one of these types of resources.

Canonical Reference and Fragments

Canonical references may include a fragment when the reference is to a contained Contained Resources. When the target of a canonical reference is a contained resource, the canonical reference will have a fragment as part of the URL:

  <valueSet value="http://fhir.acme.com/Questionnaire/example|1.0#vs1"/>

This is a reference to the value set with id "vs1" in version 1.0 of the identified questionnaire. The common case for this is internal references:

  <answerValueSet value="#vs1"/>

Which is the form for references to the contained value set inside the above example questionnaire.

Rendering References in Resource Narratives

References between resources create a particular challenge when rendering resource narratives: the narrative includes information from the target resources. As an example, consider an Observation with a patient reference:

{
  "resourceType" : "Observation",
  "subject" : {
    "reference" : "Patient/example"
  }
}

When represented in XHTML, this reference will generally become something like:

  ...
  <p>Patient: <a href="Patient/example">Peter James CHALMERS (12345)</a></p>  ...

This implies that the system generating the resource narrative will need to resolve the reference and generate a summary, or that the reference will contain the information (generated by an application that is able to resolve the reference):

{
  "resourceType" : "Observation",
  "subject" : {
    "reference" : "Patient/example",
    "display" : "Peter James CHALMERS (12345)"
  }
}

Narrative that contains information derived from other resources like this is still regarded as 'generated' (for Narrative.status).

It's not mandatory to generate narrative this way. Narrative may be generated like this:

  ...
  <p>Patient: <a href="Patient/example">(link)</a></p>  ...

However users generally prefer a more informative narrative, so this is not always acceptable.

Applications (and networks of applications) will need some kind of systematic approach for resolving references and/or maintaining the currency of narratives as the resources they reference are changed. The exact details of this are out of scope for the FHIR standard.

Applications are encouraged to use the Reference.display element to store a user presentable representation of the resource for when the resource cannot be resolved (e.g. due to network errors). The canonical type does not have a display element because applications are generally expected to carry cached copies of the resources that are the target of the canonical references. If this functionality is still needed or desired anyway, the Rendered Value extension can be used.

Contained Resources

In some circumstances, the content referred to in the resource reference does not have an independent existence apart from the resource that contains it - it cannot be identified independently, and nor can it have its own independent transaction scope. Typically, such circumstances arise where resources are being assembled by a secondary user of the source data, such as a middleware engine. If the data available when the resource is constructed does not include record keys or absolute identification information, then a properly identified resource cannot be assembled, and even if an arbitrary identification was associated with it, the resource could never be the subject of a transaction outside the context of the resource that refers to it.

For example, consider a situation where an interface engine is creating a Condition record on a patient from an HL7 v2 message, and the only information about the primary surgeon is her first name and last name (REL-7.2 & REL-7.3). In the absence of a controlled practitioner directory, this is not enough information to create an identified Practitioner resource since more than one practitioner might have the same name.

In these circumstances, the resource is placed directly in-line in the resource. This SHOULD NOT be done when the content can be identified properly, as once the identification is lost, it is extremely difficult (and context dependent) to restore it again. The FHIR version of a contained resource SHALL always be the same as the resource that contains it.

An example of a contained resource:

 <Condition xmlns="http://hl7.org/fhir">
  <contained>
    <Practitioner>
      <id value="p1"/>
      <name>
        <family value="Person"/>
        <given value="Patricia"/>
      </name>
    </Practitioner>
  </contained>
  <!-- other attributes -->
  <asserter>
    <reference value="#p1" />
  </asserter>
  <!-- other attributes -->
 </Condition>

The same example in JSON:

{
  "resourceType" : "Condition",
  "contained": [
    {
      "resourceType" : "Practitioner",
      "id" : "p1",
      "name" : [{
        "family" : "Person",
        "given" : ["Patricia"]
      }]
	  }],
   "asserter" : {
     "reference" : "#p1"
  }
}
Contained resources are still a reference rather than being inlined directly into the element that is the reference (e.g. "custodian" above) to ensure that a single approach to resolving resource references can be used. Though direct containment would seem simpler, it would still be necessary to support internal references where the same contained resource is referenced more than once. In the end, all that it would achieve is creating additional options in the syntax. For users using XPath to process the resource, the following XPath fragment resolves the internal reference:

ancestor::f:*[not(parent::f:*)]/f:contained/*[@id=substring-after(current()/f:reference/@value, '#')]

Some notes about use and interpretation of contained resources:

Like other resources, contained resources can contain narrative. However, when rendering the containing resource, the narrative of the contained resources is ignored, so relevant information about contained resources SHALL appear in the narrative of the containing resource.

Resources that are contained inline do not "inherit" context from their parent resource. For instance, if the parent resource contains a "subject", and the contained resource also has a "subject" element defined, there is no implication that the contained resource has the same subject as the parent resource.

Resources can only be contained in other resources if there is a reference from the resource to the contained resource, or if the contained resource references the container resource. This is intended to ensure that the meaning of the contained resource is clear, and that there is no confusion as to its significance.

For a resource that references the container, the reference is "#", like this:

<Patient xmlns="http://hl7.org/fhir">
  <id value="something"/>
  <contained>
    <Provenance>
      <!-- no id necessary (though still allowed) -->
      <target>
        <reference value="#"/>
      </target>
    </Provenance>
  </contained>
  <!-- other attributes -->
</Patient>

There is no way to search for contained resources that reference their container. Is this a problem?

Feedback is welcome here.

Circular Resource References

Some references are circular - that is, the reference points to another resource of the same type. There are several reasons why a resource may refer to other resources of the same type:

For parameters where the relationship is a strict hierarchy (i.e. where it would be wrong to have circular references, even transitively), there is additional search support for traversing the hierarchy using :above and :below modifiers on the search parameters.

Hierarchical references with search parameters (can have :above and :below modifiers on search parameters):

References that may refer back to the source instance:

References for which the hierarchical behavior is not specified:


resourceguide.html

Guide to Resources

Maturity Level: N/AStandards Status:Informative

The FHIR specification defines a set of resources, and an infrastructure for handling resources. In order to use FHIR to create solutions for integration requirements, implementers must map their problems to resources and their content.

The Resource List provides views of the resources organized in several different ways, and is the primary entry point to the resources.

This page describes the resources and their functional intent in more detail to assist implementers to understand their purpose and scope, and their supporting classifications.

Where to find common concepts in this specification:

Concept Example Where to find
Clinical Findings
Laboratory ResultsBlood panels such as CBC with Differential, Liver Panel, etc.DiagnosticReport with Observations
Imaging Study FindingsCT Scans, MRI, Plain Radiographs, Ultrasounds)DiagnosticReport (some with Observations)
Diagnostic Test ResultsEKG, pulmonary function test, EEGObservations (and maybe a DiagnosticReport)
Vital SignsTemperature, Blood Pressure, Heart Rate, Respiratory RateObservation
Other Physical Exam FindingsAuscultation findingsObservation
Pulmonary Artery Catheter readingsPulmonary artery pressureObservation
Patient Problems, Allergies and Adverse Events
AllergyFood or drug allergiesAllergyIntolerance
Clinical DiagnosisDiabetes, Congestive Heart FailureCondition
Adverse EventAdverse reaction to an agent, falls, adverse surgical events, hospital infectionsAdverseEvent
Patient History
Chief ComplaintCough, Pain, Fever, FatigueCondition
Past Surgical HistoryAppendectomy, Hernia repairProcedure
Past Medical HistoryDiabetes, Congestive heart failureCondition
MAR (Medication Administration Record)Warfarin 5mg PO administered on 12/10/2013 at 3pmMedicationAdministration
Home MedsWarfarin 5mg, 30 day supply, dispensed on 12/01/2013MedicationStatement
Social HistorySexual behavior, Smoking status, Alcohol intake, Illicit drug useObservation
Family HistoryMother has diabetesFamilyMemberHistory
Signs & Symptomsfrom a review of systems- Pain, FeverCondition
Suggested Physician Orders
Proposal for a laboratory testA blood panel, a stool analysisServiceRequest
Proposal for an imaging procedureCT Scan, MRI, X-RaysServiceRequest
Proposed Diet OrderAn oral diet orderNutritionOrder
Proposed respiratory orderOxygen deliveryNot done yet
Proposed MedicationsAspirin, LisinoprilMedicationRequest
Proposed SupplyWheel Chair, Food TraySupplyRequest
Interdisciplinary Care Planning
Patient GoalReduce risk of falls, lose weightGoal (as part of a CarePlan)
InterventionPatient assessmentsServiceRequest

In addition, to the information on this page, see also Common Use Cases.

Resource Classification

The following frameworks are provided for helping to understand the set of resources provided in this specification:


resourcelist-examples.html

Maturity Level: N/AStandards Status:Informative

Resource Examples

TODO: fill this page out.


resourcelist.html

Resource Index

Maturity Level: N/AStandards Status:Informative

This page is provided to help find resources quickly. There is also a more detailed classification, ontology, and description. For background to the layout on the layers in this page, see the Architect's Overview. See also tne abstract Base Resources Resource and DomainResource.

Foundation
Conformance Terminology Security Documents Other
Base
Individuals Entities Workflow Management
Clinical
Summary Diagnostics Medications Care Provision Request & Response
Financial
Support Billing Payment General
Specialized
Public Health & Research Definitional Artifacts Evidence-Based Medicine Quality Reporting & Testing Medication Definition
Alphabetical

A-C:

D-L:

M-P:

P-Z:

Clinical

General:

Care Provision:

Medication & Immunization:

Diagnostics:

Identification

Individuals:

Groups:

Entities:

Devices:

Workflow

Patient Management:

Scheduling:

Workflow #1:

Workflow #2:

Infrastructure

Information Tracking:

Documents & Lists:

Structure:

Exchange:

Conformance

Terminology:

Content:

Operations Control:

Misc:

Financial

Support:

Billing:

Payment:

Other:

Additional Resources will be added in the future. A list of hypothesized resources can be found on the HL7 Confluence. Feel free to add any you think are missing or engage with one of the HL7 Work Groups to submit a proposal to define a resource of particular interest.


resources-definitions.html

Maturity Level: NormativeStandards Status:Normative

Resource - Detailed Descriptions

Resource


resources-examples.html

Maturity Level: N/AStandards Status:Informative

Resource Format Examples

The specification includes many example resources. Most of the examples can be found in the examples section for each defined resource. In addition, there are some general examples of sets of resources:


rxnorm.html

Using RxNorm with FHIR

Maturity Level: 3Standards Status:Trial Use

Summary

SourceRxNorm is made available by the US National Library of Medicine at http://www.nlm.nih.gov/research/umls/rxnorm
SystemThe URI http://www.nlm.nih.gov/research/umls/rxnorm identifies the RxNorm code system
VersionWhere a version is used, it should be the date of release, encoded as in the download files, e.g. "07092014"
CodeThe code value for an RxNorm code is a Concept Identifier (CUI), and only CUIs for which there is an SAB=RXNORM
DisplayThe correct display for a CUI is the string description for it associated with the source RXNORM. Display values are not case sensitive
InactiveTodo: Describe how it is determined which concepts are inactive
SubsumptionNo Subsumption relationships are defined by RxNorm
Filter PropertiesSeveral properties are defined as described below

RxNorm MySQL Database

The RxNorm scripts are able to populate a MySQL database that contains the data from RxNorm. This page provides SQL statements that describe how to implement the features of the RxNorm terminology correctly against this database. These are provided for implementer convenience, and do not imply that any particular approach be used in implementations.

For example, the correct display name for a CUI is 'Select STR from rxnconso where RXCUI = :code and SAB = 'RXNORM' and TTY <> 'SY'.

Copyright/License Issues

Using RxNorm codes of type SAB=RXNORM as this specification describes does not require a UMLS license. Access to the full set of RxNorm definitions, and/or additional use of other RxNorm structures and information requires a UMLS license. The use of RxNorm in this specification is pursuant to HL7's status as a licensee of the NLM UMLS. HL7's license does not convey the right to use RxNorm to any users of this specification; implementers must acquire a license to use RxNorm in their own right.

RxNorm Filter Properties

This section documents the property filters that can be used with the RxNorm code system in value set composition statements.

The base SQL statement for returning a list of CUIs that conform to these filters is:

  Select RXCUI from rxnconso where SAB = 'RXNORM' and TTY <> 'SY' 

Semantic Type

DescriptionAllows for the selection of a set of CUIs based on their Semantic Type
Property NameSTY
Operations Allowed= / in
Values Allowed[column:]value
CommentsIf not column is specified, the default column is TUI
SQL
and RXCUI in (select RXCUI from rxnsty where [:column] = :value)

Source

DescriptionAllows for the selection of a set of concepts that have mappings to a particular RxNorm concept
Property NameSAB
Operations Allowed= / in
Values AllowedValues from RxNorm SAB table (e.g. select RSAB from rxnsab)
SQL
and RXCUI in (select RXCUI from rxnconso where SAB = :value)

Term Type

DescriptionAllows for the selection of a concept based on its designated type
Property NameTTY
Operations Allowed= / in
Values AllowedTTY values from the RxNorm Concept table (e.g. select distinct TTY from rxnconso)
SQL
and TTY = :value

Relationship

DescriptionAllows for the selection of a concept based on its relationships
Property Name[REL]
Operations Allowed= / in
Values AllowedCUI:[RXCUI] or AUI:[RXAUI] must be a valid CUI or AUI. Note that a CUI does not need to have an SAB=RXNORM entry to be used here
Comments[REL] (:rel) is one of SY, SIB, RN, PAR, CHD, RB or RO
SQL for CUI:
and (RXCUI in (select RXCUI from rxnconso where RXCUI in (select RXCUI1 from rxnrel where REL = :rel and RXCUI2 = :value))
for AUI:
and (RXCUI in (select RXCUI from rxnconso where RXAUI in (select RXAUI1 from rxnrel where REL = :rel and RXAUI2 = :value))

Relationship Type

DescriptionAllows for the selection of a concept based on the type of its relationships
Property Name[RELA]
Operations Allowed= / in
Values AllowedCUI:[RXCUI] or AUI:[RXAUI] must be a valid CUI or AUI. Note that a CUI does not need to have an SAB=RXNORM entry to be used here
Comments[RELA] (:rela) is one of the relationship types defined in RxNorm Appendix 1 (the "RELA" column)
SQL for CUI:
and (RXCUI in (select RXCUI from rxnconso where RXCUI in (select RXCUI1 from rxnrel where RELA = :rel and RXCUI2 = :value))
for AUI:
and (RXCUI in (select RXCUI from rxnconso where RXAUI in (select RXAUI1 from rxnrel where RELA = :rel and RXAUI2 = :value))

RxNorm Properties

In addition to the standard properties, the following properties are defined for RxNorm:

(Yet to be done).

Implicit Value Sets

Implicit value sets are those whose specification can be predicted based on the grammar of the underlying code system, and the known structure of the URL that refers to them. At the time of this publication, RxNorm does not define implicit value sets.

The identifier http://www.nlm.nih.gov/research/umls/rxnorm/vs represents a value set that contains all RxNorm CUIs.


safety.html

Clinical Safety

Maturity Level: N/AStandards Status:Informative

This specification defines data elements, resources, formats, methods and APIs for exchanging healthcare data between different participants in the healthcare process. As such, Clinical Safety is a key concern with regard to the specification and its many and various implementations.

This page, and the concept of safety in an API specification, needs further development.

Feedback is welcome here.

Implementer's Safety Check List

FHIR is as simple to implement as we know how to make it. However, due to the nature of healthcare, and healthcare processes, and cultural concerns, there are a number of features in FHIR that implementers are obliged to consider in order to implement safe systems.

This section is a check list to help implementers be sure that they've considered all the parts of FHIR that impact on their system design with regard to safety.

  1. Production exchange of patient or other sensitive data will always use some form of encryption on the wire
  2. For each resource that my system handles, I've reviewed the Modifier elements
  3. My system checks for modifierExtension elements
  4. My system supports elements labeled as "MustSupport" in the profiles that apply to my system
  5. All resources in use are valid against the base specification and the profiles that apply to my system (see note about the correct run-time use of validation)
  6. For each resource that my system handles, my system handles the full Life cycle (status codes, currency issues, and erroneous entry status)
  7. Deleting Records
    1. For each resource, I have checked whether resources can be deleted, and/or how records are marked as incorrect/no longer relevant
    2. Deletion of records (or equivalent updates in status) flow through the system so any replicated copies are deleted/updated
    3. (If a server) my documentation about deleted resources is clear, and my test sandbox (if exists) has deleted/error record cases in the test data
  8. My system can render narratives properly and securely(where they are used)
  9. My system has documented how distributed resource identification works in its relevant contexts of use, and where (and why) contained resources are used
  10. My system manages lists of current resources correctly
  11. My system makes the right Provenance statements and AuditEvent logs, and uses the right security labels where appropriate
  12. My system checks that the right Patient consent has been granted (where applicable)
  13. When other systems return http errors from the RESTful API and Operations (perhaps using Operation Outcome), my system checks for them and handles them appropriately
  14. Search (For clients)
    1. My system will display warnings returned by the server to the user
    2. My system checks whether the server processed all the requested search parameter, and is safe if servers ignore parameters (typically, either filters locally or warns the user)
  15. Search (For Servers)
    1. My system caters for parameters that have missing values when doing search operations, and responds correctly to the client with regard to erroneous search parameters
    2. My system includes appropriate default filters when searching based on patient context - e.g. filtering out entered-in-error records, filtering to only include active, living patients if appropriate, and clearly documents these (preferably including them in the self link for a search
  16. My system ensures that system clocks are synchronized using a protocol like NTP or SNTP, or my server is robust against clients that have the wrong clock set
  17. My system ensures checks for patient links (and/or merges) and handles data that is linked to patients accordingly
  18. My system publishes a Capability Statement with StructureDefinitions, ValueSets, and OperationDefinitions, etc., so other implementers know how the system functions
  19. My system checks for timezones, and adjusts times appropriately. (note: timezones are extremely difficult to get correct - see W3C Timezone Advice, and note that some fields should be timezone corrected, and others should not be)
  20. My system renders dates safely for changes in culture and language (the date formats D-M-Y and M-D-Y are not differentiated for many dates, and this is a well known source of confusion. Systems should use the month name, or otherwise be specific for each date when rendering, unless there is solid confidence that such confusion cannot arise, even in the future when information/narrative from resources will be shared much more widely)
  21. I've reviewed the Observation resource, and understand how focus is a mechanism for observations to be about someone or something other than the patient or subject of record.
  22. My system takes care to ensure that clients can (for servers) or will (for clients) find the information they need when content that might reasonably be exposed using more than one FHIR resource. Possible patterns: Support a single search across the applicable resources, or expose data through each applicable resource. See discussion on Wiki Page for further information

Obviously this list is only a small part of the overall safety check list for an application, which will have checks regarding jurisdictionally mandated policies, internal integrity, etc.

In addition, server developers should check these specific additional checks for client convenience:

  1. Server: CORS (cross-origin resource sharing) is appropriately enabled (many clients are Javascript apps running in a browser)
  2. JSON is supported (many clients are Javascript apps running in a browser; XML is inconvenient at best)
  3. JSON is returned correctly when errors happen (clients often don't handle HTML errors well)
  4. The _format header is supported correctly
  5. Errors are trapped and an OperationOutcome returned

sc.html

FHIR Status Codes Grid

FHIR Infrastructure Work GroupMaturity Level: N/AStandards Status: Informative

This is an internal QA page. The intent of this table is to help reviewers compare the mappings between the general resource status codes and the status codes on particular resources.

Note: This page is not proscriptive; it's descriptive and comparative, to assist with review. The FHIR methodology says that if two domains use different terms for the same concept (e.g. 'withdrawn' and 'cancelled') then the domain concept name should be used. Conversely, where there is no explicit reason for the codes to differ based on domain usage, they should not.

All status codes must be mapped to one of the general status codes, which are found in the Resource Status code system.

Note: Bold indicates that the element is marked as a modifier.


search.html

Search

Maturity Level: NormativeStandards Status:Normative

Searching for resources is fundamental to the mechanics of FHIR. Search operations traverse through an existing set of resources filtering by parameters supplied to the search operation. The text below describes the FHIR search framework, starting with simple cases moving to the more complex. Implementers need only implement the amount of complexity that they require for their implementations.

Summary Table

Search Parameter TypesParameters for all resourcesSearch result parameters
_id
_lastUpdated
_tag
_profile
_security
_text
_content
_list
_has
_type
_sort
_count
_include
_revinclude
_summary
_total
_elements
_contained
_containedType

In addition, there is a special search parameters _query and _filter that allow for an alternative method of searching, and the parameters _format and _pretty defined for all interactions.

Also, there is a single page that lists all the search parameters. Note that search parameter names are case sensitive, though this specification never defines different parameters with names that differ only in case. Clients SHOULD use correct case, and servers SHALL not define additional parameters with different meanings with names that only differ in case.

There are several safety issues associated with the implementation of searching that implementers should always keep in mind.

Introduction

In the simplest case, a search is executed by performing a GET operation in the RESTful framework:

 GET [base]/[type]?name=value&...{&_format=[mime-type]}}

For this RESTful search (see definition in RESTful API), the parameters are a series of name=[value] pairs encoded in the URL or as an application/x-www-form-urlencoded submission for a POST:

 POST  [base]/[type]/_search{?[parameters]{&_format=[mime-type]}}

The server determines which of the set of resources it serves meet the specific criteria, and returns the results in the HTTP response as a bundle which includes the resources that are the results of the search. Note that the _format parameter works for search like for other interactions.

Search operations are executed in one of three defined contexts that control which set of resources are being searched:

Search operations can also be implemented in the messaging framework.

The server determines which of their resources meet the criteria contained in the search parameters as described below. However the server has the prerogative to return additional search results if it believes them to be relevant. Note: There is a special search for the most relevant context in which the search set is indeterminate: Patient MPI Search.

Search using GET may include sensitive information in the search parameters. Therefore, secure communications and endpoint management are recommended, see Security Communications

The response to any search operation is always a list of resources in a Bundle. An alternative approach is to use GraphQL.

Handling Errors

If a server is unable to execute a search request, it may return an error. A HTTP status code of 403 signifies that the server refused to perform the search, while other 4xx and 5xx codes signify that some sort of error has occurred. When the search fails, a server SHOULD return an OperationOutcome detailing the cause of the failure. Note: An empty search result is not a failure.

In some cases, parameters may cause an error, or might not be able to match anything. For instance:

Note: Empty parameters are not an error - they are just ignored by the server.

Where the content of the parameter is syntactically incorrect, servers SHOULD return an error. However, where the issue is a logical condition (e.g. unknown subject or code), the server SHOULD process the search, including processing the parameter - with the result of returning an empty search set, since the parameter cannot be satisfied.

In such cases, the search process MAY include an OperationOutcome in the search set that contains additional hints and warnings about the search process. This is included in the search results as an entry with search mode = outcome. Clients can use this information to improve future searches. If, for example, a client performed the following search:

GET [base]/Observation?patient.identifier=http://example.com/fhir/identifier/mrn|123456

and there is no patient for MRN 123456, the server would return a bundle with a warning.

Unknown and unsupported parameters

Servers may receive parameters from the client that they do not recognize, or may receive parameters they recognize but do not support (either in general, or for a specific search). In general, servers SHOULD ignore unknown or unsupported parameters for the following reasons:

Clients can specify how the server should behave, by using the prefer header

Servers SHOULD honor the client's request, but are not required to do so.

Standard Parameters

Parameters for all resources

The following parameters apply to all resources:. In addition, the search parameter _text and _filter, (documented below) also applies to all resources (as do the search result parameters).

The search parameter _id refers to the logical id of the resource, and can be used when the search context specifies a resource type:

 GET [base]/Patient?_id=23

This search finds the patient resource with the given id (there can only be one resource for a given id). Functionally, this is equivalent to a simple read operation:

 GET [base]/Patient/23

However, the search with parameter _id returns a bundle with the requested resource, instead of just the resource itself. Additional parameters can be added which may provide additional functionality on top of this base read equivalence (e.g. _include). Note that although the _id parameter has a type of token, because servers SHALL use exact match with it, there is no system for the _id parameter. Note that matches on _id are always case sensitive.

The search parameter _lastUpdated can be used to select resources based on the last time they were changed:

 GET [base]/Observation?_lastUpdated=gt2010-10-01

This search finds any observations changed since 1-Oct 2010. When this search parameter is used, applications should consider synchronization approaches (RESTful history or the Subscription resource).

The search parameters _tag, _profile and _security parameters search on the equivalent elements in the meta element. For example,

 GET [base]/Condition?_tag=http://acme.org/codes|needs-review

searches for all Condition resources with the tag:

{
  "system" : "http://acme.org/codes",
  "code" : "needs-review"
}

In the same manner:

 GET [base]/DiagnosticReport?_profile=http://hl7.org/fhir/StructureDefinition/lipid
 GET [base]/DiagnosticReport?_profile=Profile/lipid

restricts the search to only DiagnosticReport resources that are tagged as conforming to a particular profile. The second reference is relative, and refers a local profile on the same server.

_tag, and _security parameters are token types (see below), and _profile is a reference search parameter.

Parameters for each resource

In addition to the _id parameter which exists for all resources, each FHIR resource type defines its own set of search parameters with their names, types, and meanings. These search parameters are on the same page as the resource definitions, and are also published as part of the standard Capability statement (XML or JSON).

In general, the defined search parameters correspond to a single element in the resource, but this is not required, and some search parameters refer to the same type of element in multiple places, or refer to derived values.

Some search parameters defined by resources are associated with more than one path in a resource. This means that the search parameter matches if any of the paths contain matching content. If a path matches, the whole resource is returned in the search results. The client may have to examine the resource to determine which path contains the match.

Servers are not required to implement any of the standard search parameters (except for the _id parameter described above), and may define their own parameters.

Search Parameter Types

Each search parameter is defined by a type that specifies how the search parameter behaves. These are the defined parameter types:

The search parameters can also append "modifiers" that control their behavior. The kinds of modifiers that available is dependent on the type of parameter being modified.

Modifiers

Parameters are defined per resource. Parameter names may specify a modifier as a suffix. The modifiers are separated from the parameter name by a colon. Modifiers are:

Server SHALL reject any search request that contains is suffixed by a modifier that the server does not support for that parameter. For example, if the server supports the name search param, but not the :exact modifier on the name, it should reject a search with the parameter name:exact=Bill, using an HTTP 400 error with an OperationOutcome with a clear error message.

Prefixes

For the ordered parameter types of number, date, and quantity, a prefix to the parameter value may be used to control the nature of the matching. To avoid URL escaping and visual confusion, the following prefixes are used:

eq the value for the parameter in the resource is equal to the provided value the range of the search value fully contains the range of the target value
ne the value for the parameter in the resource is not equal to the provided value the range of the search value does not fully contain the range of the target value
gt the value for the parameter in the resource is greater than the provided value the range above the search value intersects (i.e. overlaps) with the range of the target value
lt the value for the parameter in the resource is less than the provided value the range below the search value intersects (i.e. overlaps) with the range of the target value
ge the value for the parameter in the resource is greater or equal to the provided value the range above the search value intersects (i.e. overlaps) with the range of the target value, or the range of the search value fully contains the range of the target value
le the value for the parameter in the resource is less or equal to the provided value the range below the search value intersects (i.e. overlaps) with the range of the target value or the range of the search value fully contains the range of the target value
sa the value for the parameter in the resource starts after the provided value the range of the search value does not overlap with the range of the target value, and the range above the search value contains the range of the target value
eb the value for the parameter in the resource ends before the provided value the range of the search value does overlap not with the range of the target value, and the range below the search value contains the range of the target value
ap the value for the parameter in the resource is approximately the same to the provided value.
Note that the recommended value for the approximation is 10% of the stated value (or for a date, 10% of the gap between now and the date), but systems may choose other values where appropriate
the range of the search value overlaps with the range of the target value

If no prefix is present, the prefix eq is assumed. Note that the way search parameters operate is not the same as the way the operations on two numbers work in a mathematical sense. sa (starts-after) and eb (ends-before) are not used with integer values but are used for decimals.

For each prefix above, two interpretations are provided - the simple intent of the prefix and the interpretation of the parameter when applied to ranges. The range interpretation is provided for decimals and dates. Searches are always performed on values that are implicitly or explicitly a range. For instance, the number 2.0 has an implicit range of 1.95 to 2.05, and the date 2015-08-12 has an implicit range of all the time during that day. If the target value is a Range, a Period, or a Timing, then the target is explicitly a range. Three ranges are identified:

range of the value The limits implied by the precision of the value The number 2.0 has a range of 1.95 to 2.05
The date 2015-08-12 has a range from 00:00 to 00:00 exclusive
range below the value Up to the specified value The range below 2.0 includes any value less or equal to <2.00000000000000000000
The range before 2015-08-12T05:23:45 includes any time up to 2015-08-12T05:23:45.000000000000000
range above the value The specified value and up The range above 2.0 includes any value greater or equal to <2.00000000000000000000
The range after 2015-08-12T05:23:45 includes any time after 2015-08-12T05:23:45.000000000000000

The proper use of these ranges is discussed further below.

number

Searching on a simple numerical value in a resource. Examples:

[parameter]=100Values that equal 100, to 3 significant figures precision, so this is actually searching for values in the range [99.5 ... 100.5)
[parameter]=100.00Values that equal 100, to 5 significant figures precision, so this is actually searching for values in the range [99.995 ... 100.005)
[parameter]=1e2Values that equal 100, to 1 significant figures precision, so this is actually searching for values in the range [95 ... 105)
[parameter]=lt100Values that are less than exactly 100
[parameter]=le100Values that are less or equal to exactly 100
[parameter]=gt100Values that are greater than exactly 100
[parameter]=ge100Values that are greater or equal to exactly 100
[parameter]=ne100Values that are not equal to 100 (actually, in the range 99.5 to 100.5)

Notes about searching on Numbers:

Here are some example searches:

SearchDescription
 GET [base]/RiskAssessment?probability=gt0.8
Search for all the Risk Assessments wth probability great than 0.8 (could also be probability=gt8e-1 using exponential form)
 GET [base]/ImmunizationRecommendation?dose-number=2
Search for any immunization recommendation recommending a second dose

date

A date parameter searches on a date/time or period. As is usual for date/time related functionality, while the concepts are relatively straight-forward, there are a number of subtleties involved in ensuring consistent behavior.

The date parameter format is yyyy-mm-ddThh:mm:ss[Z|(+|-)hh:mm] (the standard XML format).

Technically, this is any of the date, dateTime, and instant data types; e.g. Any degree of precision can be provided, but it SHALL be populated from the left (e.g. can't specify a month without a year), except that the minutes SHALL be present if an hour is present, and you SHOULD provide a time zone if the time part is present. Note: Time can consist of hours and minutes with no seconds, unlike the XML Schema dateTime type. Some user agents may escape the : characters in the URL, and servers SHALL handle this correctly.

Date parameters may be used with the following data types:

dateThe range of the value is the day, month, or year as specified
dateTimeThe range of the value as defined above; e.g. For example, the date 2013-01-10 specifies all the time from 00:00 on 10-Jan 2013 to immediately before 00:00 on 11-Jan 2013
instantAn instant is considered a fixed point in time with an interval smaller than the precision of the system, i.e. an interval with an effective width of 0
PeriodExplicit, though the upper or lower bound might not actually be specified in resources.
Timingthe specified scheduling details are ignored and only the outer limits matter. For instance, a schedule that specifies every second day between 31-Jan 2013 and 24-Mar 2013 includes 1-Feb 2013, even though that is on an odd day that is not specified by the period. This is to keep the server load processing queries reasonable.

Implicitly, a missing lower boundary is "less than" any actual date. A missing upper boundary is "greater than" any actual date. The use of the prefixes:

[parameter]=eq2013-01-14
  • 2013-01-14T00:00 matches (obviously)
  • 2013-01-14T10:00 matches
  • 2013-01-15T00:00 does not match - it's not in the range
[parameter]=ne2013-01-14
  • 2013-01-15T00:00 matches - it's not in the range
  • 2013-01-14T00:00 does not match - it's in the range
  • 2013-01-14T10:00 does not match - it's in the range
[parameter]=lt2013-01-14T10:00
  • 2013-01-14 matches, because it includes the part of 14-Jan 2013 before 10am
[parameter]=gt2013-01-14T10:00
  • 2013-01-14 matches, because it includes the part of 14-Jan 2013 after 10am
[parameter]=ge2013-03-14
  • "from 21-Jan 2013 onwards" is included because that period may include times after 14-Mar 2013
[parameter]=le2013-03-14
  • "from 21-Jan 2013 onwards" is included because that period may include times before 14-Mar 2013
[parameter]=sa2013-03-14
  • "from 15-Mar 2013 onwards" is included because that period starts after 14-Mar 2013
  • "from 21-Jan 2013 onwards" is not included because that period starts before 14-Mar 2013
  • "before and including 21-Jan 2013" is not included because that period starts (and ends) before 14-Mar 2013
[parameter]=eb2013-03-14
  • "from 15-Mar 2013 onwards" is not included because that period starts after 14-Mar 2013
  • "from 21-Jan 2013 onwards" is not included because that period starts before 14-Mar 2013, but does not end before it
  • "before and including 21-Jan 2013" is included because that period ends before 14-Mar 2013
[parameter]=ap2013-03-14
  • 14-Mar 2013 is included - as it exactly matches
  • 21-Jan 2013 is not included because that is near 14-Mar 2013
  • 15-Jun 2015 is not included - as it is not near 14-Mar 2013. Note that the exact value here is at the discretion of the system

Other notes:

To search for all the procedures in a patient compartment that occurred over a 2 year period:

 GET [base]/Patient/23/Procedure?date=ge2010-01-01&date=le2011-12-31

Managing timezones and offsets and their impact on search is a very difficult area. The FHIR implementation community is still investigating and debating the best way to handle timezones. Implementation guides may make additional rules in this regard.

Future versions of this specification may impose rules around the use of timezones with dates. Implementers and authors of implementation guides should be aware of ongoing work in this area.

Implementer feedback is welcome on the issue tracker or chat.fhir.org.

string

For a simple string search, a string parameter serves as the input for a search against sequences of characters. This search is insensitive to casing and included combining characters, like accents or other diacritical marks. Punctuation and non-significant whitespace (e.g. repeated space characters, tab vs space) should also be ignored. By default, a field matches a string query if the value of the field equals or starts with the supplied parameter value, after both have been normalized by case and combining characters. Therefore, the default string search only operates on the base characters of the string parameter. The :contains modifier returns results that include the supplied parameter value anywhere within the field being searched. The :exact modifier returns results that match the entire supplied parameter, including casing and accents.

Examples:

[base]/Patient?given=eveAny patients with a name containing a given part with "eve" at the start of the name. This would include patients with the given name "Eve", "Evelyn".
[base]/Patient?given:contains=eveAny patients with a name with a given part containing "eve" at any position. This would include patients with the given name "Eve", "Evelyn", and also "Severine".
[base]/Patient?given:exact=EveAny patients with a name with a given part that is exactly "Eve". Note: This would not include patients with the given name "eve" or "EVE".

An additional modifier :text can be used to specify a search with advanced text handling (see below) though only a few servers are expected to offer this facility.

When a string search parameter refers to the types HumanName and Address, the search covers the elements of type string, and does not cover elements such as use and period. For robust search, servers should search the parts of a family name independently. E.g. Searching either Carreno or Quinones should match a family name of "Carreno Quinones". HL7 affiliates may make more specific recommendations about how search should work in their specific culture.

It is at the discretion of the server whether to pre-process names, addresses, and contact details to remove separator characters prior to matching in order to ensure more consistent behavior. For example, a server might remove all spaces and - characters from phone numbers. What is most appropriate varies depending on culture and context. A server may also use a free-text style searches on this property to achieve the best results When searching whole names and addresses (not parts), servers may also use flexible match or a free-text style searches on names to achieve the best results.

uri

The uri parameter refers to an element that contains a URI (RFC 3986). By default, matches are precise (e.g. case, accent, and escape) sensitive, and the entire URI must match. The modifier :above or :below can be used to indicate that partial matching is used. For example:

 GET [base]/ValueSet?url=http://acme.org/fhir/ValueSet/123
 GET [base]/ValueSet?url:below=http://acme.org/fhir/
 GET [base]/ValueSet?url:above=http://acme.org/fhir/ValueSet/123/_history/5
 GET [base]/ValueSet?url=urn:oid:1.2.3.4.5

The search type uri is used with elements of type uri and url. The type reference is used for the types Reference and canonical. Note that for uri parameters that refer to the Canonical URLs of the conformance and knowledge resources (e.g. StructureDefinition, ValueSet, PlanDefinition etc), servers SHOULD support searching by canonical references, and SHOULD support automatically detecting a |[version] portion as part of the search parameter, and interpreting that portion as a search on the version.

token

A token type is a parameter that provides a close to exact match search on a string of characters, potentially scoped by a URI. It is mostly used against a code or identifier data type where the value may have a URI that scopes its meaning, where the search is performed against the pair from a Coding or an Identifier. Tokens are also used against other fields where exact matches are required - uris, booleans, and ContactPoints. In these cases, the URI portion is not used.

For tokens, matches are literal (e.g. not based on subsumption or other code system features). Match is case sensitive unless the underlying semantics for the context indicate that the token should be interpreted case-insensitively (see, e.g. CodeSystem.caseSensitive). Note that matches on _id are always case sensitive. If the underlying data type is string then the search is not case sensitive.

Note: There are many challenging issues around case senstivity and token searches. Some code systems are case sensitive (e.g. UCUM) while others are known not to be. For many code systems, it's ambiguous. Other kinds of values are also ambiguous. When in doubt, servers SHOULD treat tokens in a case-insensitive manner, on the grounds that including undesired data has less safety implications than excluding desired behavior. Clients SHOULD always use the correct case when possible, and allow for the server to perform case-insensitive matching.

To use subsumption based logic, use the modifiers below, or list all the codes in the hierarchy. The syntax for the value is one of the following:

Notes:

Token search parameters are used for the following data types:

Data Type URI Code Comments
Coding Coding.system Coding.code
CodeableConcept CodeableConcept.coding.system CodeableConcept.coding.code Matches against any coding in the CodeableConcept
Identifier Identifier.system Identifier.value Clients can search by type not system using the :of-type modifier, see below. To search on a CDA II.root - which may appear in either Identifier.system or Identifier.value, use the syntax identifier=|[root],[root]
ContactPoint ContactPoint.value At the discretion of the server, token searches on ContactPoint may use special handling, such as ignoring punctuation, performing partial searches etc.
code (implicit) code the system is defined in the value set (though it's not usually needed)
boolean boolean The implicit system for boolean values is http://hl7.org/fhir/special-values but this is never actually used
uri uri
string n/a string Token is sometimes used for string to indicate that exact matching is the correct default search stategy

Note: The use of token search parameters for boolean fields: the boolean values "true" and "false" are also represented as formal codes in the Special Values code system, which is useful when boolean values need to be represented in a Coding data type. The namespace for these codes is http://hl7.org/fhir/special-values, though there is usually no reason to use this, as a simple true or false is sufficient.

Modifiers:

Modifier Use
:text The search parameter is processed as a string that searches text associated with the code/value - either CodeableConcept.text, Coding.display, or Identifier.type.text. In this case, the search functions as a normal string search
:not Reverse the code matching described in the paragraph above: return all resources that do not have a matching item. Note that this includes resources that have no value for the parameter - e.g. ?gender:not=male includes all patients that do not have gender = male, including patients that do not have a gender at all
:above The search parameter is a concept with the form [system]|[code], and the search parameter tests whether the coding in a resource subsumes the specified search code. For example, the search concept has an is-a relationship with the coding in the resource, and this includes the coding itself.
:below the search parameter is a concept with the form [system]|[code], and the search parameter tests whether the coding in a resource is subsumed by the specified search code. For example, the coding in the resource has an is-a relationship with the search concept, and this includes the coding itself.
:in The search parameter is a URI (relative or absolute) that identifies a value set, and the search parameter tests whether the coding is in the specified value set. The reference may be literal (to an address where the value set can be found) or logical (a reference to ValueSet.url). If the server can treat the reference as a literal URL, it does, else it tries to match known logical ValueSet.url values.
:not-in The search parameter is a URI (relative or absolute) that identifies a value set, and the search parameter tests whether the coding is not in the specified value set.
:of-type The search parameter has the format system|code|value, where the system and code refer to a Identifier.type.coding.system and .code, and match if any of the type codes match. All 3 parts must be present

Most servers will only process value sets that are already known/registered/supported internally. However, servers can elect to accept any valid reference to a value set. Servers may elect to consider concept mappings when testing for subsumption relationships.

Example searches:

SearchDescription
 GET [base]/Patient?identifier=http://acme.org/patient|2345
Search for all the patients with an identifier with key = "2345" in the system "http://acme.org/patient"
 GET [base]/Patient?gender=male
Search for any patient with a gender that has the code "male"
 GET [base]/Patient?gender:not=male
Search for any patient with a gender that does not have the code "male". Note that for :not, the search does not return any resources that have a gen
 GET [base]/Composition?section=48765-2
Search for any Composition that contains an Allergies and adverse reaction section
 GET [base]/Composition?section:not=48765-2
Search for any Composition that does not contain an Allergies and adverse reaction section. Note that this search does not return "any document that has a section that is not an Allergies and adverse reaction section" (e.g. in the presence of multiple possible matches, the negation applies to the set, not each individual entry)
 GET [base]/Patient?active=true
Search for any patients that are active
 GET [base]/Condition?code=http://acme.org/conditions/codes|ha125
Search for any condition with a code "ha125" in the code system "http://acme.org/conditions/codes"
 GET [base]/Condition?code=ha125
Search for any condition with a code "ha125". Note that there is not often any useful overlap in literal symbols between code systems, so the previous example is generally preferred
 GET [base]/Condition?code:text=headache
Search for any Condition with a code that has a text "headache" associated with it (either in the text, or a display)
 GET [base]/Condition?code:in=http%3A%2F%2Fsnomed.info%2Fsct%3Ffhir_vs%3Disa%2F126851005
Search for any condition in the SNOMED CT value set "http://snomed.info/sct?fhir_vs=isa/126851005" that includes all descendants of "Neoplasm of liver"
 GET [base]/Condition?code:below=126851005
Search for any condition that is subsumed by the SNOMED CT Code "Neoplasm of liver". Note: This is the same outcome as the previous search
 GET [base]/Condition?code:in=http://acme.org/fhir/ValueSet/cardiac-conditions
Search for any condition that is in the institutions list of cardiac conditions
 GET [base]/Patient?identifier:otype=http://terminology.hl7.org/CodeSystem/v2-0203|MR|446053
Search for the Medical Record Number 446053 - this is useful where the system id for the MRN is not known
Searching Mime Types

The :below modifier is also very useful with searching mime types, such as for DocumentReference.contenttype which refers to Attachment.contentType. A simple search such as:

GET [base]/DocumentReference?contenttype=text/xml

will miss documents with a mime type such as text/xml; charset=UTF-8. This search will find all text/xml documents:

GET [base]/DocumentReference?contenttype:below=text/xml

For ease of processing on the server, servers are only required to support :below on the base part of the mime type; servers are not required to sort between different parameters and do formal subsumption logic.

quantity

A quantity parameter searches on the Quantity data type. The syntax for the value follows the form:

The prefix is optional, and is as described above, both regarding how precision and comparator/range operators are interpreted. Like a number parameter, the number part of the search value can be a decimal in exponential format. The system and code follow the same pattern as token parameters are also optional. Example searches:

SearchDescription
 GET [base]/Observation?value-quantity=5.4|http://unitsofmeasure.org|mg
Search for all the observations with a value of 5.4(+/-0.05) mg where mg is understood as a UCUM unit (system/code)
 GET [base]/Observation?value-quantity=5.40e-3|http://unitsofmeasure.org|g
Search for all the observations with a value of 0.0054(+/-0.000005) g where g is understood as a UCUM unit (system/code)
 GET [base]/Observation?value-quantity=5.4||mg
Search for all the observations with a value of 5.4(+/-0.05) mg where the unit - either the code (code) or the stated human unit (unit) are "mg"
 GET [base]/Observation?value-quantity=5.4
Search for all the observations with a value of 5.4(+/-0.05) irrespective of the unit
 GET [base]/Observation?value-quantity=le5.4|http://unitsofmeasure.org|mg
Search for all the observations where the value of is less than 5.4 mg exactly where mg is understood as a UCUM unit
 GET [base]/Observation?value-quantity=ap5.4|http://unitsofmeasure.org|mg
Search for all the observations where the value of is about 5.4 mg where mg is understood as a UCUM unit (typically, within 10% of the value - see above)

Specifying a system and a code for the search implies that the search is based on a particular code system - usually UCUM, and that a precise (and potentially canonical) match is desired. In this case, it is inappropriate to search on the human display for the unit, which can be is uncontrolled and may unpredictable.

The search processor may choose to perform a search based on canonical units (e.g. any value where the units can be converted to a value in mg in the case above). For example, an observation may have a value of 23 mm/hr. This is equal to 0.23 m/hr. The search processer can choose to normalise all the values to a canonical unit such as 6.4e-6 m/sec, and convert search terms to the same units (m/sec). Such conversions can be performed based on the semantics defined in UCUM

reference

A reference parameter refers to references between resources. For example, find all Conditions where the subject reference is a particular patient, where the patient is selected by name or identifier. The interpretation of a reference parameter is either:

Note: A relative reference resolving to the same value as a specified absolute URL, or vice versa, qualifies as a match. For example, if the search parameter value is Patient/123, then this will find references like this:

 <patient>
   <reference value="Patient/123"/>
 </patient>

If the server base address is http://example.org/fhir, then the full URL for that reference is http://example.org/fhir/Patient/123, which means that the search term also matches patient references like this:

 <patient>
   <reference value="http://example.org/fhir/Patient/123"/>
 </patient>

In addition, searching for reference=http://example.org/fhir/Patient/123 will also match both references.

Some references are allowed to point to more than one type of resource; e.g. subject : Reference(Patient|Group|Device|..). In these cases, multiple resources may have the same logical identifier. Servers SHOULD reject a search where the logical id refers to more than one matching resource across different types. In order to allow the client to perform a search in these situations the type is specified explicitly:

 GET [base]/Observation?subject=Patient/23

This searches for any observations where the subject refers to the patient resource with the logical identifier "23". A modifier is also defined to to allow the client to be explicit about the intended type:

 GET [base]/Observation?subject:Patient=23

This has the same effect as the previous search. The modifier becomes useful when used with chaining as explained in the next section. Note: The [type] modifier can't be used with a reference to a resource found on another server, since the server would not usually know what type that resource has. However, since these are absolute references, there can be no ambiguity about the type.

In some cases, search parameters are defined with an implicitly limited scope. For example, Observation has an element subject, which is a reference to one of a number of types. This has a matching search parameter subject, which refers to any of the possible types. In addition to this, there is another search parameter patient, which also refers to Observation.subject, but is limited to only include references of type Patient. When using the patient search parameter, there is no need to specify ":Patient" as a modifier, or "Patient/" in the search value, as this must always be true.

References are also allowed to have an identifier. The modifier :identifier allows for searching by the identifier rather than the literal reference:

 GET [base]/Observation?subject:identifier=http://acme.org/fhir/identifier/mrn|123456

This is a search for all observations that reference a patient by a particular patient MRN. When the :identifier modifier is used, the search value works as a token search. The :identifier modifier is not supported on canonical elements since they do not have an identifier separate from the reference itself.

Chaining is not supported when using the :identifier modifier, nor are chaining, includes or reverse includes supported for reference elements that do not have a reference element.

The reference search parameter is mostly used for resource elements of type Reference or canonical. However, it is also be used to search resource elements of type Resource - i.e. where one resource is directly nested within another - see the Bundle search parameters 'message' and 'composition' as an example of this.

References and Versions

Elements of type Reference may contain a versioned reference:

   <evidence>
      <reference value="Observation/123/_history/234234"/>
  </evidence>

When searching on versioned references, the following rules apply:

Elements of type canonical may contain a version specific reference, but this version is different in both meaning and format to version specific references that might be found in a Reference:

   <valueSet value="http://hl7.org/fhir/ValueSet/example|3.0"/>

This version is a reference to the business version of the resource.

For canonical references, servers SHOULD support searching by Canonical URLs, and SHOULD support automatically detecting a |[version] portion as part of the search parameter, and interpreting that portion as a search on the business version of the target resource. The modifier :below is used with canonical references, to control whether the version is considered in the search. The search:

GET {base]/Observation?definition:below=http:http://acme.com/some-profile

matches all of these element values:

The search:

GET {base]/Observation?definition:below=http:http://acme.com/some-profile|1

matches the first two element values.

Searching Hierarchies

Some references are circular - that is, the reference points to another resource of the same type. When the reference establishes a strict hierarchy, the modifiers :above and :below may be used to search transitively through the hierarchy:

GET [base]/Procedure?location:below=42

This search returns no only all procedures that occurred at location with id 42, but also any procedures that occurred in locations that are part of location with id 42.

GET [base]/MedicationAdministration?encounter:above=21

Returns all medication administrations that happened during encounter with id 21 or during any "parent" encounter of that encounter.

Servers indicate that :above/:below is supported on a search parameter by defining them as Modifiers on the Search Parameter definition.

Chained parameters

In order to save a client from performing a series of search operations, reference parameters may be "chained" by appending them with a period (.) followed by the name of a search parameter defined for the target resource. This can be done recursively, following a logical path through a graph of related resources, separated by .. For instance, given that the resource DiagnosticReport has a search parameter named subject, which is usually a reference to a Patient resource, and the Patient resource includes a parameter name which searches on patient name, then the search

 GET [base]/DiagnosticReport?subject.name=peter

is a request to return all the lab reports that have a subject whose name includes "peter". Because the Diagnostic Report subject can be one of a set of different resources, it's necessary to limit the search to a particular type:

 GET [base]/DiagnosticReport?subject:Patient.name=peter

This request returns all the lab reports that have a subject which is a patient, whose name includes "peter".

Note that chained parameters are applied independently to the target resource. For example,

GET Patient?general-practitioner.name=Joe&general-practitioner.address-state=MN

may return Patients cared for by Joe from CA and Jane from MN: no one practitioner need satisfy both conditions. E.g. the chains are evaluated separately. For use cases where the joins must be evaluated in groups, there are either Composite search parameters, or the _filter parameter.

Advanced Search Note: Where a chained parameter searches a resource reference that may have more than one type of resource as its target, the parameter chain may end up referring to search parameters with the same name on more than one kind of resource at once. Servers SHOULD reject a search where the logical id refers to more than one matching resource across different types. For example, the client has to specify the type explicitly using the syntax in the second example above.

Reverse Chaining

The _has parameter provides limited support for reverse chaining - that is, selecting resources based on the properties of resources that refer to them (instead of chaining, above, where resources can be selected based on the properties of resources that they refer to). Here is an example of the _has parameter:

GET [base]/Patient?_has:Observation:patient:code=1234-5

This requests the server to return Patient resources, where the patient resource is referred to by at least one Observation where the observation has a code of 1234, and where the Observation refers to the patient resource in the patient search parameter.

"Or" searches are allowed (e.g. GET [base]/Patient?_has:Observation:patient:code=123,456), and multiple _has parameters are allowed (e.g. GET [base]/Patient?_has:Observation:patient:code=123&_has:Observation:patient:code=456). Note that each _has parameter is processed independently of other _has parameters.

The _has parameter can be chained, like this:

GET [base]/Patient?_has:Observation:patient:_has:AuditEvent:entity:user=MyUserId

Fetch all the patients that have an Observation where the observation has an audit event from a specific user.

Composite Search Parameters

Composite search parameters support joining single values with a $. For example, the result of the search operation is the intersection of the resources that match the criteria specified by each individual search parameter. If a parameter repeats, such as /Patient?language=FR&language=NL, then this matches a patient who speaks both languages. This is known as an AND search parameter, since the server is expected to respond only with results which match both values.

If, instead, the search is to find patients that speak either language, then this is a single parameter with multiple values, separated by a ,. For example, /Patient?language=FR,NL. This is known as an OR search parameter, since the server is expected to respond with results which match either value. Every search parameter may be used with comma-separated values in this fashion; this includes the use of search parameters with modifiers, such as `?code:text=this,that.

AND parameters and OR parameters may also be combined, for example: /Patient?language=FR,NL&language=EN would refer to any patient who speaks English, as well as either French or Dutch.

This approach allows for simple combinations of and/or values, but doesn't allow a search based on a pair of values, such as all observations with a sodium value >150 mmol/L (particularly as the end criteria of a chained search), or searching on Group.characteristic where you need find a combination of key/value, not an intersection of separate matches on key and value. Another example is spatial coordinates when doing geographical searches.

To allow these searches, a resource may also specify composite parameters that take sequences of single values that match other defined parameters as an argument. The matching parameter of each component in such a sequence is documented in the definition of the parameter. These sequences are formed by joining the single values with a $. Note: This sequence is a single value and itself can be composed into a set of values, so that, for example, multiple matching characteristic-value parameters can be specified as GET [base]/Group?characteristic-value=gender$mixed,owner$Eve.

Note: Modifiers are not used on composite parameters.

Examples of using composite parameters:

SearchDescription
 GET [base]/DiagnosticReport?result.code-value-quantity=http://loinc.org|2823-3$gt5.4|http://unitsofmeasure.org|mmol/L
Search for all diagnostic reports that contain on observation with a potassium value of >5.4 mmol/L (UCUM)
 GET [base]/Observation?component-code-value-quantity=http://loinc.org|8480-6$lt60
Search for all the observations with a systolic blood pressure < 60. Note that in this case, the unit is assumed (everyone uses mmHg)
 GET [base]/Group?characteristic-value=gender$mixed
Search for all groups that have a characteristic "gender" with a text value of "mixed"
 GET [base]/Questionnaire?context-type-value=focus$http://snomed.info/sct|408934002
Search for all questionnaires that have a cliical focus = "Substance abuse prevention assessment (procedure)"

Handling Missing Data

Consider the case of searching for all AllergyIntolerance resources:

GET [base]/AllergyIntolerance?clinical-status=http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical|active

This search will only return resources that have a value for clinicalStatus:

{
  "resourceType" : "AllergyIntolerance",
   "clinicalStatus": {
    "coding": [
      {
        "system": "http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical",
        "code": "active"
      }
    ]
  }
}

Resources missing a clinicalStatus will not be returned. This is probably unsafe - it would not usually be appropriate to ignore AllergyIntolerance warnings with an unknown clinical status, and only return resources with an explicit clinicalStatus. Instead, it might be desired to return AllergyIntolerance resources with either an explicit value for clinicalStatus, or none:

GET [base]/AllergyIntolerance?clinical-status=http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical|active
GET [base]/AllergyIntolerance?clinical-status:missing=true

Note that this is 2 separate queries. They can be combined in a batch, but not in a single operation. This query will always return an empty list, as no resource can satisfy both criteria at once:

GET [base]/AllergyIntolerance?clinical-status=http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical|active&clinical-status:missing=true

There is no way to use the :missing modifier and mix with a value using the comma syntax documented above for composite search parameters.

An alternative approach is to use the _filter parameter, for servers that support this parameter.

Escaping Search Parameters

In the rules described above, special rules are defined for the characters $, ,, and |. As a consequence, if these characters appear in an actual parameter value, they must be differentiated from their use as separator characters. When any of these characters appear in an actual parameter value, they must be prepended by the character \, which also must be used to prepend itself. Therefore, param=xxx$xxx indicates that it is a composite parameter, while param=xx\$xx indicates that the parameter has the literal value xx$xx. The parameter value xx\xx is illegal, and the parameter value param=xx\\xx indicates a literal value of xx\xx. This means that:

GET [base]/Observation?code=a,b

is a request for any Observation that has a code of either a or b, where as:

GET [base]/Observation?code=a\,b

is a request for any Observation that has a code of a,b.

This escaping is at a different level to the % encoding that applies to all URL parameters. Standard % escaping still applies, such that these URLs have the same meaning:

GET [base]/ValueSet?url=http://acme.org/fhir/ValueSet/123,http://acme.org/fhir/ValueSet/124,125
GET [base]/ValueSet?url=http://acme.org/fhir/ValueSet/123,http://acme.org/fhir/ValueSet/124%2CValueSet/125

As do these URLs:

GET [base]/ValueSet?url=http://acme.org/fhir/ValueSet/123,http://acme.org/fhir/ValueSet/124\,125
GET [base]/ValueSet?url=http%58%47%47acme%46org%47fhir%47ValueSet%47123%44http%58%47%47acme%46org%47fhir%47ValueSet%47124%92%46125

This specification defines this additional form of escape because the escape syntax using \ applies to all parameter values after they have been 'unescaped' on the server while being read from the HTTP headers.

Text Search Parameters

The special text search parameters, _text and _content, search on the narrative of the resource, and the entire content of the resource respectively. Just like string parameters using the :text modifier, these parameters SHOULD support a sophisticated search functionality of the type offered by typical text indexing services. The value of the parameter is a text-based search, which may involve searching multiple words with thesaurus and proximity considerations, and logical operations such as AND, OR etc. For example:

 GET [base]/Condition?_text=(bone OR liver) and metastases

This request returns all Condition resources with the word "metastases" and either "bone" or "liver" in the narrative. The server MAY choose to search for related words as well.

Implementers could consider using the rules specified by the the OData specification for the $search parameter. Typical implementations would use Lucene, Solr, an sql-based full text search, or some similar indexing service.

Special Parameters

A few parameters have the type special. The way this parameter works is unique to the parameter, and described with the parameter. The general modifiers and comparators do not apply, except as stated in the description.

Implementers will generally need to do special implementations for these parameters. These parameters are special:

Searching by list

The _list parameter allows for the retrieval of resources that are referenced by a List resource.

 GET [base]/Patient?_list=42

This request returns all Patient resources that are referenced from the list found at [base]/List/42) in List.entry.item. While it is possible to retrieve the list, and then iterate the entries in the list fetching each patient, using a list as a search criteria allows for additional search criteria to be specified. For instance:

 GET [base]/Patient?_list=42&gender=female

This request will return all female patients in the list. The server can return the list referred to in the search parameter as an included resource, but is not required to do so. In addition, a system can support searching by lists by their logical function. For example:

 GET [base]/AllergyIntolerance?patient=42&_list=$current-allergies

This request will return all allergies in patient 42's "Current Allergy List". The server returns all relevant AllergyIntolerance resources, and can also choose to return the list. For further information, refer to the definition of "$current-allergies", and the List Operation "Find". Note: Servers are not required to make these lists available to the clients as list resources, but may choose to do so.

Advanced filtering

The search mechanism described above is flexible, and easy to implement for simple cases, but is limited in its ability to express combination queries. To complement this mechanism, the "_filter" search expression parameter can be used.

For example, "Find all the observations for patient with a name including peter that have a LOINC code 1234-5":

GET [base]/Observation?code=http://loinc.org|1234-5&subject.name=peter

Using the _filter parameter, the search would be expressed like this:

GET [base]/Observation?_filter=code eq http://loinc.org|1234-5 and subject.name co "peter"

The _filter parameter is described in detail on the "_Filter Parameter" page.

Specifying the type of Resource

Normally, a search is initiated against a known type of resource, e.g.

GET [base]/Observation?params...

However, in some circumstances, a search is executed where there is no fixed type of resource:

In these circumstances, the search criteria may need to specify one or more resource types that the search applies to. This can be done by using the _type parameter:

GET [base]/?_type=Observation,Condition&other params...

If no type is specified, the only search parameters that be can be used in global search like this are the base parameters that apply to all resources. If multiple types are specified, any search parameters shared across the entire set of specified resources may be used (see search parameter registry).

Technically, the _type parameter is a token parameter on the Resource Types Value Set.

Managing Returned Resources

Sorting

The client can indicate which order to return the results by using the parameter _sort, which can contains a comma-separated list of sort rules in priority order:

GET [base]/Observation?_sort=status,-date,category

Each item in the comma separated list is a search parameter, optionally with a '-' prefix. The prefix indicates decreasing order; in its absence, the parameter is applied in increasing order.

Notes:

The _total parameter has the status trial-use pending real world experience of it's use.

Total number of matching resources

The return Bundle has an element total which is the number of resources that match the search parameters.

Note that Bundle.total represents the total number of matches, not how many resources are returned in a particular response (see paging, immediately below).

Providing a precise number of matching resources may be onerous for the server, depending on how the server is designed. To help reduce the server load, a client can provide the parameter _total to indicate it's preference with regard to the total, which can have one of the following values:

noneThere is no need to populate the total count; the client will not use it
estimateA rough estimate of the number of matching resources is sufficient
accurateThe client requests that the server provide an exact total of the number of matching resources

The Bundle.total element is still optional, and the servers can ignore the _total parameter: it is just an optimization hint, that might possibly save the server some work.

Page Count

In order to keep the load on clients, servers and the network minimized, the server may choose to return the results in a series of pages. The search result set contains the URLs that the client uses to request additional pages from the search set. For a simple RESTful search, the page links are contained in the returned bundle as links.

Typically, a server will provide its own parameters in the links that it uses to manage the state of the search as pages are retrieved. These parameters do not need to be understood or processed by the client.

The parameter _count is defined as an instruction to the server regarding how many resources should be returned in a single page. Servers SHALL NOT return more resources than requested, even if they don't support paging, but are allowed to return less than the client requested. The server should repeat the original _count parameter in its returned page links so that subsequent paging requests honor the original _count. Note: It is at the discretion of the search engine as to how to handle ongoing updates to the resources while the search is proceeding.

Note: The combination of _sort and _count can be used to return only the latest resource that meets a particular criteria - set the criteria, and then sort by date in descending order, with _count=1. This way, the last matching resource will be returned.

if _count has the value 0, this shall be treated the same as _summary=count: the server returns a bundle that reports the total number of resources that match in Bundle.total, but with no entries, and no prev/next/last links. Note that the Bundle.total only include the total number of matching resources. It does not count extra resources such as OperationOutcome or included resources that may also be returned. In the same way, the _count parameter only applies to resources with entry.search.mode = search, and does not include included resources or operation outcomes.

The _count parameter has no impact on the value of Bundle.total as the latter represents the total number of matches, not how many are returned in a single Bundle response.

Including other resources in result (_include and _revinclude)

Clients may request that the engine return resources related to the search results, in order to reduce the overall network delay of repeated retrievals of related resources. This is useful when the client is searching on a clinical resource, but for every such resource returned, the client will also need the subject (patient) resource that the clinical resource refers to. The client can use the _include parameter to indicate that the subject resources be included in the results. An alternative scenario is where the client wishes to fetch a particular resource, and any resources that refer to it. For example, the client may wish to fetch a MedicationRequest, and any provenance resources that refer to the prescription. This is known as a reverse include, and is specified by providing a _revinclude parameter.

Both _include and _revinclude are based on search parameters, rather than paths in the resource, since joins, such as chaining, are already done by search parameter.

Each _include parameter specifies a search parameter to join on:

 GET [base]/MedicationRequest?_include=MedicationRequest:patient
 GET [base]/MedicationRequest?_revinclude=Provenance:target

The first search requests all matching MedicationRequests, to include any patient that the medication prescriptions in the result set refer to. The second search requests all matching prescriptions, return all the provenance resources that refer to them.

Parameter values for both _include and _revinclude have three parts, separated by a : character:

  1. The name of the source resource from which the join comes
  2. The name of the search parameter which must be of type reference
  3. (Optional) A specific of type of target resource (for when the search parameter refers to multiple possible target types)

_include and _revinclude parameters do not include multiple values. Instead, the parameters are repeated for each different include criteria.

For each returned resource, the server identifies the resources that meet the criteria expressed in the join, and adds to the results, with the entry.search.mode set to "include" (in some searches, it is not obvious which resources are matches, and which are includes). If there is no reference, or no matching resource, the resource cannot be retrieved (e.g. on a different server), then the resource is omitted, and no error is returned.

The inclusion process can be iterative, if (and only if) the modifier :iterate is included. For example, this search returns all Medication Request resources and their prescribing Practitioner Resources for the matching Medication Dispense resources:

GET [base]/MedicationDispense?_include=MedicationDispense:prescription
    &_include:iterate=MedicationRequest:performer&criteria...

This technique applies to circular relationships as well. For example, the first of these two searches includes any related observations to the target relationships, but only those directly related. The second search asks for the _include based on related parameter to be executed iteratively, so it will retrieve observations that are directly related, and also any related observations to any other included observation.

GET [base]/Observation?_include=Observation:related-target&criteria...
GET [base]/Observation?_include:iterate=Observation:related-target&criteria...

Both _include and _revinclude use the wild card "*" for the search parameter name, indicating that any search parameter of type=reference be included. Though both clients and servers need to take care not to request or return too many resources when doing this. Most notably, using iterative wildcards inclusions might lead to the retrieval of the full patient's record, or even more than that: resources are organized into an interlinked network and broad _include paths may eventually traverse all possible paths on the server. For servers, these iterative and wildcard _includes are demanding and may slow the search response time significantly.

It is at the server's discretion how deep to iteratively evaluate the inclusions. Servers are expected to limit the number of iterations done to an appropriate level and are not obliged to honor requests to include additional resources in the search results. Because iterative search is generally resource intensive, it is not the default behavior.

When search results are paged, each page of search results should include the matching includes for the resources in each page, so that each page stands alone as a coherent package.

Note: when considering using _include and _revinclude, implementers should also consider whether using GraphQL and/or GraphDefinition are more appropriate approaches in their context.

Contained Resources

By default, search results only include resources that are not contained in other resources. A chained condition will be evaluated inside contained resources. To illustrate this, consider a MedicationRequest resource that has a contained Medication resource specifying a custom formulation that has ingredient with a itemCodeableConcept "abc" in "http://acme.com./medications". In this case, a search:

GET MedicationRequest?medication.ingredient-code=abc

will include the MedicationRequest resource in the results. However, this search:

GET Medication?ingredient-code=abc

will not include the contained Medication resource in the results, since either the wrong type of resource would be returned, or the contained resource would be returned without its container resource, which provides context to the contained resource.

Clients are able to modify this behavior using the _contained parameter, which can have one of the following values:

When contained resources are being returned, the server should return either the container resource, or the contained resource alone. The client can specify which by using the _containedType parameter, which can have one of the following values:

When returning a container resource, the server simply puts this in the search results:

<Bundle>
  ...
  <entry>
    <resource>
      <MedicationRequest>
        <id value="23">
        ....
        <contained>
          <Medication>
            <id value="m1">
            ...
          </Medication>
        <contained>

      </MedicationRequest>
    </resource>
    <search>
      <mode value="match"/>
    </search>
  </entry>
</Bundle>

In the case of returning container resources, the server SHALL populate the entry.search.mode element, as shown, so that the client can pick apart matches and includes (since the usual approach of doing it by type might not work).

If the return type is the contained resource, this must be done slightly differently:

<Bundle>
  ...
  <entry>
    <fullUrl value="http://example.com/fhir/MedicationRequest/23#m1"/>
    <resource>
      <Medication>
        <id value="m1">
        ...
      </Medication>
    </resource>
    <search>
      <mode value="match"/>
    </search>
  </entry>
</Bundle>

In this case, the fullUrl informs the client that this is a contained resource, along with indicating the identity of the containing resource.

External References

If the _include path selects a reference that refers to a resource on another server, the server can elect to include that resource in the search results for the convenience of the client.

If the _include path selects a reference that refers to an entity that is not a Resource, such as an image attachment, the server may also elect to include this in the returned results as a Binary resource. For example, the include path may point to an attachment which is by reference, like this:

 <content>
   <contentType>image/jpeg</contentType>
   <url>http://example.org/images/2343434/234234.jpg</url>
 </content>

The server can retrieve the target of this reference, and add it to the results for the convenience of the client.

Paging

When returning paged results for a search with _include resources, all _include resources that are related to the primary resources returned for the page SHOULD also be returned as part of that same page, even if some of those resource instances have previously been returned on previous pages. This approach allows both sender and receiver to avoid caching results of other pages.

Summary

The client can request the server to return only a portion of the resources by using the parameter _summary:

   GET [base]/ValueSet?_summary=true

The _summary parameter requests the server to return a subset of the resource. It can contain one of the following values:

trueReturn a limited subset of elements from the resource. This subset SHOULD consist solely of all supported elements that are marked as "summary" in the base definition of the resource(s) (see ElementDefinition.isSummary)
textReturn only the "text" element, the 'id' element, the 'meta' element, and only top-level mandatory elements
dataRemove the text element
countSearch only: just return a count of the matching resources, without returning the actual matches
falseReturn all parts of the resource(s)

The intent of the _summary parameter is to reduce the total processing load on server, client, and resources between them such as the network. It is most useful for resources that are large, particularly ones that include images or elements that may repeat many times. The purpose of the summary form is to allow a client to quickly retrieve a large set of resources, and let a user pick the appropriate one. The summary for an element is defined to allow a user to quickly sort and filter the resources, and typically omit important content on the basis that the entire resource will be retrieved when the user selects a resource.

Servers are not obliged to return just a summary as requested. There are only a limited number of summary forms defined for resources in order to allow servers to store the summarized form(s) in advance. Servers SHOULD mark the resources with the tag SUBSETTED to ensure that the incomplete resource is not acidentally used to overwrite a complete resource.

Note that the _include and _revinclude parameters cannot be mixed with _summary=text.

There is some question about the inclusion of extensions in the summary. Additional rules may be made around this in the future.

Elements

If one of the summary views defined above is not appropriate, a client can request a specific set of elements be returned as part of a resource in the search results using the _elements parameter:

   GET [base]/Patient?_elements=identifier,active,link

The _elements parameter consists of a comma-separated list of base element names such as, elements defined at the root level in the resource. Only elements that are listed are to be returned. Clients SHOULD list all mandatory and modifier elements in a resource as part of the list of elements. The list of elements does not apply to included resources.

Servers are not obliged to return just the requested elements. Servers SHOULD always return mandatory elements whether they are requested or not. Servers SHOULD mark the resources with the tag SUBSETTED to ensure that the incomplete resource is not actually used to overwrite a complete resource.

Relevance

Where a search specifies a non-deterministic sort, the search algorithm may generate some kind of ranking score to indicate which resources meet the specified criteria better than others. The server can return this score in entry.score:

  <entry>
    <score value=".45"/>
    <Patient>
      ... patient data ...
    </Patient>
  </entry>

The score is a decimal number with a value between (and including) 0 and 1, where 1 is best match, and 0 is least match.

Server Conformance

In order to allow the client to be confident about what search parameters were used as criteria by the server, the server SHALL return the parameters that were actually used to process the search. Applications processing search results SHALL check these returned values where necessary. For example, if the server did not support some of the filters specified in the search, a client might manually apply those filters to the retrieved result set, display a warning message to the user or take some other action.

In the case of a RESTful search, these parameters are encoded in the self link in the bundle that is returned:

  <link>
    <relation value="self"/>
    <url value="http://example.org/Patient?name=peter"/>
  </link>

In other respects, servers have considerable discretion with regards to supporting search:


Advanced Search

The search framework described above is a useful framework for providing a simple search based on indexed criteria, but more sophisticated query capability is needed to handle precise queries, complex decision support based requests, and direct queries that have human resolution.

More advanced search operations are specified by the _query parameter:

   GET [base]/Patient?_query=name&parameters...

The _query parameter names a custom search profile that describes a specific query operation. The named query may define additional named parameters that are used with that particular named query. Servers can define their own additional named queries to meet their own uses using an OperationDefinition.

There can only ever be one _query parameter in a set of search parameters. Servers processing search requests SHALL refuse to process a search request if they do not recognize the _query parameter value.

Search Result Currency

The results of a search operation are only guaranteed to be current at the moment the operation is executed. After the operation is executed, ongoing actions performed on the resources against which the search was executed will render the results increasingly stale. The significance of this depends on the nature of the search, and the kind of use that is being made of the results.

This is particularly relevant when the server is returning the results in a series of pages. It is at the discretion of the search engine of how to handle ongoing updates to the resources while the search is proceeding.

Performing a search operation does not change the set of resources on the server, with the exception of the creation of Audit Event resources auditing the search itself.

Summary Tables

Common Parameters defined for all resources:
NameTypeDescriptionPaths
_idtokenResource id (not a full URL)Resource.id
_lastUpdateddateDate last updated. Server has discretion on the boundary precisionResource.meta.lastUpdated
_tagtokenSearch by a resource tagResource.meta.tag
_profileuriSearch for all resources tagged with a profileResource.meta.profile
_securitytokenSearch by a security labelResource.meta.security
_textstringText search against the narrative
_contentstringText search against the entire resource
_liststringAll resources in nominated list (by id, not a full URL)
_querystringCustom named query
Search Control Parameters:
NameTypeDescriptionAllowable Content
_sortstringOrder to sort results in (can repeat for inner sort orders)Name of a valid search parameter
_countnumber Number of results per pageWhole number
_includestringOther resources to include in the search results that search matches point toSourceType:searchParam(:targetType)
_revincludestringOther resources to include in the search results when they refer to search matchesSourceType:searchParam(:targetType)
_summarystringJust return the summary elements (for resources where this is defined)true | false (false is default)
_containedstringWhether to return resources contained in other resources in the search matchestrue | false | both (false is default)
_containedTypestringIf returning contained resources, whether to return the contained or container resourcescontainer | contained

Cross-map between search parameter types and Data types:

Data Type number date reference quantity uri string token
Primitive Types
base64Binary
boolean
canonical
code
date
dateTime
decimal
id
instant
integer
markdown
oid
positiveInt
string
time
unsignedInt
uri
url
uuid
Data Types
Address
Age
Annotation
Attachment
CodeableConcept
Coding
Count
ContactPoint
Distance
Duration
HumanName
Identifier
Money
Period
Quantity
Range
Ratio
Reference
SampledData
Signature
Timing

search_filter.html

_filter Parameter

Maturity Level: 2Standards Status:Trial Use

Introduction

_filter is a parameter that can be used with the Search Operation. It uses the same set of standard parameters defined for the resources, and provides a syntax for expressing a set of query expressions on the underlying resources.

Examples of filters:

The _filter syntax has the following features:

Note: The only difference between a "string" value and a "token" value is that a string can contain spaces and ) and ]. There is otherwise no significant difference between them.

Formal grammar for the syntax:

filter        = paramExp / logExp / ("not") "(" filter ")"
logExp        = filter ("and" / "or" filter)+
paramExp      = paramPath SP compareOp SP compValue
compareOp     = (see table below)
compValue     = string / numberOrDate / token
string        = json string
token         = any sequence of non-whitespace characters (by Unicode rules) except "]" and ")"
paramPath     = paramName (("[" filter "]") "." paramPath)
paramName     = nameCharStart (nameChar)*
nameCharStart = "_" / ALPHA
nameChar      = "_" / "-" / DIGIT / ALPHA
numberOrDate  = DIGIT (DateChar)*
dateChar      = DIGIT / "T" / "-" / "." / "+"

Notes about using the syntax:

Operators

This table summarizes the comparison operations available:

Operation Definition
eq an item in the set has an equal value
ne An item in the set has an unequal value
co An item in the set contains this value
sw An item in the set starts with this value
ew An item in the set ends with this value
gt / lt / ge / le A value in the set is (greater than, less than, greater or equal, less or equal) the given value
ap A value in the set isis approximately the same as this value.
Note that the recommended value for the approximation is 10% of the stated value (or for a date, 10% of the gap between now and the date), but systems may choose other values where appropriate
sa The value starts after the specified value
eb The value ends before the specified value
pr The set is empty or not (value is false or true)
po True if a (implied) date period in the set overlaps with the implied period in the value
ss True if the value subsumes a concept in the set
sb True if the value is subsumed by a concept in the set
in True if one of the concepts is in the nominated value set by URI, either a relative, literal or logical vs
ni True if none of the concepts are in the nominated value set by URI, either a relative, literal or logical vs
re True if one of the references in set points to the given URL

For detailed rules about the operators eq, ne, le, ge, lt, gt, sa, and eb see Search Prefixes.

The interpretation of the operation depends on the type of the search parameter it is being evaulated against. This table contains those details:

Operation String Number Date Token Reference Quantity
Eq Character sequence is the same (case insensitive) Number is the same incl same precision Date is the same including same precision and timezone if provided Token is the same, including namespace if specified (case insensitive) n/a Unit and value are the same
Ne (same)
Co Character sequence matches somewhere (case insensitive) An item in the set's implicit imprecision includes the stated value An item in the set's implicit period includes the stated value n/a n/a n/a?
Sw Character sequence matches from first digit (left most, when L->R) (case insensitive) n/a n/a n/a n/a n/a
ew Character sequence matches up to last digit (right most, when L->R) (case insensitive) n/a n/a n/a n/a n/a
gt / lt / ge / le Based on Integer comparison of Unicode code points of starting character (trimmed) (case insensitive) Based on numerical comparison Based on date period comparison per 2.2.2.3 n/a n/a Based on numerical comparison if units are the same (or are canonicalised)
pr
po n/a n/a Based on date period comparison per 2.2.2.3 n/a n/a
ss n/a n/a n/a Based on logical subsumption; potentially catering for mapping between tx n/a n/a
sb n/a n/a n/a Based on logical subsumption; potentially catering for mapping between tx n/a n/a
in n/a n/a n/a Based on logical subsumption; potentially catering for mapping between tx n/a n/a
re n/a n/a n/a n/a Relative or absolute url n/a

Note:

Additional Parameters

Some additional parameters are defined for the filter parameter (to do: move these into the standard parameters):

Resource Type Parameter Name Children
Observation related

target = related-target

Type = related-type

Group characteristic

value = value

code = characteristic

DocumentReference relatesTo

code = relation

target = relatesTo

ServiceRequest event

status = event-status
date = event-date

ServiceRequest item

status = item-status

code = item-code

site = bodysite

event = item-event

ServiceRequest item-event

status = item-past-status
date = item-date
actor = actor

Note: