6.11 Query リソース

logo fhir

HomeInfrastructureQuery [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:

  • A specified resource type
  • A specified compartment, perhaps with a specified resource type in that compartment
  • All resources

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

Standard Parameters 6.11.2

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.

Search Parameter Types 6.11.2.1

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.

Modifiers 6.11.2.1.1

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:

  • For all parameters (except combination): "missing". E.g. gender:missing=true (or false). Searching for "gender:missing=true" will return all the resources that don't have any value for the gender parameter (which usually equates to not having the relevant element in the resource). Searching for "gender:missing=false" will return all the resources that have a value for the "gender" parameter.
  • For dates: ":before" and ":after". E.g. birthdate:before=1972-11-30. See below for how date searches are interpreted.
  • For string: ":exact" (the match needs to be exact, no partial matches, case sensitive and accent-sensitive) and ":partial" (the search may function on partial matches). It is at the discretion of the server whether to do a left-partial search
  • For token: ":text" (the match does a partial searches on the text portion of a CodeableConcept or the display portion of a Coding), ":code" (a match on code and system of the coding/codeable concept), and :anyns matches all codes irrespective of the namespace.

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:

  • name=namespace/code specifies matches on both the namespace and the code (or, for identifiers, key)
  • name=/code matches a code that has no specified namespace

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.

  • The date parameter format is yyyy-mm-ddThh:nn:ss(TZ) (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 must 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 timezone if the time part is present
    • Some user agents may escape the ":" characters in the URL, and servers SHALL handle this correctly
  • Date parameters have the :before and :after modifiers. [date]=[value] searches for resources where the date is within the given date value. [date]:after=[value] searches for all resources where the specified date is after [value]. [date]:before=[value] searches for all resources where the specified date is before [value].
  • The element the search refers to may be a date, a dateTime, a Period, or a Schedule. All of these time related types actually specify an interval of time, as does the search parameter itself.
    • For Period and Schedule, the interval of time is explicit (though the upper or lower bound may not actually be specified in resources)
    • For a date or a dateTime (and the search parameter), the interval is implicit. 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.
    • An instant (which is the same as a fully specified dateTime with milliseconds) 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.
  • Date parameter searches are always matched based on the behavior of intervals, as follows:
    • For [date]=[value], the requirement is that the search interval fully contains the time of the target. i.e. 2013-01-14 includes 2013-01-14T00:00 (obviously) and also 2013-01-14T10:00 but not 2013-01-15T00:00
    • For [date]:before=[value], the requirement is that the interval of the time before [value] intersects (i.e. overlaps) with the interval of time in the relevant resource element. For instance, the resource time 2013-01-14 is included in the set of values that come before 2013-01-14T10:00, because it includes the part of 14-Jan 2013 before 10am
    • For [date]:after=[value], the requirement is that the interval of the time after [value] intersects (i.e. overlaps) with the interval of time in the relevant resource element. For instance, the resource time 2013-01-14 is included in the set of values that come after 2013-01-14T10:00, because it includes the part of 14-Jan 2013 after 10am
    • If the bounds of the interval are not known (i.e. a range with no start, or a schedule like "every two days" with neither start or end), then the boundaries are implicitly considered above or below calculable time, and so these count as intersections. For instance, the period from 21-Jan 2013 onwards is included in matches for date-after=2013-03-14 because it may include times after 14-Mar 2013.
  • Similarly, when the date parameter is not fully specified, matches against it are based on the behavior of intervals, where:
    • Dates with just the year specified are equivalent to an interval that starts at the first instant of January 1st to the last instant of December 31st, e.g. 2000 is equivalent to an interval of [2000-01-01T00:00, 2000-12-31T23:59]
    • Dates with the year and month are equivalent to an interval that starts at the first instant of the first day of the month and ends on the last instant of the last day of the month, e.g. 2000-04 is equivalent to an interval of [2000-04-01T00:00, 2000-04-30T23:59]
  • Where possible, the system should correct for timezones when performing queries. Dates do not have timezones, and timezones should not be considered. Where both search parameters and resource element date times do not have timezones, the servers local time zone should be assumed.
  • Note that for a Schedule data type, the 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.

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

reference 6.11.2.1.5

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:

  • name=id the id of a resource (not including the @ that goes in the URL)
  • name=type/id matches an id of a resource with a specific target type. This is useful if the resource reference can refer to multiple different resource types.

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.

Managing Returned Resources 6.11.3

Sorting 6.11.3.1

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.

Including other resources in result (_include) 6.11.3.3

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.

Summary 6.11.3.4

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.

Server Conformance 6.11.4

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:

  • Servers can choose which parameters to support (other than _id above)
  • Servers can choose when and where to implement parameter chaining, and when and where they support the _include parameter
  • Servers are able to declare additional parameters in the profiles referenced from their conformance statements. Servers should define search parameters starting with a "-" character to ensure that the names they choose do not clash with future parameters defined by this specification
  • Servers are not required to enforce case sensitivity on parameter names, though the names are case sensitive (and URLs are generally case-sensitive)
  • Servers may choose how many results to return, though the client can use _count as above
  • Servers can choose how to sort the return results, though they SHOULD honour the _sort parameter

Advanced Search/Query 6.11.5

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&parameters...

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:

  • Perform search operation on a RESTful interface (as described above)
  • Send a query message, and receive a query response
  • On a RESTful interface, create a query resource with an order, and wait for the order response (this allows asynchronous queries across a RESTful interface)

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.

Query Resource 6.11.7

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

Terminology Bindings 6.11.8.1

Notes about the Query resource:

  • The id is usually a UUID (urn:uuid:...). Its sole use is to match request and response logically
  • The parameters defined for use with the query the resource are all those described above
  • The extension type is used for parameters. The namespace http://hl7.org/fhir/query is used in the uri value for all the named parameters. Other namespaces may be used for parameters that would/could not appear in the named parameter list in a query url.
  • Parameter names are mandatory, and values are optional. Parameters with missing values are ignored when processing the query
  • Parameter names do not need to be unique. The interpretation of multiple search parameters is as described above
  • There SHALL be at least one parameter provided with a search - a search request without any request cannot be processed
  • The search engine SHALL return the parameters used to process the search so the client knows what search was performed
  • The links to first, previous, next and last pages in the query result set are provided at the discretion of the server. The client performs a new query using those parameters to retrieve the specified pages. If no parameters are returned, there is no link to follow
  • The references to the result set are usually version specific references
  • The query resource contains an outcome code. There is no way to represent the code "limited" in a RESTful query where there is no query resource

Messaging based Queries 6.11.8.2

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:

  1. The requester constructs a Query resource, and performs a create operation to the /query endpoint, and gets the id of the query resource on the server
  2. The requester constructs an Order resource that contains details as appropriate, and which has the query resource as its order detail, and creates that on the server
  3. A responder picks up the existence of the order resource (either the server acting directly, or a client that is subscribed to the order feed on the server)
  4. The responder retrieves the query, and then processes it, generating a new query resource that is the response, and then creates that on the server
  5. The responder constructs an Order Response resource with a reference to the request from Step #2, a code of "complete", and a fulfillment that points to the query response from step #4
  6. The requester sees the existence of the order response (e.g. by subscribing - watching the updates to Order Response on the server), and retrieves the query response
  7. The requester retrieves the matching resources by iterating through the matching resources and retrieving them based on their reference.

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.

Search/Query Result Currency 6.11.9

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:

  • The question of searching on a particular resource (as described by the RESTful interface). is this a parameter? Should the restful search operate at the system level as well?
  • The overlap between query response and operation outcome in the case of errors in them messaging context

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 6.11.11

Search Parameters for RESTful searches. The standard parameters also apply as described above.