FHIR® tutorials FHIR® уроки

ValueSet and CodeSystem

This tutorial will cover the basics of the ValueSet and CodeSystem resources which are two of the three key resources for working with terminology within FHIR, with the other one being ConceptMap.

Step 1: What are ValueSets and CodeSystems

In Healthcare, we use many codes from many different sets of codes. We have relatively simple ones like patient gender and more complex ones such as allergies and adverse reactions and more clerical ones like facility codes or billing codes. FHIR cannot define every required code and code set for every Healthcare system across the world. Instead, FHIR provides a mechanism to manage the codes and code sets and that mechanism is a CodeSystem and ValueSet resources.

FHIR's CodeSystems and ValueSets work hand in hand to manage terminology in FHIR. The two are so closely tied that in the early versions of FHIR they were actually one resource. Yet since the STU3 version of FHIR, they have been separated. Here we will first explain the concepts behind CodeSystem and ValueSet and later we will look at the FHIR resources that embody them.

It is best to start by explaining CodeSystem as it is the basis that ValueSets are then created from. You can think of a CodeSystem as being a master catalogue of a particular set of codes. It is the totality of all the codes in a system. That system may be SNOMED-CT or LOINC or even a system you create for yourself. Let's use an analogy to help explain.

I love Allen's lollies. Let's imagine that each different lolly is a code. We have RipeRaspberries, Pineapples, MilkBottles, Snakes and all of the other Allen's lollies. If we listed the entire catalogue of Allen's lollies with a description for each, the date the list was put together, the lists publisher details and more then this would be the CodeSystem.

The CodeSystem does not get used by the consumers, it is just the reference catalogue for all Allen's lollies, so if you want to find out more about the code 'RipeRaspberrie' then you would go to the CodeSystem. What a consumer uses is a ValueSet, because a ValueSet adds value to the consumer. In our lolly analogy, the ValueSet is the packet of lollies you buy, like the Party Mix or the bag of lollies you choose because they're your favourites. This is a ValueSet because it serves a purpose. It is a selection of codes from the CodeSystem to be used for a purpose.

A ValueSet is not limited to a single CodeSystem just as our bag of lollies is not limited to Allen's lollies. I'm also quite fond of Smarties, but only Red and Blue ones, from the Smarties CodeSystem, and also a few RedSkins from the Wonka CodeSystem. All of these can go into my same lolly bag which is a single ValueSet.

Next, we will look at the FHIR resources used for these concepts which are also named CodeSystem and ValueSet.

ValueSet и CodeSystem

Этот урок охватывает основы ресурсов ValueSet и CodeSystem, которые являются двумя из трех ключевых ресурсов для работы с терминологией в FHIR; третьим является ConceptMap.

Шаг 1: Что такое ValueSet и CodeSystem

В здравоохранении мы используем множество кодов из различных наборов кодов. У нас есть относительно простые, такие как пол пациента, и более сложные, такие как аллергии и побочные реакции, а также более административные, такие как коды учреждений или коды выставления счетов. FHIR не может определить каждый необходимый код и набор кодов для каждой системы здравоохранения по всему миру. Вместо этого FHIR предоставляет механизм для управления кодами и наборами кодов, и этим механизмом являются ресурсы CodeSystem и ValueSet.

CodeSystem и ValueSet в FHIR работают рука об руку для управления терминологией в FHIR. Эти два ресурса настолько тесно связаны, что в ранних версиях FHIR они фактически были одним ресурсом. Однако с версии STU3 FHIR они были разделены. Здесь мы сначала объясним концепции, лежащие в основе CodeSystem и ValueSet, а затем рассмотрим ресурсы FHIR, которые их воплощают.

Лучше всего начать с объяснения CodeSystem, поскольку это основа, на которой затем создаются ValueSet. Вы можете думать о CodeSystem как о главном каталоге определенного набора кодов. Это совокупность всех кодов в системе. Эта система может быть SNOMED-CT или LOINC, или даже система, которую вы создаете для себя. Давайте используем аналогию для объяснения.

Я люблю конфеты Allen's. Давайте представим, что каждая разная конфета - это код. У нас есть RipeRaspberries, Pineapples, MilkBottles, Snakes и все остальные конфеты Allen's. Если бы мы перечислили весь каталог конфет Allen's с описанием для каждой, датой составления списка, деталями издателя списка и многим другим, то это был бы CodeSystem.

