FHIR® tutorials FHIR® уроки

Bundle tutorial

Bundle is a container for resources, enabling you to group and transmit resources altogether at once. Guidance on the resource in general is available on the Bundle page, and on the RESTful API pages of the FHIR specification, with specific bundle types like transactions, messaging and documents having their own documentation.

Step 1: About Bundle

We've mentioned in the previous tutorial on resource references that resources can "contain" other resources. So how are Bundles different? The FHIR spec is quite helpful in this regard:

  • Contained resources are "in" the container resource - they can only ever be interpreted and/or changed in the context of the container
  • A Bundle is a collection of resources that have an independent existence - for example, they can also be accessed directly using the RESTful API

So, contained resources cannot be GET'd, PUT'd and DELETE'd separately, or even referenced individually from outside the containing resource. Resources inside a Bundle, depending on your Bundle type and how you've uploaded it, do get created individually on the server and thus can be acted on independently.

Here is how the general layout of a bundle looks like:

  1. Metadata describing the Bundle type, the total amount of entries (some which may not be visible because of paging), and a link if you need to retrieve this Bundle later.
  2. The meat of the resource, so to speak - this is where the resources that the Bundle has are stored. Included with resources are URLs which you can use to retrieve the resource individually.
  3. Used when you're uploading Bundles - this is where you specify to the server what to do with each resource.
  4. Used by the server when it's responding to your upload request - this is where it says how each operation went.

Here's an annotated example Bundle you'd receive from the server when searching:

Урок по Bundle (Пакетам)

Bundle - это контейнер для ресурсов, позволяющий группировать и передавать ресурсы все сразу. Руководство по ресурсу в целом доступно на странице Bundle, а также на страницах RESTful API спецификации FHIR, при этом конкретные типы пакетов, такие как транзакции, сообщения и документы, имеют свою собственную документацию.

Шаг 1: О Bundle

Мы упоминали в предыдущем уроке по ссылкам на ресурсы, что ресурсы могут "содержать" другие ресурсы. Так чем же отличаются Bundle? Спецификация FHIR довольно полезна в этом отношении:

  • Содержащиеся ресурсы находятся "внутри" контейнерного ресурса - они могут интерпретироваться и/или изменяться только в контексте контейнера
  • Bundle - это коллекция ресурсов, которые имеют независимое существование - например, к ним также можно получить прямой доступ с помощью RESTful API

Таким образом, содержащиеся ресурсы нельзя получить, обновить или удалить отдельно с помощью GET, PUT и DELETE, или даже ссылаться на них индивидуально извне содержащего ресурса. Ресурсы внутри Bundle, в зависимости от типа Bundle и способа загрузки, создаются индивидуально на сервере и, таким образом, могут обрабатываться независимо.

Вот как выглядит общая структура bundle:

  1. Метаданные, описывающие тип Bundle, общее количество записей (некоторые из которых могут быть не видны из-за пагинации), и ссылка, если вам нужно получить этот Bundle позже.
  2. Суть ресурса, так сказать - здесь хранятся ресурсы, которые содержит Bundle. Вместе с ресурсами включены URL-адреса, которые можно использовать для получения ресурса индивидуально.
  3. Используется при загрузке Bundle - здесь вы указываете серверу, что делать с каждым ресурсом.
  4. Используется сервером при ответе на ваш запрос загрузки - здесь он сообщает, как прошла каждая операция.

Вот аннотированный пример Bundle, который вы получили бы от сервера при поиске:

Paging

When the Bundle is too big to send in one go, because it has many resources within it, the server can choose to break it up into pieces (called "pages"). To allow you to easy navigate from one page to the next the Bundle provides links to the next page within it. So the client, after getting a page, can request the next page and so on until the end. In addition, there are also links to the previous, first, and last pages provided in each Bundle (see the example below):

Пагинация

