Home > Infrastructure > Query [query]
Resource Query - Content6.11
A description of a query with a set of parameters.
The resource name as it appears in a RESTful URL is [root]/query/
One operation that is fundamental to the way FHIR works is to search (find existing resources by filter criteria) or query (more detailed questions based on existing data). Search/query operations can span complexity from a simple search based on indexed criteria, through to complex decision support based requests, and finally complex queries that can only be resolved by human intervention. This page documents the FHIR search framework, starting with the simple cases, and working through to the full complexity. Implementations need only implement the amount of complexity that they require.
In the simplest case, a search is executed by performing a GET operation in the RESTful framework:
GET .../[resourcetype]/(?parameters)
For this RESTful search, the parameters are a series of name=value pairs encoded in the URL or as an x-multi-part-form submission for a POST. The server returns the results in the HTTP response as a bundle (in XML, an atom feed) which includes the resources that are the results of the query. The server can also include additional resources in the result set, such as OperationOutcome resources. Clients should ignore resources that don't have the expected type. A HTTP status code of 403 signifies that the server refused to perform the query, while some other 4xx or 5xx code signifies that some error occurred.
Search operations are executed in one of 3 defined contexts that control which set of resources are being searched:
Search/Query operations can also be initiated by other more complex and flexible methods described below, which change both the way the search/query is initiated, and the results that are returned.
Search / Query 6.11.1
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 .../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 .../patient/@23
except that it returns a bundle with the requested resource, rather than the resource itself. However additional parameters can be added which may provide additional functionality on top of this base read equivalence.
In addition to this resource, each FHIR resource type defines a set of applicable search parameters with their names, types, and meanings. Mostly, 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 of the search parameters defined by the resources are associated with more than one path in the resource. This means that the search parameter matches if any of the paths contain matching content, and which ever 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 these search parameters (except for the _id parameter described above), and may define their own additional parameters if they wish.
Each search parameter is defined a type that defines how the search parameter behaves. These are the defined parameter types:
The search parameters can also have "modifiers" appended to them that control their behaviour. The kind of modifiers that can be used depend on the type of parameter.
Parameters are defined per resource, and their names may additionally specify a modifier as a suffix, separated from the parameter name by a dot. Modifiers are:
integer6.11.2.1.2
The prefixes >, >=, <=, and < may be used on the parameter value, and has the usual meaning. Note that '=" must be escaped in the value in a URL.
token6.11.2.1.3
A token type is a parameter that searches on a code or identifier value where the value may have a URI that scopes its meaning (from aCoding or an Identifier type, and also from a code where the URI is implicit).
If the parameter has no modifier, or the modifier ":text", the search parameter is a string; if the modifier is ":code" the parameter is a pair of fixed value strings, namespace and value, separated by a "/"; if the modifier is :anyns, the parameter is a single value fixed string. Without modifier, the search will use the textual parameter to do a partial match on code, text or display. With modifier ":text" the search will do a partial match on text or display. With the ":code" modifier, the search will work as follows:
In the url of the code system, the “#” (fragment identifier) must be escaped, and in some implementations, the ":" does too. The modifier :anyns means that the code matches all codes irrespective of the namespace.
Here are some example searches:
date6.11.2.1.4
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.
As an example, the following search searches for all the procedures in a patient compartment that occurred over a 2 year period:
GET [baseurl]/patient/@23/procedure?date:after=2010-01-01&date:before=2011-12-31
A reference parameter refers to references between resources, e.g. find all Conditions where the subject reference is a particular patient by the patient id. The interpretation of a reference parameter is either:
In order to save a client from doing a series of search operations, reference parameters may be "chained" by appending them with a period (.) followed by the name of a search parameters 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 [baseurl]/diagnosticreport/search?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 possible to limit the search to a particular type:
GET [baseurl]/diagnosticreport/search?subject:patient.name="peter"
Advanced Search Note: Where a chained parameter searches a resource reference that may have more than one different 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. The parameter names defined in FHIR have consistent types wherever they are used. Implementers defining their own names need to be sure that they do not create unprocessable combinations.
Combining Search Parameters6.11.2.2
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. If, instead, the search is to find patients that speak either language, then this is a single parameter with multiple values, separated by a ',': /patient?language=FR,NL.
This 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: 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 combination 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 that this sequence is a single value and itself can be composed into a set of values, so that, for example, multiple matching state-on-date parameters can be specified as state-on-date=new$2013-05-04,active$2013-05-05.
Selecting resources by Tag6.11.2.3
Resources may have tags affixed to them. the _tag resource searches for a resource by URI. For example:
condition/search?_tag=http://acme.org/fhir/tags/needs-review
This searches for all Condition resources with the tag "http://acme.org/fhir/tags/needs-review". The _tag search parameter may have the modifiers :partial and :text, which mean to only match on the left side of the target tags, or to search the label part of the tag respectively.
The client can indicate which order to return the results in using the parameter "_sort". This can be set to one of the search parameters. Where the search parameter returns multiple values, the lowest value will be used when ordering the returned records. Note that the actual sort value used is not returned explicitly by the server.
Page Count6.11.3.2
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 query as pages are retrieved. These parameters do not need to be understood or processed by the client.
The parameter _count is defined as a hint 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 asked for. Note that it is at the discretion of the search engine how to handle ongoing updates to the resources while the search is proceeding.
Clients may request that the engine return additional resources related to the search results, in order to reduce the overall network query time. A typical case where this is useful is where the client is querying on some type of 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 requests that the subject resources be included in the results set by providing one or more _include parameters.
Each _include parameter specifies a path to a url (usually a resource reference):
GET .../medicationdispense/search?_include=MedicationDispense.prescription &_include=MedicationPrescription.prescriber&criteria...
For each returned resource, the server collects the elements described by the path, and any resources they point to that the server also holds are added to the results. This search returns all the Medication Prescription resources and their prescribing Practitioner Resources for the matching Medication Dispense resources.
Include paths are processed only in the context of a single resource - they can not include paths such as Resource.name1.name2 where name2 is a name in a resource pointed to by name1. Include paths may include wild cards, such as MedicationDispense.results.*, or even _include=*, though both servers and clients need to take care not to request or return too many resources when doing this.
For servers, recursive and wildcard _includes are demanding and may slow the search response time significantly. Servers are not obliged to honor requests to include additional resources in the search results.
External References6.11.3.3.1
If the _include path matches an url that points to a resource that the server itself does not hold itself, the server may still elect to include the target of the uri reference 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 on behalf of the client, and add this to the results for the convenience of the client.
The client can request the server to return a summary portion of the resources only using the parameter "_summary":
GET [base-url]/valueset?_summary=true
The _summary parameter requests the server to return only the elements marked as "summary" in their definition. This is used to reduce the total processing load on server, client, and resources between them such as the network. It is most useful for resources that can be large, particularly ones that include images or elements that may repeat many times.
Servers are not obliged to return just a summary, and summaries are not defined for resources where there is no need for summarization. There is only one summary form defined for each resource in order to allow servers to store the summarised form in advance.
In order to allow the client to be confident about what search parameters were used as a 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 atom feed that is returned:
<link rel="self" href="http://example.org/patient/search?name=peter"/>
In other respects, servers have considerable discretion with regards to supporting search:
The search framework described above is a useful framework for providing a simple search based on indexed criteria, but more sophistication is needed to handle precise queries, complex decision support based requests, and direct queries that have human resolution.
More advanced search/query operations are specified by the _query parameter:
GET .../patient?_query=name¶meters...
The _query parameter names a custom search profile that describes a specific search/query operation. The named query may define additional parameters that are used with that particular named query, and will define their type and behavior on repetition and omission.
FHIR defines some named queries:
In addition, servers can define their own additional named queries to meet their own uses.
There can only ever be one _query parameter in a set of search parameters. Servers processing search requests must refuse to process a search request if they do not recognise the _query parameter value.
Some named queries may have side effects such as creating new clinical resources that may be persistent or transitory. The general search defined above always searches existing resources, and the only new resources that may be created are Security Event resources auditing the search.
Executing Search / Query6.11.6
FHIR defines 3 different ways in which a search through a repository of resources can be initiated:
In all 3 cases, the basic operation is simple: given a set of parameters which are name/value pairs, perform a query against a repository of resources, and return the set of matching resources, possibly with some additional related resources. The second two search methods are implemented using the Query Resource.
The resource is used to perform queries using messaging-based exchanges, and to perform asynchronous searches using the RESTful interface.
Resource Content6.11.8
<Query xmlns="http://hl7.org/fhir"> <!-- from Resource: extension, narrative, and contained --> <identifier value="[uri]"/><!-- 1..1 Links query and its response(s) --> <parameter><!-- 1..* Extension Set of query parameters with values --></parameter> <response> <!-- 0..1 If this is a response to a query --> <identifier value="[uri]"/><!-- 1..1 Links response to source query --> <outcome value="[code]"/><!-- 1..1 Outcome of processing the query --> <total value="[integer]"/><!-- 0..1 Total number of matching records --> <parameter><!-- 0..* Extension Parameters server used --></parameter> <first><!-- 0..* Extension To get first page (if paged) --></first> <previous><!-- 0..* Extension To get previous page (if paged) --></previous> <next><!-- 0..* Extension To get next page (if paged) --></next> <last><!-- 0..* Extension To get last page (if paged) --></last> <reference><!-- 0..* Resource(Any) Resources that are the results of the search --></reference> </response> </Query>
Alternate definitions: Schema/Schematron, Resource Profile
Notes about the Query resource:
In order to initiate a message-based query, a sender sends a message consisting of a Message resource, and a Query resource. The message resource routes the message to the correct destination, and the query contains the parameters of the search that is requested. See the examples for an example query request message.
The receiver processes the message, and then returns a message with a message header, a query with a response details, and a set of resources that meet the query criteria. See the examples for an example query response message.
If the sender wishes to retrieve additional pages from the original search, the sender constructs a new query with the parameters specified by the search processing system, and the cycle starts again.
Asynchronous Queries on a REST framework6.11.8.3
The RESTful framework provides a simple convenient synchronous search based on request/response as described above. This works well as long it doesn't take very long to process a query. As the query processing time gets longer, the synchronous search starts to take too long to manage in this kind of framework. In particular, some queries may require human intervention to process correctly, or may even by direct human-human queries. For these, some asynchronous approach is required. The messaging solution discussed above can be used asynchronously, but it's also possible to implement asynchronous queries in a RESTful environment. Here's how this would work:
This pattern is more complex than the other uses, so will be used less. There are several variations on this theme. For instance, the requester may choose to perform the first two operations as a transaction, or the responder may choose to inform the requester that processing as commenced with an order response code of "accepted".
Note that it's also possible to expose service end points in a SOA fashion that use the query resource and/or definitions in other ways, though such usages are not described in FHIR.
The results of a search/query 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 query 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 how to handle ongoing updates to the resources while the search is proceeding.
Query result sets may include resources created by the processing of the search. Typically, these are the results of queries for decision support, value set expansion, etc., and represent the outcome of processing the query. In order to be usable in the scenarios above, these resources have a defined structure and have the same metadata as any other resource, including a known identity, but they have the same currency issues as the results from a query.
Applications handling the results of an operation that creates resources should use these resources with careful consideration of their currency. Though the resources may be retained for audit purposes, implementers must be careful not to reuse these as if they are current.
note: known issues relating to this page:
Searching the Searches6.11.10
As a consequence of the general framework, it is possible to search on a set of stored queries, though there is no known particular use case for doing so.
Search Parameters for RESTful searches. The standard parameters also apply as described above.