CodeSystem не используется потребителями напрямую, это просто справочный каталог всех конфет Allen's, поэтому если вы хотите узнать больше о коде 'RipeRaspberries', то вы обратитесь к CodeSystem. То, что использует потребитель, это ValueSet, потому что ValueSet добавляет ценность для потребителя. В нашей аналогии с конфетами ValueSet - это пакет конфет, который вы покупаете, например Party Mix или пакет конфет, который вы выбираете, потому что они ваши любимые. Это ValueSet, потому что он служит цели. Это выборка кодов из CodeSystem для использования в определенных целях.

ValueSet не ограничен одним CodeSystem, так же как наш пакет конфет не ограничен конфетами Allen's. Я также довольно люблю Smarties, но только красные и синие, из CodeSystem Smarties, а также несколько RedSkins из CodeSystem Wonka. Все это может попасть в мой же пакет конфет, который является единым ValueSet.

Далее мы рассмотрим ресурсы FHIR, используемые для этих концепций, которые также называются CodeSystem и ValueSet.

Step 2: CodeSystem the FHIR Resource

Let's take a closer look at the FHIR resource named CodeSystem, you will find the resource page in the FHIR specification here:

Below is a simple example of a CodeSystem FHIR resource

The example below only contains two codes 'easy' and 'hard'. What is important for you at this stage is to grasp the basic structure of the resource. Notice that the top section (lines 8 to 20), like all FHIR resources, is a narrative HTML representation of the CodeSystem. The middle section (lines 21 to 37) is all the metadata about the CodeSystem, things like the version, a name and description for the CodeSystem, its status, whether it is experimental or not, who is the publisher and whether the codes are case sensitive. The last section (lines 38 to 45) are the actual codes each in their own <concept> element.

Don't forget, the CodeSystem is a catalogue of codes to be selected in ValueSets.

Шаг 2: CodeSystem - ресурс FHIR

Давайте внимательнее рассмотрим ресурс FHIR под названием CodeSystem, страницу ресурса в спецификации FHIR вы найдете здесь:

Ниже приведен простой пример ресурса CodeSystem FHIR

Пример ниже содержит только два кода 'easy' и 'hard'. Важно для вас на этом этапе понять базовую структуру ресурса. Обратите внимание, что верхняя секция (строки 8-20), как и все ресурсы FHIR, является нарративным HTML-представлением CodeSystem. Средняя секция (строки 21-37) содержит все метаданные о CodeSystem, такие как версия, имя и описание CodeSystem, его статус, является ли он экспериментальным или нет, кто является издателем и чувствительны ли коды к регистру. Последняя секция (строки 38-45) содержит фактические коды, каждый в своем элементе <concept>.

Не забывайте, CodeSystem - это каталог кодов для выбора в ValueSet.

This example does not show every property of a CodeSystem resource. I've only used the ones I thought were key while also trying to keep the example nice and short. Take a look at CodeSystem in the FHIR specification to see all the properties available.

Этот пример не показывает все свойства ресурса CodeSystem. Я использовал только те, которые считал ключевыми, стараясь при этом сохранить пример коротким и понятным. Посмотрите на CodeSystem в спецификации FHIR, чтобы увидеть все доступные свойства.

Step 3: ValueSet the FHIR Resources

Let's take a closer look at the FHIR resource named ValueSet, you will find the resource page in the FHIR specification here:

Here is a simple example of a ValueSet FHIR resource

This ValueSet resource below selects codes from the CodeSystem example we looked at in Step 2. Notice that this ValueSet selects both the 'easy' and 'hard' codes from the CodeSystem.

Please notice how the the CodeSystem is referenced in the ValueSet using the 'compose/include/system/@value' which points to the GUID seen in the CodeSystem's 'url' property. Take special note of this 'url' property as it is not the resource id or the URL to the FHIR resource in the server. Rather, it is a property of the CodeSystem resource. This 'url' is intended to be globally unique, so the same CodeSystem can be in any number of servers and can always be found by this 'url', not by the resource id.

Remember the ValueSet is free to pick and choose whichever codes it requires from the CodeSystem, it could even select more codes from another CodeSystem if required.

Шаг 3: ValueSet - ресурс FHIR

Давайте внимательнее рассмотрим ресурс FHIR под названием ValueSet, страницу ресурса в спецификации FHIR вы найдете здесь:

Вот простой пример ресурса ValueSet FHIR