Когда Bundle слишком большой для отправки за один раз, поскольку он содержит много ресурсов, сервер может разбить его на части (называемые "страницами"). Чтобы позволить вам легко переходить от одной страницы к следующей, Bundle предоставляет ссылки на следующую страницу внутри себя. Таким образом, клиент, получив страницу, может запросить следующую страницу и так далее до конца. Кроме того, в каждом Bundle также предоставляются ссылки на предыдущую, первую и последнюю страницы (см. пример ниже):


See more information on paging on the FHIR spec.

См. больше информации о пагинации в спецификации FHIR.

Step 3: Bundle Types

There are several types of Bundles defined by FHIR: document, message, transaction, transaction-response, batch, batch-response, history, searchset, and collection.

Шаг 3: Типы Bundle

FHIR определяет несколько типов Bundle: document, message, transaction, transaction-response, batch, batch-response, history, searchset и collection.

Bundle type Тип Bundle Bundle description Описание Bundle
searchset Used in searching - an operation you're already familiar with - it's the Bundle that collates search results into a single response. As some search results can return a large number of results, this is where the idea of paging comes in. Используется при поиске - операция, с которой вы уже знакомы - это Bundle, который объединяет результаты поиска в один ответ. Поскольку некоторые результаты поиска могут возвращать большое количество результатов, здесь появляется идея пагинации.
document, message, collection Used in specific data exchange paradigms. Loosely speaking, you can think of document-type Bundles as those representing a CDA document, a message-type Bundle representing a V2 message, and a collection as a general catch-all type. Используются в специфических парадигмах обмена данными. Грубо говоря, можно думать о Bundle типа document как о представляющих CDA документ, Bundle типа message как о представляющих V2 сообщение, а collection как об общем универсальном типе.
history Similar to searchset, but is specialised for the _history operations when you're looking at the history of operations on single instance of a resource. For example, looking at all the edits made to a single Patient resource. Похож на searchset, но специализирован для операций _history, когда вы просматриваете историю операций над одним экземпляром ресурса. Например, просмотр всех изменений, внесенных в один ресурс Patient.
batch, transaction Allows you to condense multiple operations into one - say you'd like to upload 5 resources but don't want to do it 5 times. You can gather all of the resources up into a bundle and upload it all at once. The difference between a batch and a transaction is how things are handled when an issue happens. When one of the operations of a transaction fails, the entire transaction fails and no changes happen on the server as a result of the transaction. If one of the operations of a batch fails, then the rest of the operations can still complete successfully. Позволяет объединить несколько операций в одну - скажем, вы хотите загрузить 5 ресурсов, но не хотите делать это 5 раз. Вы можете собрать все ресурсы в bundle и загрузить все сразу. Разница между batch и transaction заключается в том, как обрабатываются ситуации при возникновении проблем. Когда одна из операций transaction терпит неудачу, вся транзакция терпит неудачу и никаких изменений на сервере в результате транзакции не происходит. Если одна из операций batch терпит неудачу, то остальные операции все еще могут завершиться успешно.
batch-response, transaction-response What the server will respond with where it tells you what happened with each operation within your batch or transaction Bundle. То, чем сервер ответит, где он сообщает вам, что произошло с каждой операцией в вашем Bundle типа batch или transaction.
Step 4: Upload endpoints

If you upload a Bundle to [Service Root URL]/Bundle, your Bundle will be stored as-is, just like any other resource. Sometimes this is the desired behaviour, alternatively, you may like the server to actually process the Bundle. For example, the transactions in your transaction Bundle to actually be acted upon. In order to get the server to unpack and process your Bundle, you need to upload to the [Service Root URL] directly. This most reliably works for transaction, batch, and document Bundle types. How the server deals with other Bundle types is up to it. Here is a complete list of endpoints that Bundles may be uploaded to:

Шаг 4: Эндпоинты для загрузки

Если вы загружаете Bundle в [Service Root URL]/Bundle, ваш Bundle будет сохранен как есть, как и любой другой ресурс. Иногда это желаемое поведение - но обычно вы хотите, чтобы сервер обработал Bundle. Например, чтобы транзакции в вашем transaction Bundle были выполнены. Чтобы заставить сервер распаковать и обработать ваш Bundle, вам нужно загрузить его непосредственно в [Service Root URL]. Это наиболее надежно работает для типов Bundle: transaction, batch и document. То, как сервер обрабатывает другие типы Bundle, зависит от него. Вот полный список конечных точек, в которые могут быть загружены Bundle:

