

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 执行批量导入和导出操作
<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 的更多信息，请参阅 “[什么是亚马逊 S3？](https://docs.aws.amazon.com//AmazonS3/latest/userguide/Welcome.html)

## IAM 权限
<a name="tm-import-export-prereqs-permissions"></a>

执行批量操作时，您需要创建一个 IAM 策略，该策略具有允许 Amazon S3、 AWS IoT TwinMaker 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": "*"
          }
      ]
  }
  ```

------
+ **亚马逊 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。

**注意**  
此策略仅允许访问在 Amazon S3 之间转移资源的导 AWS IoT TwinMaker 入和导出任务。

```
{
    "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
  ```

  如果您调用不存在 GetMetadataTransferJob 的 AWS IoT TwinMaker 导入或导出任务，则会收到`ResourceNotFoundException`错误的响应。
+ 要列出当前作业，请使用 [ ListMetadataTransferJobs](https://docs.aws.amazon.com//iot-twinmaker/latest/apireference/API_ListMetadataTransferJobs.html)API 操作。

  以下是以 destinationType 和 SourceType AWS IoT TwinMaker `s3` 作为源类型调 ListMetadataTransferJobs 用的 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：**表示在转移过程中跳过的资源数量。
+ **succededCount：**表示在转移过程中成功的资源数量。
+ **TotalCount：**表示转移过程中涉及的资源总数。

此外，还会返回一个包含预签名网址的 reportUrl 元素。如果您的转移任务存在错误，您想进一步调查，则可以使用此网址下载完整的错误报告。

## 导入元数据模板
<a name="tm-import-metadata-templates"></a>

您可以通过一次批量导入操作导入多个组件、组件类型或实体。本节中的示例说明了如何执行此操作。

------
#### [ 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
     ```