Этот ресурс ValueSet ниже выбирает коды из примера CodeSystem, который мы рассмотрели в Шаге 2. Обратите внимание, что этот ValueSet выбирает оба кода 'easy' и 'hard' из CodeSystem.

Пожалуйста, обратите внимание на то, как CodeSystem ссылается в ValueSet с использованием 'compose/include/system/@value', который указывает на GUID, видимый в свойстве 'url' CodeSystem. Обратите особое внимание на это свойство 'url', поскольку это не идентификатор ресурса и не URL к ресурсу FHIR на сервере. Скорее, это свойство ресурса CodeSystem. Этот 'url' предназначен для глобальной уникальности, поэтому один и тот же CodeSystem может находиться на любом количестве серверов и всегда может быть найден по этому 'url', а не по идентификатору ресурса.

Помните, что ValueSet свободен выбирать любые коды, которые ему требуются из CodeSystem, он может даже выбрать больше кодов из другого CodeSystem, если это необходимо.

Remember, a ValueSet is a grouping of codes, codes are taken from CodeSystems, to be used for a purpose. ValueSet codes adds value to some use case, for example: a clinical systems drop down box to select an allergy.

Once again you should go to the FHIR specification page for ValueSet to see the full list of properties available.

Question: If you had two copies of a ValueSet resource given to you, from different people, how would you determine that the two instances were actually the same ValueSet?

CSIRO's Snapper

Snapper is an online tool developed by the CSIRO team that created the ONTO FHIR Terminology server. The tool provides a friendly user interface for creating and editing FHIR CodeSystems, ValueSets and ConceptMaps rather than having you fiddle with XML or JSON. Your finished resource can then be downloaded locally or published directly into an FHIR server of you choosing. This free tool can be found here: Snapper

Помните, ValueSet - это группировка кодов, коды берутся из CodeSystems для использования в определенных целях. Коды ValueSet добавляют ценность для некоторого случая использования, например: выпадающий список клинической системы для выбора аллергии.

Еще раз вам следует перейти на страницу спецификации FHIR для ValueSet, чтобы увидеть полный список доступных свойств.

Вопрос: Если бы вам дали две копии ресурса ValueSet от разных людей, как бы вы определили, что эти два экземпляра на самом деле являются одним и тем же ValueSet?

Snapper от CSIRO

Snapper - это онлайн-инструмент, разработанный командой CSIRO, которая создала терминологический сервер ONTO FHIR. Инструмент предоставляет дружественный пользовательский интерфейс для создания и редактирования FHIR CodeSystems, ValueSets и ConceptMaps, вместо того чтобы заставлять вас возиться с XML или JSON. Ваш готовый ресурс затем может быть загружен локально или опубликован непосредственно на FHIR-сервере по вашему выбору. Этот бесплатный инструмент можно найти здесь: Snapper

Step 4: Understanding how ValueSet codes are stored

It is easy to fall into the trap of thinking that the code information you list in a ValueSet will be exactly the same code information used when a ValueSet is called upon by a system. This isn't the case, however, as the codes stored in a ValueSet actually belong to a CodeSystem - a valueset instance only contains the 'links' to the actual codes in a codesystem. Thus when a codesystem's codes are updated, the valuesets containing these codes will contain the updated codes automatically. This is demonstrated well by one of the primary uses of a ValueSet: getting a list of codes to present to a user as specified by the links in the valueset, this is done with a special operation on the FHIR Terminology Server called '$expand'. This is known as ValueSet Expansion or ValueSet enumeration.

We are not going to go into how to perform an expansion now (see step 6 for that), but you do need to know what happens in the FHIR Terminology Server when an expansion is performed as it is key to your understanding.

As seen in this first diagram (you can click to enlarge) a developer calls the '$expand' operation on a given ValueSet because they want the list of codes and descriptions to display to a user. As we have seen, the ValueSet has a list of codes and it knows the CodeSystems for each code.

Шаг 4: Понимание того, как хранятся коды ValueSet

Легко попасть в ловушку, думая, что информация о кодах, которую вы перечисляете в ValueSet, будет точно такой же информацией о кодах, используемой, когда ValueSet вызывается системой. Однако это не так, поскольку коды, хранящиеся в ValueSet, фактически принадлежат CodeSystem - экземпляр valueset содержит только 'ссылки' на фактические коды в codesystem. Таким образом, когда коды codesystem обновляются, valuesets, содержащие эти коды, будут автоматически содержать обновленные коды. Это хорошо демонстрируется одним из основных применений ValueSet: получение списка кодов для представления пользователю, как указано ссылками в valueset, это делается с помощью специальной операции на FHIR Terminology Server, называемой '$expand'. Это известно как ValueSet Expansion или ValueSet enumeration.

