

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

# AWS Database Migration Service 用于将来自其他数据存储的数据加载到 Amazon Neptune
<a name="dms-neptune"></a>

AWS Database Migration Service (AWS DMS) 可以快速安全地将[支持的源数据库](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.html)中的数据加载到 Neptune。源数据库在迁移过程中可保持完全正常运行，从而最大程度减少依赖于该数据库的应用程序停机时间。

您可以在《[AWS Database Migration Service 用户指南》](https://docs.aws.amazon.com/dms/latest/userguide/)和《[AWS Database Migration Service API 参考](https://docs.aws.amazon.com/dms/latest/APIReference/)》 AWS DMS 中找到相关的详细信息。特别是，您可以在[使用 Amazon Neptune 作为 AWS Database Migration Service的目标](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html)中了解如何将 Neptune 集群设置为迁移目标。

以下是使用 AWS DMS将数据导入 Neptune 中的一些先决条件：
+ 您需要创建一个 AWS DMS 表映射对象来定义如何从源数据库中提取数据（有关详细信息，请参阅 AWS DMS 用户指南中的[使用 JSON 通过表映射指定表选择和转换](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.CustomizingTasks.TableMapping.html#CHAP_Tasks.CustomizingTasks.TableMapping.SelectionTransformation)）。此表映射配置对象指定应读取哪些表、按何种顺序读取以及如何命名它们的列。它还可以筛选正在复制的行，并提供简单的值转换，例如转换为小写或舍入。
+ 您需要创建一个 Neptune `GraphMappingConfig`，以指定如何将从源数据库中提取的数据加载到 Neptune。对于 RDF 数据（使用 SPARQL 查询），`GraphMappingConfig` 使用 W3 的标准 [R2RML](https://www.w3.org/TR/r2rml/) 映射语言编写。对于属性图数据（使用 Gremlin 进行查询），`GraphMappingConfig` 是 JSON 对象，如[GraphMappingConfig Property-Graph/Gremlin 数据的布局](dms-neptune-graph-mapping.md#dms-neptune-graph-mapping-gremlin)中所述。
+ 您必须使用在 AWS DMS 与 Neptune 数据库集群相同的 VPC 中创建复制实例，以调解数据的传输。
+ 您还需要一个 Amazon S3 桶来用作中间存储，以暂存迁移数据。

# 创建海王星 GraphMappingConfig
<a name="dms-neptune-graph-mapping"></a>

您创建的 `GraphMappingConfig` 指定如何将从源数据存储中提取的数据加载到 Neptune 数据库集群中。它的格式根据要加载 RDF 数据还是要加载属性图数据而有所不同。

对于 RDF 数据，您可以使用 W3 [R2RML](https://www.w3.org/TR/r2rml/) 语言，将关系数据映射到 RDF。

如果要加载将使用 Gremlin 查询的属性图数据，则为 `GraphMappingConfig` 创建 JSON 对象。

## GraphMappingConfig RDF/SPARQL 数据布局
<a name="dms-neptune-graph-mapping-sparql"></a>

如果您正在使用 SPARQL 加载要查询的 RDF 数据，您可以在 [R2RML](https://www.w3.org/TR/r2rml/) 中编写 `GraphMappingConfig`。`R2RML` 是一种标准 W3 语言，用于将关系数据映射到 RDF。示例如下：

```
@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix ex: <http://example.com/ns#> .

<#TriplesMap1>
    rr:logicalTable [ rr:tableName "nodes" ];
    rr:subjectMap [
        rr:template "http://data.example.com/employee/{id}";
        rr:class ex:Employee;
    ];
    rr:predicateObjectMap [
        rr:predicate ex:name;
        rr:objectMap [ rr:column "label" ];
    ] .
```

以下是另一个示例：

```
@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix ex: <http://example.com/#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<#TriplesMap2>
    rr:logicalTable [ rr:tableName "Student" ];
    rr:subjectMap   [ rr:template "http://example.com/{ID}{Name}";
                      rr:class foaf:Person ];
    rr:predicateObjectMap [
        rr:predicate ex:id ;
        rr:objectMap  [ rr:column "ID";
                        rr:datatype xsd:integer ]
    ];
    rr:predicateObjectMap [
        rr:predicate foaf:name ;
        rr:objectMap  [ rr:column "Name" ]
    ] .
```

位于 [R2RML：RDB 到 RDF 映射语言](https://www.w3.org/TR/r2rml/)的 W3 推荐提供了语言的详细信息。

## GraphMappingConfig Property-Graph/Gremlin 数据的布局
<a name="dms-neptune-graph-mapping-gremlin"></a>

与属性图形数据相当的 `GraphMappingConfig` 是一个 JSON 对象，该对象为要从源数据生成的每个图形实体提供映射规则。以下模板显示了此对象中的各个规则的情况：

```
{
  "rules": [
    {
      "rule_id": "(an identifier for this rule)",
      "rule_name": "(a name for this rule)",
      "table_name": "(the name of the table or view being loaded)",
      "vertex_definitions": [
        {
          "vertex_id_template": "{col1}",
          "vertex_label": "(the vertex to create)",
          "vertex_definition_id": "(an identifier for this vertex)",
          "vertex_properties": [
            {
              "property_name": "(name of the property)",
              "property_value_template": "{col2} or text",
              "property_value_type": "(data type of the property)"
            }
          ]
        }
      ]
    },
    {
      "rule_id": "(an identifier for this rule)",
      "rule_name": "(a name for this rule)",
      "table_name": "(the name of the table or view being loaded)",
      "edge_definitions": [
        {
          "from_vertex": {
            "vertex_id_template": "{col1}",
            "vertex_definition_id": "(an identifier for the vertex referenced above)"
          },
          "to_vertex": {
            "vertex_id_template": "{col3}",
            "vertex_definition_id": "(an identifier for the vertex referenced above)"
          },
          "edge_id_template": {
            "label": "(the edge label to add)",
            "template": "{col1}_{col3}"
          },
          "edge_properties":[
            {
              "property_name": "(the property to add)",
              "property_value_template": "{col4} or text",
              "property_value_type": "(data type like String, int, double)"
            }
          ]
        }
      ]
    }
  ]
}
```

请注意，顶点标签的存在意味着在这里创建了顶点，而没有顶点标签则意味着顶点由不同的源创建，而此定义仅添加顶点属性。

以下是员工记录的示例规则：

```
{
  "rules": [
    {
      "rule_id": "1",
      "rule_name": "vertex_mapping_rule_from_nodes",
      "table_name": "nodes",
      "vertex_definitions": [
        {
          "vertex_id_template": "{emp_id}",
          "vertex_label": "employee",
          "vertex_definition_id": "1",
          "vertex_properties": [
            {
              "property_name": "name",
              "property_value_template": "{emp_name}",
              "property_value_type": "String"
            }
          ]
        }
      ]
    },
    {
      "rule_id": "2",
      "rule_name": "edge_mapping_rule_from_emp",
      "table_name": "nodes",
      "edge_definitions": [
        {
          "from_vertex": {
            "vertex_id_template": "{emp_id}",
            "vertex_definition_id": "1"
          },
          "to_vertex": {
            "vertex_id_template": "{mgr_id}",
            "vertex_definition_id": "1"
          },
          "edge_id_template": {
            "label": "reportsTo",
            "template": "{emp_id}_{mgr_id}"
          },
          "edge_properties":[
            {
              "property_name": "team",
              "property_value_template": "{team}",
              "property_value_type": "String"
            }
          ]
        }
      ]
    }
  ]
}
```

# 创建以 Neptune 为目标的 AWS DMS 复制任务
<a name="dms-neptune-replication"></a>

创建表映射和图形映射配置后，使用以下过程将数据从源存储加载到 Neptune。有关问题的更多详细信息，请查阅 AWS DMS 文档。 APIs 

## 创建 AWS DMS 复制实例
<a name="dms-neptune-replication-instance"></a>

在运行 Neptune 数据库集群的 VPC 中创建 AWS DMS 复制实例（参见《 AWS DMS 用户[指南》[CreateReplicationInstance](https://docs.aws.amazon.com/dms/latest/APIReference/API_CreateReplicationInstance.html)中的 “使用 AWS DMS 复制实例](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html)”）。你可以使用如下 AWS CLI 命令来做到这一点：

```
aws dms create-replication-instance \
    --replication-instance-identifier (the replication instance identifier) \
    --replication-instance-class (the size and capacity of the instance, like 'dms.t2.medium') \
    --allocated-storage (the number of gigabytes to allocate for the instance initially) \
    --engine-version (the DMS engine version that the instance should use) \
    --vpc-security-group-ids (the security group to be used with the instance)
```

## 为源数据库创建 AWS DMS 终端节点
<a name="dms-neptune-source-endpoint"></a>

下一步是为您的源数据存储创建一个 AWS DMS 终端节点。你可以 AWS CLI 这样使用 AWS DMS [CreateEndpoint](https://docs.aws.amazon.com/dms/latest/APIReference/API_CreateEndpoint.html)API：

```
aws dms create-endpoint \
    --endpoint-identifier (source endpoint identifier) \
    --endpoint-type source \
    --engine-name (name of source database engine) \
    --username (user name for database login) \
    --password (password for login) \
    --server-name (name of the server) \
    --port (port number) \
    --database-name (database name)
```

## 设置 Amazon S3 存储桶以供 Neptune 用于暂存数据
<a name="dms-neptune-s3-staging-bucket"></a>

如果您没有可用于暂存数据的 Amazon S3 桶，请按照以下说明创建一个桶：《Amazon S3 入门指南》中的[创建桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingABucket.html)，或《控制台用户指南》中的[如何创建 S3 桶？](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket.html)。

如果您还没有创建用于授予对桶的 `GetObject`、`PutObject`、`DeleteObject` 和 `ListObject` 权限的 IAM policy，则需要创建此策略：

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "ListObjectsInBucket",
      "Effect": "Allow",
      "Action": [
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket"
      ]
    },
    {
      "Sid": "AllObjectActions",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/*"
      ]
    }
  ]
}
```

------

如果 Neptune 数据库集群启用了 IAM 身份验证，则还需要包括以下策略：

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": "neptune-db:*",
      "Resource": "arn:aws:neptune-db:us-east-1:111122223333:cluster-resource-id/*"
    }
  ]
}
```

------

创建 IAM 角色作为将策略附加到的可信文档：

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "dms.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    },
    {
      "Sid": "neptune",
      "Effect": "Allow",
      "Principal": {
        "Service": "rds.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

------

将策略附加到角色后，将该角色附加到您的 Neptune 数据库集群。这将 AWS DMS 允许使用存储桶暂存正在加载的数据。

## 在 Neptune VPC 中创建 Amazon S3 端点
<a name="dms-neptune-s3-endpoint"></a>

现在，在您的 Neptune 集群所在的 VPC 中，为中间 Amazon S3 桶创建 VPC 网关端点。您可以使用 AWS 管理控制台 或 AWS CLI 来执行此操作，如[创建网关终端节点](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-gateway.html#create-gateway-endpoint)中所述。

## 为 Neptune 创建 AWS DMS 目标端点
<a name="dms-neptune-target-endpoint"></a>

为您的目标 Neptune 数据库集群创建 AWS DMS 终端节点。你可以将 AWS DMS [CreateEndpoint](https://docs.aws.amazon.com/dms/latest/APIReference/API_CreateEndpoint.html)API 与`NeptuneSettings`参数配合使用，如下所示：

```
aws dms create-endpoint \
    --endpoint-identifier (target endpoint identifier) \
    --endpoint-type target \
    --engine-name neptune \
    --server-name (name of the server) \
    --port (port number) \
    --neptune-settings '{ \
      "ServiceAccessRoleArn": "(ARN of the service access role)", \
      "S3BucketName": "(name of S3 bucket to use for staging files when migrating)", \
      "S3BucketFolder": "(name of the folder to use in that S3 bucket)", \
      "ErrorRetryDuration": (number of milliseconds to wait between bulk-load retries), \
      "MaxRetryCount": (the maximum number of times to retry a failing bulk-load job), \
      "MaxFileSize": (maximum file size, in bytes, of the staging files written to S3), \
      "IamAuthEnabled": (set to true if IAM authentication is enabled on the Neptune cluster) }'
```

在`NeptuneSettings`参数中传递给 AWS DMS `CreateEndpoint` API 的 JSON 对象具有以下字段：

****
+ **`ServiceAccessRoleArn`** – *（必需）*IAM 角色的 ARN，该角色允许对用于暂存迁移到 Neptune 的数据的 S3 桶进行精细访问。如果对 Neptune 数据库集群启用了 IAM 授权，则此角色还应有权访问该数据库集群。
+ **`S3BucketName`** – *（必需）*对于完全加载迁移，复制实例会将所有 RDS 数据转换为 CSV、四元组文件并将其上传到 S3 中的此暂存桶，然后将其批量加载到 Neptune。
+ **`S3BucketFolder`** – *（必需）*要在 S3 暂存桶中使用的文件夹。
+ **`ErrorRetryDuration`** – *（可选）*Neptune 请求失败后在发出重试请求之前等待的毫秒数。默认值是 250。
+ **`MaxRetryCount`**—*（可选）*在可重试失败后 AWS DMS 应发出的最大重试请求数。默认值为 5。
+ **`MaxFileSize`** – *（可选）*在迁移期间，保存到 S3 的各个暂存文件的最大大小（以字节为单位）。默认值是 1048576 KB（1 GB）。
+ **`IsIAMAuthEnabled`** – *（可选）*如果在 Neptune 数据库集群上启用了 IAM 身份验证，则设置为 `true`，否则设置为 `false`。默认值为 `false`。

## 测试与新端点的连接
<a name="dms-neptune-test-endpoints"></a>

你可以使用 AWS DMS [TestConnection](https://docs.aws.amazon.com/dms/latest/APIReference/API_TestConnection.html)API 测试与每个新端点的连接，如下所示：

```
aws dms test-connection \
    --replication-instance-arn (the ARN of the replication instance) \
    --endpoint-arn (the ARN of the endpoint you are testing)
```

## 创建 AWS DMS 复制任务
<a name="dms-neptune-replication-task"></a>

成功完成上述步骤后，使用如下所示的 AWS DMS [CreateReplicationTask](https://docs.aws.amazon.com/dms/latest/APIReference/API_CreateReplicationTask.html.html)API 创建用于将数据从源数据存储迁移到 Neptune 的复制任务：

```
aws dms create-replication-task \
    --replication-task-identifier (name for the replication task) \
    --source-endpoint-arn (ARN of the source endpoint) \
    --target-endpoint-arn (ARN of the target endpoint) \
    --replication-instance-arn (ARN of the replication instance) \
    --migration-type full-load \
    --table-mappings (table-mapping JSON object or URI like 'file:///tmp/table-mappings,json') \
    --task-data (a GraphMappingConfig object or URI like 'file:///tmp/graph-mapping-config.json')
```

`TaskData` 参数提供 [GraphMappingConfig](dms-neptune-graph-mapping.md)，用于指定所复制的数据应如何存储在 Neptune 中。

## 启动 AWS DMS 复制任务
<a name="dms-neptune-start-task"></a>

现在，您可以启动复制任务：

```
aws dms start-replication-task
    --replication-task-arn (ARN of the replication task started in the previous step)
    --start-replication-task-type start-replication
```