

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

# 執行大量匯入和匯出操作
<a name="tm-import-export-api"></a>

本主題涵蓋如何執行大量匯入和匯出操作，以及如何處理傳輸任務中的錯誤。它提供使用 CLI 命令的傳輸任務範例。

 AWS IoT TwinMaker API 參考包含 [ CreateMetadataTransferJob](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_CreateMetadataTransferJob.html) 和其他 API 動作的相關資訊。

**Topics**
+ [metadataTransferJob 先決條件](#tm-import-export-prereqs)
+ [IAM 許可](#tm-import-export-prereqs-permissions)
+ [執行大量操作](#tm-import-export-procedure)
+ [錯誤處理](#tm-import-export-error-handling)
+ [匯入中繼資料範本](#tm-import-metadata-templates)
+ [AWS IoT TwinMaker metadataTransferJob 範例](#tm-import-export-cli-examples)

## metadataTransferJob 先決條件
<a name="tm-import-export-prereqs"></a>

請先完成下列先決條件，再執行metadataTransferJob：
+ 建立 AWS IoT TwinMaker 工作區。工作區可以是metadataTransferJob。如需建立工作區的詳細資訊，請參閱 [建立工作區](twinmaker-gs-workspace.md)。
+ 建立 Amazon S3 儲存貯體以存放資源。如需使用 Amazon S3 的詳細資訊，請參閱[什麼是 Amazon S3？](https://docs.aws.amazon.com//AmazonS3/latest/userguide/Welcome.html)

## IAM 許可
<a name="tm-import-export-prereqs-permissions"></a>

當您執行大量操作時，您需要建立具有許可的 IAM 政策 AWS IoT TwinMaker，以允許在 Amazon S3 AWS IoT SiteWise和本機機器之間交換 AWS 資源。如需建立 IAM 政策的詳細資訊，請參閱[建立 IAM 政策](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies_create.html)。

 AWS IoT TwinMaker AWS IoT SiteWise 和 Amazon S3 的政策陳述式列於此處：
+ **AWS IoT TwinMaker 政策**：

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [{
          "Effect": "Allow",
          "Action": [
              "s3:PutObject",
              "s3:GetObject",
              "s3:GetBucketLocation",
              "s3:ListBucket",
              "s3:AbortMultipartUpload",
              "s3:ListBucketMultipartUploads",
              "s3:ListMultipartUploadParts"
          ],
          "Resource": "*"
          },
          {
              "Effect": "Allow",
              "Action": [
                  "iottwinmaker:GetWorkspace",
                  "iottwinmaker:CreateEntity",
                  "iottwinmaker:GetEntity",
                  "iottwinmaker:UpdateEntity",
                  "iottwinmaker:GetComponentType",
                  "iottwinmaker:CreateComponentType",
                  "iottwinmaker:UpdateComponentType",
                  "iottwinmaker:ListEntities",
                  "iottwinmaker:ListComponentTypes",
                  "iottwinmaker:ListTagsForResource",
                  "iottwinmaker:TagResource",
                  "iottwinmaker:UntagResource"
              ],
              "Resource": "*"
          }
      ]
  }
  ```

------
+ **AWS IoT SiteWise 政策**：

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [{
          "Effect": "Allow",
          "Action": [
              "s3:PutObject",
              "s3:GetObject",
              "s3:GetBucketLocation",
              "s3:ListBucket",
              "s3:AbortMultipartUpload",
              "s3:ListBucketMultipartUploads",
              "s3:ListMultipartUploadParts"
          ],
          "Resource": "*"
          },
          {
              "Effect": "Allow",
              "Action": [
                  "iotsitewise:CreateAsset",
                  "iotsitewise:CreateAssetModel",
                  "iotsitewise:UpdateAsset",
                  "iotsitewise:UpdateAssetModel",
                  "iotsitewise:UpdateAssetProperty",
                  "iotsitewise:ListAssets",
                  "iotsitewise:ListAssetModels",
                  "iotsitewise:ListAssetProperties",
                  "iotsitewise:ListAssetModelProperties",
                  "iotsitewise:ListAssociatedAssets",
                  "iotsitewise:DescribeAsset",
                  "iotsitewise:DescribeAssetModel",
                  "iotsitewise:DescribeAssetProperty",
                  "iotsitewise:AssociateAssets",
                  "iotsitewise:DisassociateAssets",
                  "iotsitewise:AssociateTimeSeriesToAssetProperty",
                  "iotsitewise:DisassociateTimeSeriesFromAssetProperty",
                  "iotsitewise:BatchPutAssetPropertyValue",
                  "iotsitewise:BatchGetAssetPropertyValue",
                  "iotsitewise:TagResource",
                  "iotsitewise:UntagResource",
                  "iotsitewise:ListTagsForResource"
              ],
              "Resource": "*"
          }
      ]
  }
  ```

------
+ **Amazon S3 政策**：

  ```
  {
      "Effect": "Allow",
      "Action": [
          "s3:PutObject",
          "s3:GetObject",
          "s3:GetBucketLocation",
          "s3:ListBucket",
          "s3:AbortMultipartUpload",
          "s3:ListBucketMultipartUploads",
          "s3:ListMultipartUploadParts"
      ],
      "Resource": "*"
  }
  ```

  或者，您可以將 Amazon S3 政策限制為僅存取單一 Amazon S3 儲存貯體，請參閱下列政策。

  **Amazon S3 單一儲存貯體範圍政策**

  ```
  {
      "Effect": "Allow",
      "Action": [
          "s3:PutObject",
          "s3:GetObject",
          "s3:GetBucketLocation",
          "s3:ListBucket",
          "s3:AbortMultipartUpload",
          "s3:ListBucketMultipartUploads",
          "s3:ListMultipartUploadParts"
      ],
      "Resource": [
          "arn:aws:s3:::bucket name",
          "arn:aws:s3:::bucket name/*"
      ]
  }
  ```

### 設定metadataTransferJob
<a name="tm-import-export-access-control"></a>

若要控制使用者可存取的任務類型，請將下列 IAM 政策新增至用於呼叫的角色 AWS IoT TwinMaker。

**注意**  
此政策僅允許存取 AWS IoT TwinMaker 匯入和匯出在 Amazon S3 之間傳輸資源的任務。

```
{
    "Effect": "Allow",
    "Action": [
        "iottwinmaker:*DataTransferJob*"
    ],
    "Resource": "*",
    "Condition": {
        "StringLikeIfExists": {
            "iottwinmaker:sourceType": [
                "s3",
                "iottwinmaker"
            ],
            "iottwinmaker:destinationType": [
                "iottwinmaker",
                "s3"
            ]
        }
    }
}
```

## 執行大量操作
<a name="tm-import-export-procedure"></a>

本節說明如何執行大量匯入和匯出操作。

**將資料從 Amazon S3 匯入至 AWS IoT TwinMaker**

1. 使用 AWS IoT TwinMaker metadataTransferJob 結構描述指定您要傳輸的資源。建立結構描述檔案並將其存放在 Amazon S3 儲存貯體中。

   如需範例結構描述，請參閱 [匯入中繼資料範本](#tm-import-metadata-templates)。

1. 建立請求內文並將其儲存為 JSON 檔案。請求內文會指定傳輸任務的來源和目的地。請務必將 Amazon S3 儲存貯體指定為來源，並將 AWS IoT TwinMaker 工作區指定為目的地。

   以下是請求內文的範例：

   ```
   {
       "metadataTransferJobId": "your-transfer-job-Id",
       "sources": [{
           "type": "s3",
           "s3Configuration": {
               "location": "arn:aws:s3:::amzn-s3-demo-bucket/your_import_data.json"
           }
       }],
       "destination": {
           "type": "iottwinmaker",
           "iotTwinMakerConfiguration": {
               "workspace": "arn:aws:iottwinmaker:us-east-1:111122223333:workspace/your-worksapce-name"
           }
       }
   }
   ```

   記錄您提供請求內文的檔案名稱，您需要在下一個步驟中使用它。在此範例中，請求內文名為 `createMetadataTransferJobImport.json`。

1. 執行下列 CLI 命令來叫用 `CreateMetadataTransferJob`（將 input-json 檔案名稱取代為您提供請求內文的名稱）：

   ```
   aws iottwinmaker create-metadata-transfer-job --region us-east-1 \
   --cli-input-json file://createMetadataTransferJobImport.json
   ```

   這會建立metadataTransferJob，並開始轉移所選資源的程序。

**從 匯出資料 AWS IoT TwinMaker 至 Amazon S3**

1. 使用適當的篩選條件建立 JSON 請求內文，以選擇要匯出的資源。在此範例中，我們使用：

   ```
   {
       "metadataTransferJobId": "your-transfer-job-Id",
       "sources": [{
           "type": "iottwinmaker",
           "iotTwinMakerConfiguration": {
               "workspace": "arn:aws:iottwinmaker:us-east-1:111122223333:workspace/your-workspace-name",
               "filters": [{
                   "filterByEntity": {
                       "entityId": "parent"
                   }},
                   {
                   "filterByEntity": {
                       "entityId": "child"
                   }},
                   {
                   "filterByComponentType": {
                       "componentTypeId": "component.type.minimal"
                   }}
               ]
           }
       }],
       "destination": {
           "type": "s3",
           "s3Configuration": {
               "location": "arn:aws:s3:::amzn-s3-demo-bucket"
           }
       }
   }
   ```

   `filters` 陣列可讓您指定要匯出的資源。在此範例中，我們會依 `entity`、 和 進行篩選`componentType`。

   請務必將 AWS IoT TwinMaker 工作區指定為來源，並將 Amazon S3 儲存貯體指定為中繼資料傳輸任務的目的地。

   儲存您的請求內文並記錄檔案名稱，您會在下一個步驟中需要它。在此範例中，我們將請求內文命名為 `createMetadataTransferJobExport.json`。

1. 執行下列 CLI 命令來叫用 `CreateMetadataTransferJob`（將 input-json 檔案名稱取代為您提供請求內文的名稱）：

   ```
   aws iottwinmaker create-metadata-transfer-job --region us-east-1 \
   --cli-input-json file://createMetadataTransferJobExport.json
   ```

   這會建立metadataTransferJob，並開始轉移所選資源的程序。

若要檢查或更新傳輸任務的狀態，請使用下列命令：
+ 若要取消任務，請使用 [ CancelMetadataTransferJob](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_CancelMetadataTransferJob.html) API 動作。當您呼叫 CancelMetadataTransferJob 時，API 只會取消執行中的metadataTransferJob，而且任何已匯出或匯入的資源都不會受到此 API 呼叫的影響。
+ 若要擷取特定任務的資訊，請使用 [ GetMetadataTransferJob](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_GetMetadataTransferJob.html) API 動作。

  或者，您可以使用下列 CLI 命令，在現有的傳輸任務上呼叫 GetMetadataTransferJob：

  ```
  aws iottwinmaker get-metadata-transfer-job --job-id ExistingJobId
  ```

  如果您在不存在的 AWS IoT TwinMaker 匯入或匯出任務上呼叫 GetMetadataTransferJob，您會收到`ResourceNotFoundException`錯誤回應。
+ 若要列出目前的任務，請使用 [ ListMetadataTransferJobs](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_ListMetadataTransferJobs.html) API 動作。

  以下是將 ListMetadataTransferJobs 呼叫 AWS IoT TwinMaker 為 destinationType 和 `s3` sourceType 的 CLI 範例：

  ```
  aws iottwinmaker list-metadata-transfer-jobs --destination-type iottwinmaker --source-type s3
  ```
**注意**  
您可以變更 sourceType 和 destinationType 參數的值，以符合匯入或匯出任務的來源和目的地。

如需叫用這些 API 動作的 CLI 命令範例，請參閱 [AWS IoT TwinMaker metadataTransferJob 範例](#tm-import-export-cli-examples)。

如果您在傳輸任務期間遇到任何錯誤，請參閱 [錯誤處理](#tm-import-export-error-handling)。

## 錯誤處理
<a name="tm-import-export-error-handling"></a>

建立並執行傳輸任務之後，您可以呼叫 GetMetadataTransferJob 來診斷發生的任何錯誤：

```
aws iottwinmaker get-metadata-transfer-job \
--metadata-transfer-job-id your_metadata_transfer_job_id \
--region us-east-1
```

一旦看到任務狀態變成 `COMPLETED`，您就可以驗證任務的結果。GetMetadataTransferJob 會傳回名為 的物件[https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_MetadataTransferJobProgress.html](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_MetadataTransferJobProgress.html)，其中包含下列欄位：
+ **failedCount：**指出轉移程序期間失敗的資源數量。
+ **skippedCount：**指出轉移過程中略過的資源數量。
+ **succeededCount：**表示傳輸程序期間成功的資源數量。
+ **totalCount：**表示傳輸程序中涉及的資源總數。

此外，會傳回 reportUrl 元素，其中包含預先簽章的 URL。如果您的傳輸任務有您想要進一步調查的錯誤，您可以使用此 URL 下載完整的錯誤報告。

## 匯入中繼資料範本
<a name="tm-import-metadata-templates"></a>

您可以使用單一大量匯入操作匯入許多元件、 componentTypes 或實體。本節中的範例示範如何執行此操作。

------
#### [ template: Importing entities ]

將下列範本格式用於匯入實體的任務：

```
{
  "entities": [
    {
      "description": "string",
      "entityId": "string",
      "entityName": "string",
      "parentEntityId": "string",
      "tags": {
        "string": "string"
      },
      "components": {
        "string": {    
          "componentTypeId": "string",
          "description": "string",
          "properties": {
            "string": {
              "definition": {
                "configuration": {
                  "string": "string"
                },
                "dataType": "DataType",
                "defaultValue": "DataValue",
                "displayName": "string",
                "isExternalId": "boolean",
                "isRequiredInEntity": "boolean",
                "isStoredExternally": "boolean",
                "isTimeSeries": "boolean"
              },
              "value": "DataValue"
            }
          },
          "propertyGroups": {
            "string": {
              "groupType": "string",
              "propertyNames": [
                "string"
              ]
            }
          }
        }
      }
    }
  ]
}
```

------
#### [ template: Importing componentTypes ]

針對匯入 componentTypes 的任務使用下列範本格式：

```
{
  "componentTypes": [
    {
      "componentTypeId": "string",
      "componentTypeName": "string",
      "description": "string",
      "extendsFrom": [
        "string"
      ],
      "functions": {
        "string": {
          "implementedBy": {
            "isNative": "boolean",
            "lambda": {
              "functionName": "Telemetry-tsDataReader",
              "arn": "Telemetry-tsDataReaderARN"
            }
          },
          "requiredProperties": [
            "string"
          ],
          "scope": "string"
        }
      },
      "isSingleton": "boolean",
      "propertyDefinitions": {
        "string": {
          "configuration": {
            "string": "string"
          },
          "dataType": "DataType",
          "defaultValue": "DataValue",
          "displayName": "string",
          "isExternalId": "boolean",
          "isRequiredInEntity": "boolean",
          "isStoredExternally": "boolean",
          "isTimeSeries": "boolean"
        }
      },
      "propertyGroups": {
        "string": {
          "groupType": "string",
          "propertyNames": [
            "string"
          ]
        }
      },
      "tags": {
        "string": "string"
      }
    }
  ]
}
```

------
#### [ template: Importing components ]

將下列範本格式用於匯入元件的任務：

```
{
  "entityComponents": [
    {
      "entityId": "string",
      "componentName": "string",
      "componentTypeId": "string",
      "description": "string",
      "properties": {
        "string": {
          "definition": {
            "configuration": {
              "string": "string"
            },
            "dataType": "DataType",
            "defaultValue": "DataValue",
            "displayName": "string",
            "isExternalId": "boolean",
            "isRequiredInEntity": "boolean",
            "isStoredExternally": "boolean",
            "isTimeSeries": "boolean"
          },
          "value": "DataValue"
        }
      },
      "propertyGroups": {
        "string": {
          "groupType": "string",
          "propertyNames": [
            "string"
          ]
        }
      }
    }
  ]
}
```

------

## AWS IoT TwinMaker metadataTransferJob 範例
<a name="tm-import-export-cli-examples"></a>

使用下列命令來管理您的中繼資料傳輸：
+ [ CreateMetadataTransferJob](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_CreateMetadataTransferJob.html) API 動作。

  CLI 命令範例：

  ```
  aws iottwinmaker create-metadata-transfer-job --region us-east-1 \
  --cli-input-json file://yourTransferFileName.json
  ```
+ 若要取消任務，請使用 [ CancelMetadataTransferJob](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_CancelMetadataTransferJob.html) API 動作。

  CLI 命令範例：

  ```
  aws iottwinmaker cancel-metadata-transfer-job 
  --region us-east-1 \
  --metadata-transfer-job-id job-to-cancel-id
  ```

  當您呼叫 CancelMetadataTransferJob 時，只會取消特定的中繼資料傳輸任務，而且任何已匯出或匯入的資源都不會受到影響。
+ 若要擷取特定任務的資訊，請使用 [ GetMetadataTransferJob](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_GetMetadataTransferJob.html) API 動作。

  CLI 命令範例：

  ```
  aws iottwinmaker get-metadata-transfer-job \
  --metadata-transfer-job-id your_metadata_transfer_job_id \
  --region us-east-1 \
  ```
+ 若要列出目前的任務，請使用 [ ListMetadataTransferJobs](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_ListMetadataTransferJobs.html) API 動作。

  您可以使用 JSON 檔案篩選 ListMetadataTransferJobs 傳回的結果。請參閱下列使用 CLI 的程序：

  1. 建立 CLI 輸入 JSON 檔案以指定您要使用的篩選條件：

     ```
     {
         "sourceType": "s3",
         "destinationType": "iottwinmaker",
         "filters": [{
             "workspaceId": "workspaceforbulkimport"
         },
         {
             "state": "COMPLETED"
         }]
     }
     ```

     儲存它並記錄檔案名稱，在輸入 CLI 命令時需要它。

  1. 使用 JSON 檔案做為下列 CLI 命令的引數：

     ```
     aws iottwinmaker list-metadata-transfer-job --region us-east-1 \
     --cli-input-json file://ListMetadataTransferJobsExample.json
     ```