Мы не будем сейчас углубляться в то, как выполнить расширение (см. шаг 6 для этого), но вам нужно знать, что происходит в FHIR Terminology Server при выполнении расширения, поскольку это ключ к вашему пониманию.

Как видно на этой первой диаграмме (вы можете нажать для увеличения), разработчик вызывает операцию '$expand' на данном ValueSet, потому что он хочет получить список кодов и описаний для отображения пользователю. Как мы видели, ValueSet имеет список кодов и знает CodeSystems для каждого кода.

The FHIR terminology server does not just return the codes in the ValueSet, what it does is reference the CodeSystems as listed for each code in the ValueSet and retrieves the information about the code from the CodeSystem resource in real-time and returns this back to the developer as an expanded ValueSet.

FHIR terminology server не просто возвращает коды в ValueSet, он ссылается на CodeSystems, как указано для каждого кода в ValueSet, и получает информацию о коде из ресурса CodeSystem в реальном времени и возвращает это разработчику как расширенный ValueSet.

What this means is that the ValueSet is only a reference to the codes in the CodeSystem. A key point here is that if the code description was updated in the CodeSystem then a ValueSet expansion will pick up the new description even though the ValueSet was never modified. You can control this by supplying version element alongside the codesystem's canonical URL.

Это означает, что ValueSet является только ссылкой на коды в CodeSystem. Ключевой момент здесь заключается в том, что если описание кода было обновлено в CodeSystem, то расширение ValueSet подхватит новое описание, даже если ValueSet никогда не изменялся. Вы можете контролировать это, давая версию CodeSystem вместе с canonical URL.

Step 5: Creating ValueSets using filters (Include, Exclude and Filter)

In the previous 'Step 4: Understanding how ValueSet codes are used' we learnt that ValueSets only select codes from CodeSystems. In our simple ValueSet example we selected, or rather 'Included', our codes by stating the actual code values 'easy' and 'hard' as they were seen in our CodeSystem. Yet, there is another way to select codes for inclusion in the ValueSet which is by using a filter.

We will avoid deep diving on filters but it is worth noting they exist and can be used. Typically a filter would be used when the code system being used has a hierarchical structure, meaning each code can have a parent or children codes such as the LOINC code system or even a poly-hierarchical system where codes can have many parents and many children codes such as SNOMED-CT.

With hierarchical code systems, we can use a filter to say "include all codes under this parent code". This way, as new codes are introduced under a parent code, in the code system, they will automatically be included in our ValueSet's selected codes. In the very same way we can include codes, we can also exclude codes either by stating the code to exclude or by using another filter.

The image below is taken from the ValueSet tree structure in the FHIR specification and highlights the sections that deals with the topic discussed in this step (Include, Exclude & Filter).

Шаг 5: Создание ValueSet с использованием фильтров (Include, Exclude и Filter)

В предыдущем 'Шаге 4: Понимание того, как используются коды ValueSet' мы узнали, что ValueSet только выбирают коды из CodeSystems. В нашем простом примере ValueSet мы выбрали, или скорее 'Включили', наши коды, указав фактические значения кодов 'easy' и 'hard', как они были видны в нашем CodeSystem. Однако есть другой способ выбрать коды для включения в ValueSet - это использование фильтра.

Мы избежим глубокого погружения в фильтры, но стоит отметить, что они существуют и могут быть использованы. Обычно фильтр используется, когда используемая система кодов имеет иерархическую структуру, что означает, что каждый код может иметь родительский или дочерние коды, такие как система кодов LOINC, или даже поли-иерархическую систему, где коды могут иметь много родителей и много дочерних кодов, такую как SNOMED-CT.

С иерархическими системами кодов мы можем использовать фильтр, чтобы сказать "включить все коды под этим родительским кодом". Таким образом, когда новые коды вводятся под родительским кодом в системе кодов, они автоматически будут включены в выбранные коды нашего ValueSet. Точно так же, как мы можем включать коды, мы также можем исключать коды, либо указав код для исключения, либо используя другой фильтр.

Изображение ниже взято из древовидной структуры ValueSet в спецификации FHIR и выделяет разделы, которые касаются темы, обсуждаемой в этом шаге (Include, Exclude и Filter).