

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 中管理 FHIR 資源 AWS HealthLake
<a name="managing-fhir-resources"></a>

使用 FHIR R4 RESTful API 互動來管理 HealthLake 資料存放區中的 FHIR 資源。下列各節說明可用於 FHIR 資源管理的所有 HealthLake 支援的 FHIR R4 RESTful API 互動。如需 HealthLake 資料存放區功能及其支援哪些 FHIR 規格部分的相關資訊，請參閱 [的 FHIR R4 功能陳述式 AWS HealthLake](reference-fhir-capability-statement.md)。

**注意**  
本章列出的 FHIR 互動是根據 HL7 FHIR R4 標準的醫療保健資料交換而建置。由於它們是 HL7 FHIR 服務的表示，因此不會透過 AWS CLI 和 AWS SDKs提供。如需詳細資訊，請參閱 FHIR [R4 RESTful API](https://hl7.org/fhir/R4/http.html) 文件中的 RESTful API。 ** R4 RESTful **

下表列出 支援的 FHIR R4 互動 AWS HealthLake。如需 HealthLake 支援的 FHIR *資源類型*相關資訊，請參閱 [資源類型](reference-fhir-resource-types.md)。




**支援的 FHIR R4 互動 AWS HealthLake**  
<a name="supported-fhir-interactions"></a>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/healthlake/latest/devguide/managing-fhir-resources.html)

**Topics**
+ [建立 FHIR 資源](managing-fhir-resources-create.md)
+ [讀取 FHIR 資源](managing-fhir-resources-read.md)
+ [讀取 FHIR 資源歷史記錄](managing-fhir-resources-read-history.md)
+ [更新 FHIR 資源](managing-fhir-resources-update.md)
+ [使用 PATCH 操作修改資源](managing-fhir-resources-patch.md)
+ [綁定 FHIR 資源](managing-fhir-resources-bundle.md)
+ [刪除 FHIR 資源](managing-fhir-resources-delete.md)
+ [冪等和並行](managing-fhir-resources-idempotency.md)

# 建立 FHIR 資源
<a name="managing-fhir-resources-create"></a>