Endpoint Конечная точка Bundle type Тип Bundle Effect on the Bundle Влияние на Bundle
[Service Root URL] batch, transaction Bundle is processed by the server - individual operations/resources are unpacked and acted upon. Bundle обрабатывается сервером - отдельные операции/ресурсы распаковываются и обрабатываются.
[Service Root URL] history Bundle may be be processed by the server as its structure is very similar to batch/transaction type. Bundle может быть обработан сервером, поскольку его структура очень похожа на тип batch/transaction.
[Service Root URL] document, message, transaction-response, batch-response, history, searchset, collection Bundle may be processed by the server as create/update operations. Bundle может быть обработан сервером как операции создания/обновления.
[Service Root URL]/Binary document Bundle is stored as-is by the server as binary content and not acted upon. Bundle сохраняется сервером как есть в виде двоичного содержимого и не обрабатывается.
[Service Root URL]/Bundle document, transaction, transaction-response, batch, batch-response, history, searchset, and collection Bundle is stored as-is by the server and not acted upon, same as if you uploaded a Patient resource. Bundle сохраняется сервером как есть и не обрабатывается, так же как если бы вы загрузили ресурс Patient.
[Service Root URL]/Bundle message Bundle is processed by the server - server will store the Bundle as-is, index it on the MessageHeader, and act on the message. This is the RESTful endpoint for a message Bundle Bundle обрабатывается сервером - сервер сохранит Bundle как есть, проиндексирует его по MessageHeader и обработает сообщение. Это RESTful конечная точка для message Bundle
[Service Root URL]/$process-message message Bundle is processed by the server as if it is a message. Bundle обрабатывается сервером как сообщение.
Step 5: Reference resolution

References between resources within a Bundle can come in two types. Either references to resources where each resource is within the Bundle but not as yet on the server.

Or references from resources in the bundle to resources that are on the server but not found in the bundle.

When uploading a bundle of resources to a server, as in the first case, it can be a little confusing to understand how to form the reference between the resources. How can you reference a resource if the server has not as yet assigned an ID to it?

The simple answer is that the bundle creator can assign temporary resource IDs to resources in order to create the references between each resource. Then depending on the way you upload the Bundle to the server the server can use your IDs to understand the linkage between resources and will assign its own server IDs and update all the existing references with the new IDs. In these cases, the server will then reply with a return Bundle that informs the sender of these updated IDs. If you refer back the Bundle layout image at the beginning of this page you can see the 'Bundle/entry/response/location' element where these new IDs would be returned as a URI. Whether the server performs this identification or not is dependant on the Bundle type you are uploading and the endpoint you are uploading it to. The table below talks more to this point.

Unlike general resources you need to take care when resolving references between resources in Bundles, you can not just assume the reference is to a resource on a server, it may be a reference to a resource within the same Bundle and you should assume this first. For more on this topic refer to the FHIR specification here:Resolving references in Bundles

The table below describes the effect Bundle type can have on uploading Bundles:

Шаг 5: Разрешение ссылок

Ссылки между ресурсами внутри Bundle могут быть двух типов. Либо ссылки на ресурсы, где каждый ресурс находится внутри Bundle, но еще не на сервере.

Или ссылки от ресурсов в bundle на ресурсы, которые находятся на сервере, но не найдены в bundle.

При загрузке bundle ресурсов на сервер, как в первом случае, может быть не совсем понятно, как формировать ссылку между ресурсами. Как можно ссылаться на ресурс, если сервер еще не назначил ему ID?

