

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

# 綁定 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 支援使用下列查詢參數的套件內條件式更新：

**注意**  
條件式 PUTs僅支援 `batch` 套件。 `Transaction`套件不支援條件式 PUTs。
+ `_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` 文件類型使用具有 [AWS Signature 第 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 特定延伸，以記錄上述失敗，而 Bundle 回應中的項目將包含 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 個操作）。

**注意**  
`PATCH` 非同步套件交易不支援 操作和條件式 PUTs。

### 提交非同步交易
<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\_PROGRESS" | 
| 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`具有錯誤詳細資訊的 。