FHIR `create`互動會在 HealthLake 資料存放區中建立新的 FHIR 資源。如需詳細資訊，請參閱 **FHIR R4 RESTful API 文件**[https://hl7.org/fhir/R4/http.html#create](https://hl7.org/fhir/R4/http.html#create)中的 。

**建立 FHIR 資源**  


1. 收集 HealthLake `region`和 `datastoreId` 值。如需詳細資訊，請參閱[取得資料存放區屬性](managing-data-stores-describe.md)。

1. 決定`Resource`要建立的 FHIR 類型。如需詳細資訊，請參閱[資源類型](reference-fhir-resource-types.md)。

1. 使用 HealthLake `region`和 的收集值來建構請求的 URL`datastoreId`。同時包含要建立的 FHIR `Resource`類型。若要在下列範例中檢視整個 URL 路徑，請捲動至**複製**按鈕。

   ```
   POST https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Resource
   ```

1. 為請求建構 JSON 內文，並指定新資源的 FHIR 資料。基於此程序的目的，我們使用 FHIR `Patient` 資源，因此請將檔案儲存為 `create-patient.json`。

   ```
   {
       "resourceType": "Patient",
       "identifier": [
           {
               "system": "urn:oid:1.2.36.146.595.217.0.1",
               "value": "12345"
           }
       ],
       "name": [
           {
               "family": "Silva",
               "given": [
                   "Ana",
                   "Carolina"
               ]
           }
       ],
       "gender": "female",
       "birthDate": "1992-02-10"
   }
   ```

1. 傳送 請求。FHIR `create`互動使用具有[AWS 簽章第 4 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html)版或 FHIR 授權上的 SMART 的`POST`請求。下列範例會使用 curl 或 HealthLake 主控台在 HealthLake 中建立 FHIR `Patient` 資源。若要檢視整個範例，請捲動至**複製**按鈕。

------
#### [ SigV4 ]

   SigV4 授權

   ```
   curl --request POST \
     'https://healthlake.region.amazonaws.com/datastore/datastore-id/r4/Patient' \
     --aws-sigv4 'aws:amz:region:healthlake' \
     --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
     --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
     --header 'Accept: application/json' \
     --data @create-patient.json
   ```

------
#### [ SMART on FHIR ]

   [https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html](https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html) 資料類型的 FHIR 上的 SMART 授權範例。

   ```
   {
       "AuthorizationStrategy": "SMART_ON_FHIR",
       "FineGrainedAuthorizationEnabled": true,
       "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
       "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\",\"permission-v2\"]}"
   }
   ```

   發起人可以在授權 lambda 中指派許可。如需詳細資訊，請參閱[OAuth 2.0 範圍](reference-smart-on-fhir-oauth-scopes.md)。

------
#### [ AWS Console ]

**注意**  
HealthLake 主控台僅支援 [AWS SigV4](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html) 授權。

   1. 登入 HealthLake 主控台上的[執行查詢](https://console.aws.amazon.com/healthlake/home#/crud)頁面。

   2. 在**查詢設定**區段下，進行下列選擇。
   + **資料存放區 ID** — 選擇資料存放區 ID 以產生查詢字串。
   + **查詢類型** — 選擇 `Create`。
   + **資源類型** — 選擇要建立的 FHIR [資源類型](reference-fhir-resource-types.md)。
   + **請求內文** - 建構請求的 JSON 內文，指定新資源的 FHIR 資料。

   3. 選擇 **Run query** (執行查詢)。

------

**設定資源建立的驗證層級**  


建立 FHIR 資源時，您可以選擇指定 `x-amzn-healthlake-fhir-validation-level` HTTP 標頭來設定資源的驗證層級。 AWS HealthLake 目前支援下列驗證層級：
+ `strict`：資源會根據資源的設定檔元素進行驗證，如果沒有設定檔，則為 R4 規格。這是 的預設驗證層級 AWS HealthLake。
+ `structure-only`：資源會根據 R4 驗證，忽略任何參考的設定檔。
+ `minimal`：最少驗證資源，忽略某些 R4 規則。搜尋/分析所需的結構檢查失敗的資源將更新為包含稽核警告。

雖然搜尋索引所需的驗證失敗，但使用最低驗證層級建立的資源仍可能會擷取至資料存放區。在這種情況下，資源將更新為包含 Healthlake 特定的延伸，以記錄上述失敗：

```
{
    "url": "http://healthlake.amazonaws.com/fhir/StructureDefinition/validation-issue",
    "valueString": "{\"resourceType\":\"OperationOutcome\",\"issue\":[{\"severity\":\"error\",\"code\":\"processing\",\"details\":{\"text\":\"FHIR resource in payload failed FHIR validation rules.\"},\"diagnostics\":\"FHIR resource in payload failed FHIR validation rules.\"}]}"
}
```

此外，以下 HTTP 回應標頭會包含在「true」的值中：

```
x-amzn-healthlake-validation-issues : true
```

**注意**  
如果存在這些錯誤，則可能無法如預期搜尋根據 R4 規格格式不正確擷取的資料。

# 讀取 FHIR 資源
<a name="managing-fhir-resources-read"></a>

FHIR `read`互動會讀取 HealthLake 資料存放區中資源的目前狀態。如需詳細資訊，請參閱 **FHIR R4 RESTful API 文件**[https://hl7.org/fhir/R4/http.html#read](https://hl7.org/fhir/R4/http.html#read)中的 。

**讀取 FHIR 資源**  


1. 收集 HealthLake `region`和 `datastoreId` 值。如需詳細資訊，請參閱[取得資料存放區屬性](managing-data-stores-describe.md)。

1. 決定`Resource`要讀取和收集相關聯`id`值的 FHIR 類型。如需詳細資訊，請參閱[資源類型](reference-fhir-resource-types.md)。

1. 使用 HealthLake `region`和 的收集值來建構請求的 URL`datastoreId`。同時包含 FHIR `Resource`類型及其相關聯的 `id`。若要在下列範例中檢視整個 URL 路徑，請捲動至**複製**按鈕。

   ```
   GET https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Resource/id
   ```

1. 傳送 請求。FHIR `read`互動使用具有[AWS 簽章第 4 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html)版或 FHIR 授權上的 SMART 的`GET`請求。下列`curl`範例會讀取 HealthLake 中 FHIR `Patient` 資源的目前狀態。若要檢視整個範例，請捲動至**複製**按鈕。

------
#### [ SigV4 ]

   SigV4 授權

   ```
   curl --request GET \
     'https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Patient/id' \
     --aws-sigv4 'aws:amz:region:healthlake' \
     --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
     --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
     --header 'Accept: application/json'
   ```

------
#### [ SMART on FHIR ]

   [https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html](https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html) 資料類型的 FHIR 上的 SMART 授權範例。

   ```
   {
       "AuthorizationStrategy": "SMART_ON_FHIR",
       "FineGrainedAuthorizationEnabled": true,
       "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
       "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\",\"permission-v2\"]}"
   }
   ```

   發起人可以在授權 lambda 中指派許可。如需詳細資訊，請參閱[OAuth 2.0 範圍](reference-smart-on-fhir-oauth-scopes.md)。

------
#### [ AWS Console ]

   1. 登入 HealthLake 主控台上的[執行查詢](https://console.aws.amazon.com/healthlake/home#/crud)頁面。

   2. 在**查詢設定**區段下，進行下列選擇。
   + **資料存放區 ID** — 選擇資料存放區 ID 以產生查詢字串。
   + **查詢類型** — 選擇 `Read`。
   + **資源類型** — 選擇要讀取的 FHIR [資源類型](reference-fhir-resource-types.md)。
   + **資源 ID** — 輸入 FHIR 資源 ID。

   3. 選擇 **Run query** (執行查詢)。

------

# 讀取 FHIR 資源歷史記錄
<a name="managing-fhir-resources-read-history"></a>

FHIR `history`互動會擷取 HealthLake 資料存放區中特定 FHIR 資源的歷史記錄。使用此互動，您可以判斷 FHIR 資源的內容如何隨時間變更。在協調稽核日誌時，查看修改前後的資源狀態也很有用。FHIR 互動 `create`、 `update`和 `delete`會產生要儲存的歷史資源版本。如需詳細資訊，請參閱 **FHIR R4 RESTful API 文件**[https://hl7.org/fhir/R4/http.html#history](https://hl7.org/fhir/R4/http.html#history)中的 。

**注意**  
您可以選擇不`history`接收特定 FHIR 資源類型。若要選擇退出，請使用 建立案例[AWS Support Center Console](https://console.aws.amazon.com/support/home#/)。若要建立您的案例，請登入您的 AWS 帳戶 ，然後選擇**建立案例**。

**讀取 FHIR 資源歷史記錄**  


1. 收集 HealthLake `region`和 `datastoreId` 值。如需詳細資訊，請參閱[取得資料存放區屬性](managing-data-stores-describe.md)。

1. 決定`Resource`要讀取和收集相關聯`id`值的 FHIR 類型。如需詳細資訊，請參閱[資源類型](reference-fhir-resource-types.md)。

1. 使用 HealthLake `region`和 的收集值來建構請求的 URL`datastoreId`。也包括 FHIR `Resource`類型、其相關聯的 `id`，以及選用的搜尋參數。若要在下列範例中檢視整個 URL 路徑，請捲動至**複製**按鈕。

   ```
   GET https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Resource/id/_history{?[parameters]}
   ```  
**HealthLake 支援的 FHIR `history`互動搜尋參數**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/healthlake/latest/devguide/managing-fhir-resources-read-history.html)

1. 傳送 請求。FHIR `history`互動使用具有[AWS 簽章第 4 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html)版或 FHIR 授權上的 SMART 的`GET`請求。下列`curl`範例使用`_count`搜尋參數，針對 HealthLake 中的 FHIR `Patient` 資源傳回每頁 100 個歷史搜尋結果。若要檢視整個範例，請捲動至**複製**按鈕。

------
#### [ SigV4 ]

   SigV4 授權

   ```
   curl --request GET \
     'https://healthlake.region.amazonaws.com/datastore/datastore-id/r4/Patient/id/_history?_count=100' \
     --aws-sigv4 'aws:amz:region:healthlake' \
     --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
     --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
     --header 'Accept: application/json'
   ```

------
#### [ SMART on FHIR ]

   [https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html](https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html) 資料類型的 FHIR 上的 SMART 授權範例。

   ```
   {
       "AuthorizationStrategy": "SMART_ON_FHIR",
       "FineGrainedAuthorizationEnabled": true,
       "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
       "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\",\"permission-v2\"]}"
   }
   ```

   發起人可以在授權 lambda 中指派許可。如需詳細資訊，請參閱[OAuth 2.0 範圍](reference-smart-on-fhir-oauth-scopes.md)。

------

   `history` 互動的傳回內容包含在 FHIR 資源 中`Bundle`，類型設定為 `history`。它包含指定的版本歷史記錄，最後以最舊的版本排序，並包含已刪除的資源。如需詳細資訊，請參閱 **FHIR R4 文件**[https://hl7.org/fhir/R4/bundle.html](https://hl7.org/fhir/R4/bundle.html)中的 。

## 讀取版本特定的 FHIR 資源歷史記錄
<a name="managing-fhir-data-get-version-specific-resource"></a>

FHIR `vread`互動會對 HealthLake 資料存放區中的資源執行版本特定讀取。使用此互動，您可以像過去特定時間一樣檢視 FHIR 資源的內容。

**注意**  
如果您在*不使用* 的情況下使用 FHIR `history`互動`vread`，HealthLake 一律會傳回資源中繼資料的最新版本。

HealthLake 宣告支援[https://hl7.org/fhir/R4/capabilitystatement-definitions.html#CapabilityStatement.rest.resource.versioning](https://hl7.org/fhir/R4/capabilitystatement-definitions.html#CapabilityStatement.rest.resource.versioning)針對每個支援的資源在 中進行版本控制。所有 HealthLake 資料存放區在所有資源上都包含 `Resource.meta.versionId`(`vid`)。

啟用 FHIR `history`互動時 （預設為 10/25/2024 之後建立的資料存放區，或請求較舊的資料存放區），`Bundle`回應會包含 `vid`作為 [https://hl7.org/fhir/R4/bundle-definitions.html#Bundle.entry.response.location](https://hl7.org/fhir/R4/bundle-definitions.html#Bundle.entry.response.location)元素的一部分。在下列範例中， `vid`會顯示為數字 `1`。若要檢視完整範例，請參閱 [Bundle/bundle-response (JSON) 範例](https://build.fhir.org/bundle-response.json.html)。

```
"response" : {
    "status" : "201 Created",
    "location" : "Patient/12423/_history/1",
    ...}
```

**讀取版本特定的 FHIR 資源歷史記錄**  


1. 收集 HealthLake `region`和 `datastoreId` 值。如需詳細資訊，請參閱[取得資料存放區屬性](managing-data-stores-describe.md)。

1. 決定要讀取和收集相關聯 `id` 和 `vid`值的 FHIR `Resource`類型。如需詳細資訊，請參閱[資源類型](reference-fhir-resource-types.md)。

1. 使用針對 HealthLake 和 FHIR 收集的值來建構請求的 URL。若要在下列範例中檢視整個 URL 路徑，請捲動至**複製**按鈕。

   ```
   GET https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Resource/id/_history/vid
   ```

1. 傳送 請求。FHIR `history`互動使用具有[AWS 簽章第 4 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html)版或 FHIR 授權上的 SMART 的`GET`請求。下列`vread`互動會針對 指定的資源中繼資料版本，傳回具有 FHIR `Patient` 資源指定內容的單一執行個體`vid`。若要在下列範例中檢視整個 URL 路徑，請捲動至**複製**按鈕。

------
#### [ SigV4 ]

   SigV4 授權

   ```
   curl --request GET \
     'https://healthlake.region.amazonaws.com/datastore/datastore-id/r4/Patient/id/_history/vid' \
     --aws-sigv4 'aws:amz:region:healthlake' \
     --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
     --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
     --header 'Accept: application/json'
   ```

------
#### [ SMART on FHIR ]

   [https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html](https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html) 資料類型的 FHIR 上的 SMART 授權範例。

   ```
   {
       "AuthorizationStrategy": "SMART_ON_FHIR",
       "FineGrainedAuthorizationEnabled": true,
       "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
       "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\",\"permission-v2\"]}"
   }
   ```

   發起人可以在授權 lambda 中指派許可。如需詳細資訊，請參閱[OAuth 2.0 範圍](reference-smart-on-fhir-oauth-scopes.md)。

------

# 更新 FHIR 資源
<a name="managing-fhir-resources-update"></a>

FHIR `update`互動會為現有資源建立新的目前版本，如果指定的 尚不存在資源，則會建立初始版本`id`。如需詳細資訊，請參閱 **FHIR R4 RESTful API 文件**[https://hl7.org/fhir/R4/http.html#update](https://hl7.org/fhir/R4/http.html#update)中的 。

**更新 FHIR 資源**  


1. 收集 HealthLake `region`和 `datastoreId` 值。如需詳細資訊，請參閱[取得資料存放區屬性](managing-data-stores-describe.md)。

1. 決定`Resource`要更新並收集相關聯`id`值的 FHIR 類型。如需詳細資訊，請參閱[資源類型](reference-fhir-resource-types.md)。

1. 使用 HealthLake `region`和 的收集值來建構請求的 URL`datastoreId`。同時包含 FHIR `Resource`類型及其相關聯的 `id`。若要在下列範例中檢視整個 URL 路徑，請捲動至**複製**按鈕。

   ```
   PUT https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Resource/id
   ```

1. 為請求建構`JSON`內文，指定要進行的 FHIR 資料更新。基於此程序的目的，請將檔案儲存為 `update-patient.json`。

   ```
   {
       "id": "2de04858-ba65-44c1-8af1-f2fe69a977d9",
       "resourceType": "Patient",
       "active": true,
       "name": [
           {
               "use": "official",
               "family": "Doe",
               "given": [
                   "Jane"
               ]
           },
           {
               "use": "usual",
               "given": [
                   "Jane"
               ]
           }
       ],
       "gender": "female",
       "birthDate": "1985-12-31"
   }
   ```

1. 傳送 請求。FHIR `update`互動使用具有[AWS 簽章第 4 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html)版或 FHIR 授權上的 SMART 的`PUT`請求。下列`curl`範例會更新 HealthLake 中的`Patient`資源。若要檢視整個範例，請捲動至**複製**按鈕。

------
#### [ SigV4 ]

   SigV4 授權

   ```
   curl --request PUT \
     'https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Patient/id' \
     --aws-sigv4 'aws:amz:region:healthlake' \
     --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
     --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
     --header 'Accept: application/json' \
     --data @update-patient.json
   ```

   如果現有資源*已更新*，您的請求將傳回 `200` HTTP 狀態碼，如果建立新資源，則傳回 `201` HTTP 狀態碼。

------
#### [ SMART on FHIR ]

   [https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html](https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html) 資料類型的 FHIR 上的 SMART 授權範例。

   ```
   {
       "AuthorizationStrategy": "SMART_ON_FHIR",
       "FineGrainedAuthorizationEnabled": true,
       "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
       "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\",\"permission-v2\"]}"
   }
   ```

   發起人可以在授權 lambda 中指派許可。如需詳細資訊，請參閱[OAuth 2.0 範圍](reference-smart-on-fhir-oauth-scopes.md)。

------
#### [ AWS Console ]

   1. 登入 HealthLake 主控台上的[執行查詢](https://console.aws.amazon.com/healthlake/home#/crud)頁面。

   2. 在**查詢設定**區段下，進行下列選擇。
   + **資料存放區 ID** — 選擇資料存放區 ID 以產生查詢字串。
   + **查詢類型** — 選擇 `Update (PUT)`。
   + **資源類型** — 選擇要更新或建立的 FHIR [資源類型](reference-fhir-resource-types.md)。
   + **請求內文** - 建構請求的 JSON 內文，指定要更新資源的 FHIR 資料。

   3. 選擇 **Run query** (執行查詢)。

------

## 根據條件更新 FHIR 資源
<a name="managing-fhir-resources-update-conditional"></a>

條件式更新可讓您根據某些識別搜尋條件更新現有資源，而不是透過邏輯 FHIR `id`。當伺服器處理更新時，它會針對 資源類型使用其標準搜尋功能執行搜尋，目標是解決請求`id`的單一邏輯。

伺服器採取的動作取決於找到多少相符項目：
+ **沒有相符項目，請求內文中未`id`提供**：伺服器會建立 FHIR 資源。
+ **不存在相符項目、`id`提供的和資源：`id`**伺服器會將互動視為更新為建立互動。
+ **沒有相符項目，`id`已提供且已存在**：伺服器拒絕更新時發生錯誤`409 Conflict`。
+ **One Match，未`id`提供資源 OR (`id`提供的資源，且符合找到的資源）**：伺服器會針對相符的資源執行更新，如上所示，如果資源已更新，伺服器 SHALL 會傳回 `200 OK`。
+ **One Match，`id`提供的資源，但不符合找到的資源**：伺服器傳回`409 Conflict`錯誤，指出用戶端 ID 規格是 的問題 `OperationOutcome`
+ **多個相符**項目：伺服器傳回`412 Precondition Failed`錯誤，指出用戶端的條件不夠選擇性，最好使用 OperationOutcome

下列範例會更新名稱為 peter `Patient`的資源，出生日期為 2000 年 1 月 1 日，電話號碼為 1234567890。

```
PUT https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Patient?name=peter&birthdate=2000-01-01&phone=1234567890
```

## 設定資源更新的驗證層級
<a name="validation-level-resource-updates"></a>

更新 FHIR 資源時，您可以選擇指定 `x-amzn-healthlake-fhir-validation-level` HTTP 標頭來設定資源的驗證層級。 AWS HealthLake 目前支援下列驗證層級：
+ `strict`：資源會根據資源的設定檔元素進行驗證，如果沒有設定檔，則為 R4 規格。這是 的預設驗證層級 AWS HealthLake。
+ `structure-only`：資源會根據 R4 驗證，忽略任何參考的設定檔。
+ `minimal`：最少驗證資源，忽略某些 R4 規則。搜尋/分析所需的結構檢查失敗的資源將更新為包含稽核警告。

使用最低驗證層級更新的資源可能會擷取至資料存放區，即使搜尋索引所需的驗證失敗。在這種情況下，資源將更新為包含 Healthlake 特定的延伸，以記錄上述失敗：

```
{
    "url": "http://healthlake.amazonaws.com/fhir/StructureDefinition/validation-issue",
    "valueString": "{\"resourceType\":\"OperationOutcome\",\"issue\":[{\"severity\":\"error\",\"code\":\"processing\",\"details\":{\"text\":\"FHIR resource in payload failed FHIR validation rules.\"},\"diagnostics\":\"FHIR resource in payload failed FHIR validation rules.\"}]}"
}
```

此外，以下 HTTP 回應標頭會包含在「true」的值中：

```
x-amzn-healthlake-validation-issues : true
```

**注意**  
請注意，如果出現這些錯誤，根據 R4 規格格式不正確擷取的資料可能無法如預期搜尋。

# 使用 PATCH 操作修改資源
<a name="managing-fhir-resources-patch"></a>

AWS HealthLake 支援 FHIR 資源的 PATCH 操作，可讓您透過鎖定要新增、取代或刪除的特定元素來修改資源，而無需更新整個資源。當您需要執行下列動作時，此操作特別有用：
+ 對大型資源進行目標性更新
+ 減少網路頻寬用量
+ 對特定資源元素執行原子修改
+ 將覆寫並行變更的風險降至最低
+ 在批次和交易工作流程中更新資源

## 支援的修補程式格式
<a name="patch-supported-formats"></a>

AWS HealthLake 支援兩種標準 PATCH 格式：

### JSON 修補程式 (RFC 6902)
<a name="patch-format-json"></a>

使用 JSON 指標語法，依其在資源結構中的位置來鎖定元素。

**Content-Type：** `application/json-patch+json`

### FHIRPath 修補程式 (FHIR R4 規格）
<a name="patch-format-fhirpath"></a>

使用 FHIRPath 表達式，依其內容和關係來鎖定元素，提供 FHIR 原生的修補方法。

**Content-Type：** `application/fhir+json`

## Usage
<a name="patch-usage"></a>

### 直接修補操作
<a name="patch-usage-direct"></a>

您可以使用 PATCH HTTP 方法，直接在 FHIR 資源上叫用 PATCH 操作：

```
PATCH [base]/[resource-type]/[id]{?_format=[mime-type]}
```

### 套件中的 PATCH
<a name="patch-usage-bundles"></a>

PATCH 操作可以包含在類型 `batch`或 的 FHIR 套件中作為項目`transaction`，讓您能夠在單一請求中將修補程式操作與其他 FHIR 互動 （建立、讀取、更新、刪除） 結合。
+ **交易套件**：所有項目都會以原子方式成功或失敗
+ **批次套件**：每個項目都會獨立處理

## JSON 修補程式格式
<a name="patch-json-format"></a>

### 受支援的 操作
<a name="patch-json-supported-operations"></a>


| 作業 | Description | 
| --- | --- | 
| add | 將新值新增至資源 | 
| remove | 從資源移除值 | 
| replace | 取代 資源中的現有值 | 
| move | 從一個位置移除值，並將其新增至另一個位置 | 
| copy | 將值從一個位置複製到另一個位置 | 
| test | 測試目標位置的值是否等於指定的值 | 

### 路徑語法
<a name="patch-json-path-syntax"></a>

JSON 修補程式使用 JSON 指標語法 (RFC 6901)：


| 路徑範例 | Description | 
| --- | --- | 
| /name/0/family | 名字的系列元素 | 
| /telecom/- | 附加至電信陣列 | 
| /active | 根層級作用中元素 | 
| /address/0/line/1 | 第一地址的第二行 | 

### 範例
<a name="patch-json-examples"></a>

**具有多個操作的直接 JSON 修補程式請求**  


```
PATCH [base]/Patient/example
Content-Type: application/json-patch+json
If-Match: W/"1"

[
  {
    "op": "replace",
    "path": "/name/0/family",
    "value": "Smith"
  },
  {
    "op": "add",
    "path": "/telecom/-",
    "value": {
      "system": "phone",
      "value": "555-555-5555",
      "use": "home"
    }
  },
  {
    "op": "remove",
    "path": "/address/0"
  },
  {
    "op": "move",
    "from": "/name/0/family",
    "path": "/name/1/family"
  },
  {
    "op": "test",
    "path": "/gender",
    "value": "male"
  },
  {
    "op": "copy",
    "from": "/name/0",
    "path": "/name/1"
  }
]
```

**使用單一操作的直接 JSON 修補程式請求**  


```
PATCH [base]/Patient/example
Content-Type: application/json-patch+json

[
  {
    "op": "replace",
    "path": "/active",
    "value": false
  }
]
```

**套件中的 JSON 修補程式**  
使用包含 base64 編碼 JSON 修補程式承載的二進位資源：

```
{
  "resourceType": "Bundle",
  "type": "transaction",
  "entry": [{
    "resource": {
      "resourceType": "Binary",
      "contentType": "application/json-patch+json",
      "data": "W3sib3AiOiJhZGQiLCJwYXRoIjoiL2JpcnRoRGF0ZSIsInZhbHVlIjoiMTk5MC0wMS0wMSJ9XQ=="
    },
    "request": {
      "method": "PATCH",
      "url": "Patient/123"
    }
  }]
}
```

## FHIRPath 修補程式格式
<a name="patch-fhirpath-format"></a>

### 受支援的 操作
<a name="patch-fhirpath-supported-operations"></a>


| 作業 | Description | 
| --- | --- | 
| add | 將新元素新增至資源 | 
| insert | 在清單中的特定位置插入 元素 | 
| delete | 從資源移除 元素 | 
| replace | 取代現有元素的值 | 
| move | 重新排序清單中的元素 | 

### 路徑語法
<a name="patch-fhirpath-path-syntax"></a>

FHIRPath 修補程式使用 FHIRPath 表達式，支援：
+ **索引型存取**： `Patient.name[0]`
+ **使用 篩選`where()`**： `Patient.name.where(use = 'official')`
+ **布林值邏輯**： `Patient.telecom.where(system = 'phone' and use = 'work')`
+ **子設定函數**：`first()`、 `last()`
+ **存在性檢查**：`exists()`、 `count()`
+ **多態導覽**： `Observation.value`

### 範例
<a name="patch-fhirpath-examples"></a>

**Direct FHIRPath 修補程式請求**  


```
PATCH [base]/Patient/123
Content-Type: application/fhir+json
Authorization: ...

{
  "resourceType": "Parameters",
  "parameter": [{
    "name": "operation",
    "part": [
      { "name": "type", "valueCode": "add" },
      { "name": "path", "valueString": "Patient" },
      { "name": "name", "valueString": "birthDate" },
      { "name": "value", "valueDate": "1990-01-01" }
    ]
  }]
}
```

**套件中的 FHIRPath 修補程式**  
透過 使用參數資源做為項目資源`method: PATCH`：

```
{
  "resourceType": "Bundle",
  "type": "transaction",
  "entry": [{
    "resource": {
      "resourceType": "Parameters",
      "parameter": [{
        "name": "operation",
        "part": [
          { "name": "type", "valueCode": "add" },
          { "name": "path", "valueString": "Patient" },
          { "name": "name", "valueString": "birthDate" },
          { "name": "value", "valueDate": "1990-01-01" }
        ]
      }]
    },
    "request": {
      "method": "PATCH",
      "url": "Patient/123"
    }
  }]
}
```

## 請求標頭
<a name="patch-request-headers"></a>


| 標頭 | 必要 | 描述 | 
| --- | --- | --- | 
| Content-Type | 是 | application/json-patch\$1json 適用於 JSON 修補程式或application/fhir\$1json適用於 FHIRPath 修補程式 | 
| If-Match | 否 | 使用 ETag 的特定版本條件更新 | 

## 回應範例
<a name="patch-sample-response"></a>

操作會傳回具有新版本資訊的更新資源：

```
HTTP/1.1 200 OK
Content-Type: application/fhir+json
ETag: W/"2"
Last-Modified: Mon, 05 May 2025 10:10:10 GMT

{
  "resourceType": "Patient",
  "id": "example",
  "active": true,
  "name": [
    {
      "family": "Smith",
      "given": ["John"]
    }
  ],
  "telecom": [
    {
      "system": "phone",
      "value": "555-555-5555",
      "use": "home"
    }
  ],
  "meta": {
    "versionId": "2",
    "lastUpdated": "2025-05-05T10:10:10Z"
  }
}
```

## Behavior (行為)
<a name="patch-behavior"></a>

PATCH 操作：
+ 根據適當的規格驗證修補程式語法 (RFC 6902 for JSON Patch、FHIR R4 for FHIRPath Patch)
+ 以原子方式套用操作 - 所有操作成功或全部失敗
+ 更新資源版本 ID 並建立新的歷史記錄項目
+ 在套用變更之前，保留歷史記錄中的原始資源
+ 套用修補程式後驗證 FHIR 資源限制
+ 支援使用 If-Match 標頭搭配 ETag 進行條件式更新

## 錯誤處理
<a name="patch-error-handling"></a>

操作會處理下列錯誤條件：
+ **400 錯誤的請求**：無效的修補程式語法 （不符合的請求或格式錯誤的修補程式文件）
+ **找不到 404**：找不到資源 （指定的 ID 不存在）
+ **409 衝突**：版本衝突 （提供並行更新或非目前版本 ID)
+ **422 無法處理的實體**：修補程式操作無法套用至指定的資源元素

## 功能摘要
<a name="patch-summary-of-capabilities"></a>


| 功能 | JSON 修補程式 | FHIRPath 修補程式 | 
| --- | --- | --- | 
| 內容類型 | application/json-patch\$1json | application/fhir\$1json | 
| 路徑格式 | JSON 指標 (RFC 6901) | FHIRPath 表達式 | 
| Direct PATCH API | 支援 | 支援 | 
| 套件批次 | 支援 （透過二進位） | 支援 （透過參數） | 
| 套件交易 | 支援 （透過二進位） | 支援 （透過參數） | 
| 操作 | 新增、移除、取代、移動、複製、測試 | 新增、插入、刪除、取代、移動 | 

## 限制
<a name="patch-limitations"></a>
+ 不支援使用搜尋條件的條件式 PATCH 操作
+ 套件中的 JSON 修補程式必須使用具有 base64 編碼內容的二進位資源
+ 套件中的 FHIRPath 修補程式必須使用參數資源

## 其他資源
<a name="patch-additional-resources"></a>

如需 PATCH 操作的詳細資訊，請參閱：
+ [FHIR R4 修補文件](https://hl7.org/fhir/http.html#patch)
+ [FHIR R4 FHIRPath 修補程式規格](https://hl7.org/fhir/fhirpatch.html)
+ [RFC 6902 - JSON 修補程式](https://datatracker.ietf.org/doc/html/rfc6902#section-4)
+ [RFC 6901 - JSON 指標](https://datatracker.ietf.org/doc/html/rfc6901)

# 綁定 FHIR 資源
<a name="managing-fhir-resources-bundle"></a>

FHIR `Bundle`是 中 FHIR 資源集合的容器 AWS HealthLake。 AWS HealthLake 支援兩種具有不同處理行為的套件類型。

[https://hl7.org/fhir/R4/http.html#transaction](https://hl7.org/fhir/R4/http.html#transaction) 套件會獨立處理每個資源。如果某個資源失敗，剩餘的資源仍然可以成功。每個操作都會個別處理，即使某些操作失敗，也會繼續處理。將批次套件用於可接受部分成功的大量操作，例如上傳多個不相關的病患記錄。

[https://hl7.org/fhir/R4/http.html#transaction](https://hl7.org/fhir/R4/http.html#transaction) 套件會以原子方式將所有資源處理為單一單位。所有資源操作都會成功，或不會 AWS HealthLake 遞交任何操作。當您需要相關資源的保證參考完整性時，請使用交易套件，例如建立具有相關觀察和條件的患者，其中所有資料必須一起記錄。


**批次與交易套件之間的差異**  

| 功能 | 批次 | 交易 | 
| --- | --- | --- | 
| 處理模型 | 每個操作都會獨立成功或失敗。 | 所有操作都會以單一原子單位的形式成功或失敗。 | 
| 失敗處理 | 即使個別操作失敗，處理仍會繼續。 | 如果任何單一操作失敗，整個套件都會失敗。 | 
| 執行順序 | 不保證執行順序。 | 操作會依指定的順序處理。 | 
| 參考完整性 | 未跨 操作強制執行。 | 針對套件內的本機參考資源強制執行。 | 
| 最適合用於 | 可接受部分成功的大量操作。 | 必須一起建立或更新的相關資源。 | 

您可以綁定相同或不同類型的 FHIR 資源，它們可以包含 FHIR 操作的混合，例如 `create`、`read`、`update`、 `delete`和 `patch`。如需詳細資訊，請參閱 **FHIR R4 文件**中的[資源套件](https://hl7.org/fhir/R4/Bundle)。

以下是每個套件類型的範例使用案例。

批次套件  
+ 在夜間資料同步期間，從不同的設施上傳多個不相關的病患記錄。
+ 大量上傳一些記錄可能有驗證問題的歷史藥物記錄。
+ 載入參考資料，例如組織和從業人員，其中個別失敗不會影響其他項目。

交易套件  
+ 在緊急部門許可期間建立具有相關觀察和條件的患者，其中所有資料必須一起記錄。
+ 更新患者藥物清單，以及必須保持一致的相關敏感資訊。
+ 將與病患、觀察、程序和帳單資訊的完整事件記錄為單一原子單位。

**重要**  
批次和交易套件都使用相同的`Bundle`資源結構。唯一的差異是 `type` 欄位的值。

下列範例顯示具有多種資源類型和操作的交易套件。

```
{
  "resourceType": "Bundle",
  "type": "transaction",
  "entry": [
    {
      "fullUrl": "urn:uuid:4f6a30fb-cd3c-4ab6-8757-532101f72065",
      "resource": {
        "resourceType": "Patient",
        "id": "new-patient",
        "active": true,
        "name": [
          {
            "family": "Johnson",
            "given": [
              "Sarah"
            ]
          }
        ],
        "gender": "female",
        "birthDate": "1985-08-12",
        "telecom": [
          {
            "system": "phone",
            "value": "555-123-4567",
            "use": "home"
          }
        ]
      },
      "request": {
        "method": "POST",
        "url": "Patient"
      }
    },
    {
      "fullUrl": "urn:uuid:7f83f473-d8cc-4a8d-86d3-9d9876a3248b",
      "resource": {
        "resourceType": "Observation",
        "id": "blood-pressure",
        "status": "final",
        "code": {
          "coding": [
            {
              "system": "http://loinc.org",
              "code": "85354-9",
              "display": "Blood pressure panel"
            }
          ],
          "text": "Blood pressure panel"
        },
        "subject": {
          "reference": "urn:uuid:4f6a30fb-cd3c-4ab6-8757-532101f72065"
        },
        "effectiveDateTime": "2023-10-15T09:30:00Z",
        "component": [
          {
            "code": {
              "coding": [
                {
                  "system": "http://loinc.org",
                  "code": "8480-6",
                  "display": "Systolic blood pressure"
                }
              ]
            },
            "valueQuantity": {
              "value": 120,
              "unit": "mmHg",
              "system": "http://unitsofmeasure.org",
              "code": "mm[Hg]"
            }
          },
          {
            "code": {
              "coding": [
                {
                  "system": "http://loinc.org",
                  "code": "8462-4",
                  "display": "Diastolic blood pressure"
                }
              ]
            },
            "valueQuantity": {
              "value": 80,
              "unit": "mmHg",
              "system": "http://unitsofmeasure.org",
              "code": "mm[Hg]"
            }
          }
        ]
      },
      "request": {
        "method": "POST",
        "url": "Observation"
      }
    },
    {
      "resource": {
        "resourceType": "Appointment",
        "id": "appointment-123",
        "status": "booked",
        "description": "Annual physical examination",
        "start": "2023-11-15T09:00:00Z",
        "end": "2023-11-15T09:30:00Z",
        "participant": [
          {
            "actor": {
              "reference": "urn:uuid:4f6a30fb-cd3c-4ab6-8757-532101f72065"
            },
            "status": "accepted"
          }
        ]
      },
      "request": {
        "method": "PUT",
        "url": "Appointment/appointment-123"
      }
    },
    {
      "request": {
        "method": "DELETE",
        "url": "MedicationRequest/med-request-456"
      }
    }
  ]
}
```

## 將 FHIR 資源綁定為獨立實體
<a name="bundle-fhir-resources-batch-type"></a>

**將 FHIR 資源綁定為獨立實體**  


1. 收集 HealthLake `region`和 `datastoreId` 值。如需詳細資訊，請參閱[取得資料存放區屬性](managing-data-stores-describe.md)。

1. 使用 HealthLake `region`和 的收集值來建構請求的 URL`datastoreId`。*請勿在* URL 中指定 FHIR 資源類型。若要在下列範例中檢視整個 URL 路徑，請捲動至**複製**按鈕。

   ```
   POST https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/
   ```

1. 為請求建構 JSON 內文，將每個 HTTP 動詞指定為`method`元素的一部分。下列範例使用與 `Bundle` 資源的`batch`類型互動來建立新的 `Medication` `Patient`和資源。所有必要區段都會相應地加上註解。基於此程序的目的，請將檔案儲存為 `batch-independent.json`。

   ```
   {
       "resourceType": "Bundle",
       "id": "bundle-batch",
       "meta": {
           "lastUpdated": "2014-08-18T01:43:30Z"
       },
       "type": "batch",
       "entry": [
           {
               "resource": {
                   "resourceType": "Patient",
                   "meta": {
                       "lastUpdated": "2022-06-03T17:53:36.724Z"
                   },
                   "text": {
                       "status": "generated",
                       "div": "Some narrative"
                   },
                   "active": true,
                   "name": [
                       {
                           "use": "official",
                           "family": "Jackson",
                           "given": [
                               "Mateo",
                               "James"
                           ]
                       }
                   ],
                   "gender": "male",
                   "birthDate": "1974-12-25"
               },
               "request": {
                   "method": "POST",
                   "url": "Patient"
               }
           },
           {
               "resource": {
                   "resourceType": "Medication",
                   "id": "med0310",
                   "contained": [
                       {
                           "resourceType": "Substance",
                           "id": "sub03",
                           "code": {
                               "coding": [
                                   {
                                       "system": "http://snomed.info/sct",
                                       "code": "55452001",
                                       "display": "Oxycodone (substance)"
                                   }
                               ]
                           }
                       }
                   ],
                   "code": {
                       "coding": [
                           {
                               "system": "http://snomed.info/sct",
                               "code": "430127000",
                               "display": "Oral Form Oxycodone (product)"
                           }
                       ]
                   },
                   "form": {
                       "coding": [
                           {
                               "system": "http://snomed.info/sct",
                               "code": "385055001",
                               "display": "Tablet dose form (qualifier value)"
                           }
                       ]
                   },
                   "ingredient": [
                       {
                           "itemReference": {
                               "reference": "#sub03"
                           },
                           "strength": {
                               "numerator": {
                                   "value": 5,
                                   "system": "http://unitsofmeasure.org",
                                   "code": "mg"
                               },
                               "denominator": {
                                   "value": 1,
                                   "system": "http://terminology.hl7.org/CodeSystem/v3-orderableDrugForm",
                                   "code": "TAB"
                               }
                           }
                       }
                   ]
               },
               "request": {
                   "method": "POST",
                   "url": "Medication"
               }
           }
       ]
   }
   ```

1. 傳送 請求。FHIR `Bundle`批次類型使用具有[AWS 簽章第 4 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html)版或 FHIR 授權上的 SMART 的`POST`請求。下列程式碼範例使用`curl`命令列工具進行示範。

------
#### [ SigV4 ]

   SigV4 授權

   ```
   curl --request POST \
     'https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/' \
     --aws-sigv4 'aws:amz:region:healthlake' \
     --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
     --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
     --header 'Accept: application/json' \
     --data @batch-type.json
   ```

------
#### [ SMART on FHIR ]

   [https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html](https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html) 資料類型的 FHIR 上的 SMART 授權範例。

   ```
   {
       "AuthorizationStrategy": "SMART_ON_FHIR",
       "FineGrainedAuthorizationEnabled": true,
       "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
       "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\",\"permission-v2\"]}"
   }
   ```

   發起人可以在授權 lambda 中指派許可。如需詳細資訊，請參閱[OAuth 2.0 範圍](reference-smart-on-fhir-oauth-scopes.md)。

------

   伺服器會傳回回應，顯示因`Bundle`批次類型請求而建立的 `Medication` `Patient`和資源。

## 套件中的條件式 PUTs
<a name="bundle-conditional-PUTs"></a>

AWS HealthLake 支援使用下列查詢參數在套件內進行條件式更新：
+ `_id` （獨立）
+ `_id` 搭配下列其中一項：
  + `_tag`
  + `_createdAt`
  + `_lastUpdated`

當您在套件中使用條件式 PUTs 時， 會根據現有資源 AWS HealthLake 評估查詢參數，並根據相符結果採取動作。


**條件式更新行為**  

| 案例 | HTTP 狀態 | 採取的動作 | 
| --- | --- | --- | 
| 未提供 ID 的資源 | 201 已建立 | 一律建立新的資源。 | 
| 具有新 ID 的資源 （不相符） | 201 已建立 | 使用指定的 ID 建立新的資源。 | 
| 具有現有 ID 的資源 （單一相符項目） | 200 OK | 更新相符的資源。 | 
| 具有現有 ID 的資源 （偵測到衝突） | 409 衝突 | 傳回錯誤。不會進行任何變更。 | 
| 具有現有 ID 的資源 (ID 不相符） | 400 錯誤的請求 | 傳回錯誤。不會進行任何變更。 | 
| 多個資源符合條件 | 412 先決條件失敗 | 傳回錯誤。不會進行任何變更。 | 

在具有條件式更新的下列範例套件中，只有在符合條件時，具有 FHIR ID `_lastUpdated=lt2025-04-20` `Patient`的資源才會`476`更新。

```
{
    "resourceType": "Bundle",
    "id": "bundle-batch",
    "meta": {
        "lastUpdated": "2014-08-18T01:43:30Z"
    },
    "type": "batch",
    "entry": [
        {
            "resource": {
                "resourceType": "Patient",
                "id": "476",
                "meta": {
                    "lastUpdated": "2022-06-03T17:53:36.724Z"
                },
                "active": true,
                "name": [
                    {
                        "use": "official",
                        "family": "Jackson",
                        "given": [
                            "Mateo",
                            "James"
                        ]
                    }
                ],
                "gender": "male",
                "birthDate": "1974-12-25"
            },
            "request": {
                "method": "PUT",
                "url": "Patient?_id=476&_lastUpdated=lt2025-04-20"
            }
        },
        {
            "resource": {
                "resourceType": "Medication",
                "id": "med0310",
                "contained": [
                    {
                        "resourceType": "Substance",
                        "id": "sub03",
                        "code": {
                            "coding": [
                                {
                                    "system": "http://snomed.info/sct",
                                    "code": "55452001",
                                    "display": "Oxycodone (substance)"
                                }
                            ]
                        }
                    }
                ],
                "code": {
                    "coding": [
                        {
                            "system": "http://snomed.info/sct",
                            "code": "430127000",
                            "display": "Oral Form Oxycodone (product)"
                        }
                    ]
                },
                "form": {
                    "coding": [
                        {
                            "system": "http://snomed.info/sct",
                            "code": "385055001",
                            "display": "Tablet dose form (qualifier value)"
                        }
                    ]
                },
                "ingredient": [
                    {
                        "itemReference": {
                            "reference": "#sub03"
                        },
                        "strength": {
                            "numerator": {
                                "value": 5,
                                "system": "http://unitsofmeasure.org",
                                "code": "mg"
                            },
                            "denominator": {
                                "value": 1,
                                "system": "http://terminology.hl7.org/CodeSystem/v3-orderableDrugForm",
                                "code": "TAB"
                            }
                        }
                    }
                ]
            },
            "request": {
                "method": "POST",
                "url": "Medication"
            }
        }
    ]
}
```

## 將 FHIR 資源綁定為單一實體
<a name="bundle-fhir-resources-document-type"></a>

**將 FHIR 資源綁定為單一實體**  


1. 收集 HealthLake `region`和 `datastoreId` 值。如需詳細資訊，請參閱[取得資料存放區屬性](managing-data-stores-describe.md)。

1. 使用 HealthLake `region`和 的收集值來建構請求的 URL`datastoreId`。在 `Bundle` URL 中包含 FHIR 資源類型。若要在下列範例中檢視整個 URL 路徑，請捲動至**複製**按鈕。

   ```
   POST https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Bundle
   ```

1. 為請求建構 JSON 內文，指定要分組的 FHIR 資源。下列範例會將 HealthLake 中的兩個`Patient`資源分組。基於此程序的目的，請將檔案儲存為 `batch-single.json`。

   ```
   {
       "resourceType": "Bundle",
       "id": "bundle-minimal",
       "language": "en-US",
       "identifier": {
           "system": "urn:oid:1.2.3.4.5",
           "value": "28b95815-76ce-457b-b7ae-a972e527db4f"
       },
       "type": "document",
       "timestamp": "2020-12-11T14:30:00+01:00",
       "entry": [
           {
               "fullUrl": "urn:uuid:f40b07e3-37e8-48c3-bf1c-ae70fe12dabf",
               "resource": {
                   "resourceType": "Composition",
                   "id": "f40b07e3-37e8-48c3-bf1c-ae70fe12dabf",
                   "status": "final",
                   "type": {
                       "coding": [
                           {
                               "system": "http://loinc.org",
                               "code": "60591-5",
                               "display": "Patient summary Document"
                           }
                       ]
                   },
                   "date": "2020-12-11T14:30:00+01:00",
                   "author": [
                       {
                           "reference": "urn:uuid:45271f7f-63ab-4946-970f-3daaaa0663ff"
                       }
                   ],
                   "title": "Patient Summary as of December 7, 2020 14:30"
               }
           },
           {
               "fullUrl": "urn:uuid:45271f7f-63ab-4946-970f-3daaaa0663ff",
               "resource": {
                   "resourceType": "Practitioner",
                   "id": "45271f7f-63ab-4946-970f-3daaaa0663ff",
                   
                   "active": true,
                   "name": [
                       {
                           "family": "Doe",
                           "given": [
                               "John"
                           ]
                       }
                   ]                
               }
           }
       ]
   }
   ```

1. 傳送 請求。FHIR `Bundle` 文件類型使用 Signature [AWS 第 4 版](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html)簽署通訊協定的`POST`請求。下列程式碼範例使用`curl`命令列工具進行示範。

------
#### [ SigV4 ]

   SigV4 授權

   ```
   curl --request POST \
     'https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Bundle' \
     --aws-sigv4 'aws:amz:region:healthlake' \
     --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
     --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
     --header 'Accept: application/json' \
     --data @document-type.json
   ```

------
#### [ SMART on FHIR ]

   [https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html](https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html) 資料類型的 FHIR 上的 SMART 授權範例。

   ```
   {
       "AuthorizationStrategy": "SMART_ON_FHIR",
       "FineGrainedAuthorizationEnabled": true,
       "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
       "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\",\"permission-v2\"]}"
   }
   ```

   發起人可以在授權 lambda 中指派許可。如需詳細資訊，請參閱[OAuth 2.0 範圍](reference-smart-on-fhir-oauth-scopes.md)。

------

   伺服器會傳回回應，顯示因`Bundle`文件類型請求而建立的兩個`Patient`資源。

## 設定套件的驗證層級
<a name="validation-level-bundles"></a>

綁定 FHIR 資源時，您可以選擇指定 `x-amzn-healthlake-fhir-validation-level` HTTP 標頭來設定資源的驗證層級。此驗證層級將針對 bundle 內的所有建立和更新請求設定。 AWS HealthLake 目前支援下列驗證層級：
+ `strict`：資源會根據資源的設定檔元素進行驗證，如果沒有設定檔，則為 R4 規格。這是 的預設驗證層級 AWS HealthLake。
+ `structure-only`：資源會根據 R4 驗證，忽略任何參考的設定檔。
+ `minimal`：最少驗證資源，忽略某些 R4 規則。搜尋/分析所需的結構檢查失敗的資源將更新為包含稽核警告。

與最低驗證層級綁定的資源可能會擷取至資料存放區，即使搜尋索引所需的驗證失敗。在此情況下，資源將更新為包含 Healthlake 特定的延伸，以記錄上述失敗，而套件回應中的項目將包含 OperationOutcome 資源，如下所示：

```
{
    "resourceType": "Bundle",
    "type": "batch-response",
    "timestamp": "2025-08-25T22:58:48.846287342Z",
    "entry": [
        {
            "response": {
                "status": "201",
                "location": "Patient/195abc49-ba8e-4c8b-95c2-abc88fef7544/_history/1",
                "etag": "W/\"1\"",
                "lastModified": "2025-08-25T22:58:48.801245445Z",
                "outcome": {
                    "resourceType": "OperationOutcome",
                    "issue": [
                        {
                            "severity": "error",
                            "code": "processing",
                            "details": {
                                "text": "FHIR resource in payload failed FHIR validation rules."
                            },
                            "diagnostics": "FHIR resource in payload failed FHIR validation rules."
                        }
                    ]
                }
            }
        }
    ]
}
```

此外，以下 HTTP 回應標頭會包含在「true」的值中：

```
x-amzn-healthlake-validation-issues : true
```

**注意**  
請注意，如果出現這些錯誤，則可能無法如預期搜尋根據 R4 規格格式不正確的資料擷取。

## 對 Bundle 類型 "message" 的有限支援
<a name="bundle-message-type-limited-support"></a>

HealthLake `message` 透過內部轉換程序提供 FHIR Bundle 類型的有限支援。此支援適用於訊息套件無法在來源重新格式化的情況，例如從舊版醫院系統擷取 ADT (Admission、Discharge、Transfer) 饋送。

**警告**  
此功能需要明確的 AWS 帳戶允許清單，且不會強制執行 FHIR R4 訊息語意或參考完整性。使用訊息套件之前，請聯絡 AWS Support 請求啟用您的帳戶。

### 與標準訊息處理的主要差異
<a name="bundle-message-key-differences"></a>
+ **訊息套件 **(FHIR 規格）：第一個項目必須是參考其他資源`MessageHeader`的 。資源缺少個別`request`物件，MessageHeader 事件決定處理動作。
+ **HealthLake Processing**：透過自動將 PUT 操作指派給每個資源項目，將訊息套件轉換為批次套件。資源會獨立處理，不會強制執行訊息語意或參考完整性。

### 重要限制
<a name="bundle-message-limitations"></a>
+ 未強制執行 FHIR R4 訊息特定處理規則
+ 資源之間沒有交易完整性
+ 未驗證資源間參考
+ 需要明確的帳戶允許清單

### 訊息套件結構範例
<a name="bundle-message-example"></a>

```
{
              "resourceType": "Bundle",
              "type": "message",
              "entry": [
                {
                  "resource": {
                    "resourceType": "MessageHeader",
                    "eventCoding": {
                      "system": "http://hl7.org/fhir/us/davinci-alerts/CodeSystem/notification-event",
                      "code": "notification-admit"
                    },
                    "focus": [{"reference": "Encounter/example-id"}]
                  }
                },
                {
                  "resource": {"resourceType": "Patient", "id": "example-id"}
                },
                {
                  "resource": {"resourceType": "Encounter", "id": "example-id"}
                }
              ]
            }
```

**注意**  
每個資源都會獨立儲存，就像透過個別 PUT 操作提交一樣。如果需要完整的 FHIR 訊息語意或參考完整性驗證，請在提交之前預先處理訊息套件或實作應用程式層級驗證。

## 非同步套件交易
<a name="managing-fhir-resources-async-transactions"></a>

AWS HealthLake 支援非同步`Bundle`類型`transaction`，可讓您提交最多 500 個資源的交易。當您提交非同步交易時，HealthLake 會將其排入佇列進行處理，並立即傳回輪詢 URL。您可以使用此 URL 來檢查狀態並擷取回應。這遵循 [FHIR 非同步套件模式](https://hl7.org/fhir/async-bundle.html)。

**何時使用非同步交易**  

+ 您需要在單一交易中提交超過 100 個資源 （同步限制）。
+ 您希望避免在等待交易處理完成時封鎖應用程式。
+ 您需要處理具有更高輸送量的大量相關資源。

**重要**  
輪詢結果會在交易完成後 90 天內提供。在此 90 天期間之後，輪詢 URL 不會再傳回結果。設計您的整合，在此視窗中擷取和儲存結果。

**注意**  
同步`Bundle`類型`transaction`會持續支援最多 100 個資源，並且是預設的處理模式。如果您在沒有 `Prefer: respond-async`標頭的情況下提交`transaction`具有超過 100 個資源的`Bundle`類型，HealthLake 會傳回`422 Unprocessable Entity`錯誤。非同步處理`batch`不支援 類型的套件 - 只能非同步提交 `Bundle`類型 `transaction` （最多 500 個操作）。

### 提交非同步交易
<a name="async-transactions-submitting"></a>

若要提交非同步交易，請使用 `Prefer: respond-async`標頭傳送`POST`請求至資料存放區端點。套件必須具有類型 `transaction`。非同步套件處理`batch`不支援 類型的套件。

HealthLake 會在提交時對套件進行初始驗證。如果驗證成功，HealthLake 會傳回 HTTP 202 已接受，其中包含輪詢 URL 的`content-location`回應標頭。

**提交非同步`Bundle`類型 `transaction`**  


1. 將`POST`請求傳送至 HealthLake 資料存放區端點。

   ```
   POST https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/
   ```

1. 使用套件類型 為請求建構 JSON 內文`transaction`。基於此程序的目的，請將檔案儲存為 `async-transaction.json`。

   ```
   {
       "resourceType": "Bundle",
       "type": "transaction",
       "entry": [
           {
               "resource": {
                   "resourceType": "Patient",
                   "active": true,
                   "name": [
                       {
                           "use": "official",
                           "family": "Smith",
                           "given": ["Jane"]
                       }
                   ],
                   "gender": "female",
                   "birthDate": "1990-01-15"
               },
               "request": {
                   "method": "POST",
                   "url": "Patient"
               }
           },
           {
               "resource": {
                   "resourceType": "Observation",
                   "status": "final",
                   "code": {
                       "coding": [
                           {
                               "system": "http://loinc.org",
                               "code": "85354-9",
                               "display": "Blood pressure panel"
                           }
                       ]
                   },
                   "subject": {
                       "reference": "urn:uuid:example-patient-id"
                   }
               },
               "request": {
                   "method": "POST",
                   "url": "Observation"
               }
           }
       ]
   }
   ```

1. 使用 `Prefer: respond-async`標頭傳送請求。FHIR `Bundle`交易類型使用具有[AWS 簽章第 4 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html)版或 FHIR 授權上的 SMART 的`POST`請求。下列程式碼範例使用`curl`命令列工具進行示範。

------
#### [ SigV4 ]

   SigV4 授權

   ```
   curl --request POST \
     'https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/' \
     --aws-sigv4 'aws:amz:region:healthlake' \
     --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
     --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
     --header 'Accept: application/json' \
     --header 'Prefer: respond-async' \
     --data @async-transaction.json
   ```

------
#### [ SMART on FHIR ]

   [https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html](https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html) 資料類型的 FHIR 上的 SMART 授權範例。

   ```
   {
       "AuthorizationStrategy": "SMART_ON_FHIR",
       "FineGrainedAuthorizationEnabled": true,
       "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
       "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\",\"permission-v2\"]}"
   }
   ```

   發起人可以在授權 lambda 中指派許可。如需詳細資訊，請參閱[OAuth 2.0 範圍](reference-smart-on-fhir-oauth-scopes.md)。

------

1. 成功提交時，伺服器會傳回 HTTP 202 已接受。`content-location` 回應標頭包含輪詢 URL。回應內文是 `OperationOutcome` 資源。

   ```
   HTTP/1.1 202 Accepted
   content-location: https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Transaction/transactionId
   ```

   ```
   {
       "resourceType": "OperationOutcome",
       "issue": [
           {
               "severity": "information",
               "code": "informational",
               "diagnostics": "Submitted Asynchronous Bundle Transaction",
               "location": [
                   "https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Transaction/transactionId"
               ]
           }
       ]
   }
   ```

### 輪詢交易狀態
<a name="async-transactions-polling"></a>

提交非同步交易之後，請使用`content-location`回應標頭中的輪詢 URL 來檢查交易狀態。將`GET`請求傳送至輪詢 URL。

**注意**  
對於啟用 FHIR 的 SMART 資料存放區，授權字符必須包含`Transaction`資源類型的`read`許可，才能輪詢交易狀態。如需 FHIR 範圍的 SMART 詳細資訊，請參閱 [HealthLake 支援的 FHIR OAuth 2.0 範圍上的 SMART](reference-smart-on-fhir-oauth-scopes.md)。

將`GET`請求傳送至輪詢 URL。下列範例使用 `curl`命令列工具。

------
#### [ SigV4 ]

SigV4 授權

```
curl --request GET \
  'https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Transaction/transactionId' \
  --aws-sigv4 'aws:amz:region:healthlake' \
  --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
  --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
  --header 'Accept: application/json'
```

------
#### [ SMART on FHIR ]

FHIR 授權上的 SMART。授權字符必須包含`Transaction`資源類型的`read`許可。

```
curl --request GET \
  'https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Transaction/transactionId' \
  --header 'Authorization: Bearer $SMART_ACCESS_TOKEN' \
  --header 'Accept: application/json'
```

------

下表說明可能的回應。


**輪詢回應代碼**  

| HTTP 狀態 | 意義 | 回應主體 | 
| --- | --- | --- | 
| 202 已接受 | 交易已排入佇列 | OperationOutcome 具有診斷 "SUBMITTED" | 
| 202 已接受 | 正在處理交易 | OperationOutcome 使用診斷 "IN\$1PROGRESS" | 
| 200 OK | 交易已成功完成 | Bundle 使用 類型 transaction-response | 
| 4xx/5xx | 交易失敗 | OperationOutcome 含錯誤詳細資訊 | 

下列範例顯示每個回應類型。

**已排入佇列的交易 (202)**  


```
{
    "resourceType": "OperationOutcome",
    "id": "transactionId",
    "issue": [
        {
            "severity": "information",
            "code": "informational",
            "diagnostics": "SUBMITTED"
        }
    ]
}
```

**交易處理 (202)**  


```
{
    "resourceType": "OperationOutcome",
    "id": "transactionId",
    "issue": [
        {
            "severity": "information",
            "code": "informational",
            "diagnostics": "IN_PROGRESS"
        }
    ]
}
```

**交易已完成 (200)**  


```
{
    "resourceType": "Bundle",
    "type": "transaction-response",
    "entry": [
        {
            "response": {
                "status": "201",
                "location": "Patient/example-id/_history/1",
                "etag": "W/\"1\"",
                "lastModified": "2024-01-15T10:30:00.000Z"
            }
        },
        {
            "response": {
                "status": "201",
                "location": "Observation/example-id/_history/1",
                "etag": "W/\"1\"",
                "lastModified": "2024-01-15T10:30:00.000Z"
            }
        }
    ]
}
```

**交易失敗 (4xx/5xx)**  


```
{
    "resourceType": "OperationOutcome",
    "issue": [
        {
            "severity": "error",
            "code": "exception",
            "diagnostics": "Transaction failed: conflict detected on resource Patient/example-id"
        }
    ]
}
```

### 處理順序
<a name="async-transactions-processing-order"></a>

類型的非同步套件`transaction`會排入佇列，但不會以嚴格的提交順序處理。HealthLake 會根據可用容量和系統負載來最佳化處理。

**重要**  
請勿依賴依提交順序處理的交易。例如，如果您在上午 10：00 提交交易 A，並在上午 10：01 提交交易 B，則交易 B 可能會在交易 A 之前完成。將您的應用程式設計為：  
處理out-of-order完成。
使用輪詢 URL 獨立追蹤每個交易。
如果您的使用案例順序很重要，請實作應用程式層級排序。

### 配額和限流
<a name="async-transactions-quotas"></a>

下列配額和速率限制適用於非同步交易。


**非同步交易配額**  

| 配額 | Value | 可調整 | 
| --- | --- | --- | 
| 每個非同步交易的最大操作數 | 500 | 否 | 
| 每個資料存放區的待處理交易上限 | 500 | 是 | 
+ 非同步交易會共用 下定義的相同 API 速率限制[Service Quotas](reference-healthlake-endpoints-quotas.md#reference-healthlake-quotas)。
+ 輪詢交易狀態與 FHIR 資源的讀取 (`GET`) 操作共用相同的 API 速率限制。
+ 如果達到待定交易限制，後續提交會傳回錯誤，直到現有交易完成為止。

### 錯誤處理
<a name="async-transactions-error-handling"></a>

對於「交易」套件，套件中包含的所有 FHIR 資源都會處理為原子操作。操作中的所有資源都必須成功，否則套件中不會處理任何操作。

錯誤分為兩個類別：HealthLake 同步傳回的提交錯誤，以及處理您透過輪詢擷取的錯誤。

**提交錯誤**  


HealthLake 會在提交時驗證套件，並在交易排入佇列之前同步傳回錯誤。提交錯誤包括無效的 FHIR 資源驗證錯誤、不支援的資源類型、超過 500 個操作限制，以及搭配批次套件使用 `Prefer: respond-async`標頭。如果已達到資料存放區的待處理交易限制，HealthLake 會傳回 `ThrottlingException`。發生提交錯誤時，交易將不會排入佇列。

**處理錯誤**  


處理錯誤會在交易排入佇列後發生，並透過輪詢 URL 傳回。這些包括交易衝突，其中另一個操作修改了屬於交易一部分的資源，以及在處理期間發生伺服器錯誤。發生處理錯誤時，交易中的資源不會進行任何資源變動。輪詢 URL 將傳回`OperationOutcome`具有錯誤詳細資訊的 。

# 刪除 FHIR 資源
<a name="managing-fhir-resources-delete"></a>

FHIR `delete`互動會從 HealthLake 資料存放區移除現有的 FHIR 資源。如需詳細資訊，請參閱 **FHIR R4 RESTful API 文件**[https://hl7.org/fhir/R4/http.html#delete](https://hl7.org/fhir/R4/http.html#delete)中的 。

**刪除 FHIR 資源**  


1. 收集 HealthLake `region`和 `datastoreId` 值。如需詳細資訊，請參閱[取得資料存放區屬性](managing-data-stores-describe.md)。

1. 決定`Resource`要刪除的 FHIR 類型，並收集相關聯的`id`值。如需詳細資訊，請參閱[資源類型](reference-fhir-resource-types.md)。

1. 使用 HealthLake `region`和 的收集值來建構請求的 URL`datastoreId`。同時包含 FHIR `Resource`類型及其相關聯的 `id`。若要在下列範例中檢視整個 URL 路徑，請捲動至**複製**按鈕。

   ```
   DELETE https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Resource/id
   ```

1. 傳送 請求。FHIR `delete`互動使用具有[AWS 簽章第 4 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html)版或 FHIR 授權上的 SMART 的`DELETE`請求。下列`curl`範例會從 HealthLake 資料存放區移除現有的 FHIR `Patient` 資源。若要檢視整個範例，請捲動至**複製**按鈕。

------
#### [ SigV4 ]

   SigV4 授權

   ```
   curl --request DELETE \
     'https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Patient/id' \
     --aws-sigv4 'aws:amz:region:healthlake' \
     --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
     --header "x-amz-security-token:$AWS_SESSION_TOKEN" \
     --header 'Accept: application/json'
   ```

   伺服器會傳回 `204` HTTP 狀態碼，確認已從 HealthLake 資料存放區中移除資源。如果刪除請求失敗，您將收到`400`一系列 HTTP 狀態碼，指出請求失敗的原因。

------
#### [ SMART on FHIR ]

   [https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html](https://docs.aws.amazon.com/healthlake/latest/APIReference/API_IdentityProviderConfiguration.html) 資料類型的 FHIR 上的 SMART 授權範例。

   ```
   {
       "AuthorizationStrategy": "SMART_ON_FHIR",
       "FineGrainedAuthorizationEnabled": true,
       "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
       "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\",\"permission-v2\"]}"
   }
   ```

   發起人可以在授權 lambda 中指派許可。如需詳細資訊，請參閱[OAuth 2.0 範圍](reference-smart-on-fhir-oauth-scopes.md)。

------
#### [ AWS Console ]

   1. 登入 HealthLake 主控台上的[執行查詢](https://console.aws.amazon.com/healthlake/home#/crud)頁面。

   2. 在**查詢設定**區段下，進行下列選擇。
   + **資料存放區 ID** — 選擇資料存放區 ID 以產生查詢字串。
   + **查詢類型** — 選擇 `Delete`。
   + **資源類型** — 選擇要刪除的 FHIR [資源類型](reference-fhir-resource-types.md)。
   + **資源 ID** — 輸入 FHIR 資源 ID。

   3. 選擇 **Run query** (執行查詢)。

------

## 根據條件刪除 FHIR 資源
<a name="conditional-delete-fhir"></a>

當您不知道特定 FHIR 資源 ID，但具有您要刪除之資源的其他識別資訊時，條件式刪除特別有用。

條件式刪除可讓您根據搜尋條件而非邏輯 FHIR ID 刪除現有資源。當伺服器處理刪除請求時，它會使用資源類型的標準搜尋功能執行搜尋，以解析請求的單一邏輯 ID。

### 條件式刪除的運作方式
<a name="conditional-delete-works"></a>

**伺服器的動作取決於找到多少相符項目：**  


1. **沒有相符**項目：伺服器嘗試一般刪除並適當回應 (404 找不到不存在的資源，204 找不到已刪除資源的內容）

1. **一個相符**項目：伺服器對相符的資源執行一般刪除

1. **多個相符**項目：傳回 412 先決條件失敗錯誤，指出用戶端的條件不夠選擇性

### 回應案例
<a name="response-scenerios"></a>

AWS HealthLake 使用以下回應模式處理條件式刪除操作：

**成功的操作**  

+ 當您的搜尋條件成功識別單一作用中資源時，系統會在完成刪除後傳回 **204 無內容**，就像標準刪除操作一樣。

**以 ID 為基礎的條件式刪除**  
根據 `id` 和其他參數 (`createdAt`、 `tag`或 `_lastUpdated`) 執行條件式刪除時：
+ **204 無內容**：資源已刪除
+ **找不到 404**：資源不存在
+ **409 衝突**：ID 相符，但其他參數不相符

**Non-ID-Based條件式刪除**  
`id` 未提供 或使用 `createdAt`、 `tag`或 以外的參數時`_lastUpdated`：
+ **找不到 404**：找不到相符項目

**衝突情況**  
數個案例會產生 412 先決條件失敗回應：
+ 多個資源符合您的搜尋條件 （條件不夠具體）
+ 搭配 使用 ETag 標頭時的版本衝突 `If-Match`
+ 在搜尋和刪除操作之間發生資源更新

**成功條件式刪除的範例**  
下列範例會根據特定條件刪除病患資源：

```
DELETE https://healthlake.region.amazonaws.com/datastore/datastoreId/r4/Patient?name=peter&birthdate=2000-01-01&phone=1234567890
```

此請求會刪除病患資源，其中：
+ 名稱為「peter」
+ 出生日期是 2000 年 1 月 1 日
+ 電話號碼為 1234567890

**最佳實務**  


1. 使用特定的搜尋條件來避免多個相符項目，並防止 412 錯誤。

1. 需要處理並行修改時，請考慮使用版本控制的 ETag 標頭。

1. 適當地處理錯誤回應：
   + 對於 404：精簡您的搜尋條件
   + 對於 412：讓條件更具體或解決版本衝突

1. 準備在高並行環境中的時間衝突，其中可能會在搜尋和刪除操作之間修改資源。

# 冪等和並行
<a name="managing-fhir-resources-idempotency"></a>

## 等冪性金鑰
<a name="idempotency-keys"></a>

AWS HealthLake 支援 FHIR `POST`操作的等冪性金鑰，提供強大的機制，以確保資源建立期間的資料完整性。透過在請求標頭中將唯一的 UUID 作為等冪性金鑰，醫療保健應用程式可以保證每個 FHIR 資源只建立一次，即使在涉及網路不穩定或自動重試的情況下也是如此。

此功能對於醫療保健系統特別重要，因為重複的醫療記錄可能會造成嚴重的後果。當收到具有與先前請求相同等冪性金鑰的請求時，HealthLake 會傳回原始資源，而不是建立重複的資源。例如，這可能會在重試迴圈期間發生，或是因為備援請求管道。使用等冪性金鑰可讓 HealthLake 維持資料一致性，同時為處理間歇性連線問題的用戶端應用程式提供無縫體驗。

### 實作
<a name="implementation"></a>

```
POST /<baseURL>/Patient
x-amz-fhir-idempotency-key: 123e4567-e89b-12d3-a456-426614174000
{
    "resourceType": "Patient",
    "name": [...]
}
```

### 回應案例
<a name="response-scenarios"></a>

第一個請求 （已建立 201)  
+ 已成功建立新資源
+ 回應包含資源 ID

重複請求 (409 衝突）  
+ 偵測到相同的等冪性金鑰
+ 傳回的原始資源
+ 未建立新的資源

無效請求 (400 個無效的請求）  
+ 格式錯誤的 UUID
+ 缺少必要欄位

### 最佳實務
<a name="best-practices"></a>
+ 為每個新資源建立產生唯一的 UUID
+ 儲存等冪索引鍵以重試邏輯
+ 使用一致的金鑰格式：建議使用 UUID v4
+ 在處理資源建立的用戶端應用程式中實作

**注意**  
對於需要嚴格資料準確性和防止重複醫療記錄的醫療保健系統來說，此功能特別重要。

## AWS HealthLake 中的 ETag
<a name="healthlake-etag"></a>

AWS HealthLake 使用 ETags 在 FHIR 資源中實現樂觀並行控制，提供可靠的機制來管理並行修改和維護資料一致性。ETag 是代表資源特定版本的唯一識別符，可透過 HTTP 標頭做為版本控制系統。讀取或修改資源時，應用程式可以使用 ETags來防止意外覆寫和確保資料完整性，尤其是在具有潛在並行更新的情況下。

### 實作範例
<a name="healthlake-etag-implementation"></a>

```
// Initial Read
GET /fhir/Patient/123
Response: 
ETag: W/"1"

// Update with If-Match
PUT /fhir/Patient/123
If-Match: W/"1"
{resource content}

// Create with If-None-Match
PUT /fhir/Patient/123
If-None-Match: *
{resource content}
// Succeeds only if resource doesn't exist
// Fails with 412 if resource exists
```

### 回應案例
<a name="healthlake-etag-scenarios"></a>

操作成功 (200 OK 或 204 No Content)  
+ ETag 符合目前版本
+ 操作會如預期進行

版本衝突 (412 先決條件失敗）  
+ ETag 與目前版本不相符
+ 拒絕更新以防止資料遺失

### 最佳實務
<a name="healthlake-etag-practices"></a>
+ 在所有更新和刪除操作中包含 ETags 
+ 實作處理版本衝突的重試邏輯
+ 使用 If-None-Match：\$1 表示 create-if-not-exists 案例
+ 修改前一律驗證 ETag 新鮮度

此並行控制系統對於維護醫療保健資料的完整性至關重要，尤其是在具有多個使用者或系統存取和修改相同資源的環境中。