Ответ заключается в том, что создатель bundle может назначить временные ID ресурсов для создания ссылок между каждым ресурсом. Затем, в зависимости от способа загрузки Bundle на сервер, сервер может использовать ваши ID для понимания связи между ресурсами и назначит свои собственные серверные ID и обновит все существующие ссылки новыми ID. В этих случаях сервер затем ответит возвращаемым Bundle, который информирует отправителя об этих обновленных ID. Если вы вернетесь к изображению структуры Bundle в начале этой страницы, вы можете увидеть элемент 'Bundle/entry/response/location', где эти новые ID будут возвращены как URI. Выполняет ли сервер эту идентификацию или нет, зависит от типа Bundle, который вы загружаете, и конечной точки, в которую вы его загружаете. Таблица ниже более подробно рассматривает этот момент.

В отличие от общих ресурсов, вам нужно быть осторожным при разрешении ссылок между ресурсами в Bundle, вы не можете просто предполагать, что ссылка указывает на ресурс на сервере, это может быть ссылка на ресурс внутри того же Bundle, и вы должны предполагать это в первую очередь. Для получения дополнительной информации по этой теме обратитесь к спецификации FHIR здесь: Разрешение ссылок в Bundle

Таблица ниже описывает влияние, которое тип Bundle может оказать на загрузку Bundle:

Bundle type Тип Bundle Effect on Bundle upload Влияние на загрузку Bundle
document You can create your own IDs for resources and use them as references for other resources within the Bundle. A document Bundle typically is stored as-is on the server, without it getting unpacked - although if you upload it to the [Service Root URL] instead of the usual endpoints then it will be up to the server to unpack the Bundle and replace your assigned resource ID's with its own (though it doesn't have to). Вы можете создать свои собственные ID для ресурсов и использовать их как ссылки для других ресурсов внутри Bundle. Document Bundle обычно сохраняется как есть на сервере, без распаковки - хотя если вы загружаете его в [Service Root URL] вместо обычных конечных точек, то сервер может распаковать Bundle и заменить ваши назначенные ID ресурсов своими собственными (хотя он не обязан это делать).
batch You cannot reference other resources inside the Bundle - thus all resources inside a batch Bundle must be completely independent, only reference resources already created on the server, or resources available on other servers. Вы не можете ссылаться на другие ресурсы внутри Bundle - таким образом, все ресурсы внутри batch Bundle должны быть полностью независимыми, ссылаться только на ресурсы, уже созданные на сервере, или ресурсы, доступные на других серверах.
transaction You can reference other resources inside the Bundle using their business identifiers in a simplified search query. It is then on the server to replace the search query with the resource ID's when processing the Bundle. See Conditional References section of Transaction Processing Rules for more. Вы можете ссылаться на другие ресурсы внутри Bundle, используя их бизнес-идентификаторы в упрощенном поисковом запросе. Затем сервер должен заменить поисковый запрос на ID ресурсов при обработке Bundle. См. раздел Условные ссылки в Правилах обработки транзакций для получения дополнительной информации.
message Similar to document - you create your own IDs and use those as references within the Bundle. In the event that you upload a message Bundle to the RESTful API on the [Service Root URL]/Bundle endpoint (instead of the usual [Service Root URL]/Bundle/$process-message), the Bundle is not unpacked and only the MessageHeader is indexed. Похоже на document - вы создаете свои собственные ID и используете их как ссылки внутри Bundle. В случае, если вы загружаете message Bundle в RESTful API на конечную точку [Service Root URL]/Bundle (вместо обычной [Service Root URL]/Bundle/$process-message), Bundle не распаковывается и индексируется только MessageHeader.
collection, searchset, history You can create your own IDs for resources and use them as references within the Bundle - although the server will most likely store these resources as-is and not act on them, since these types of Bundles are typically for servers to send to clients. Вы можете создать свои собственные ID для ресурсов и использовать их как ссылки внутри Bundle - хотя сервер, скорее всего, сохранит эти ресурсы как есть и не будет действовать на них, поскольку эти типы Bundle обычно предназначены для отправки серверами клиентам.

That's about it for the difficult parts of a Bundle! Have a look at the FHIR page for Bundle now for things like uniqueness rules and search parameters of a Bundle.

Это все о сложных частях Bundle! Теперь взгляните на страницу FHIR для Bundle для изучения таких вещей, как правила уникальности и параметры поиска Bundle.