

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

# 开始使用亚马逊 DataZone
<a name="getting-started"></a>

本节中的信息可帮助您开始使用 Amazon DataZone。如果您不熟悉 Amazon DataZone，请先熟悉中介绍的概念和术语[亚马逊 DataZone 术语和概念](datazone-concepts.md)。

在开始执行这两个快速入门工作流中的任一工作流的步骤之前，您必须先完成本指南的[设置](setting-up.md)部分中描述的过程。如果您使用的是全新的 AWS 账户，则必须[配置使用亚马逊 DataZone 管理控制台所需的权限](create-iam-roles.md)。如果您使用的 AWS 账户已有 AWS Glue 数据目录对象，则还必须为[亚马逊配置 Lake Formation 权限 DataZone](lake-formation-permissions-for-datazone.md)。

本入门部分将引导您完成以下 Amazon DataZone 快速入门工作流程：

**Topics**
+ [亚马逊 DataZone 快速入门 Glue AWS 数据](quickstart-glue.md)
+ [亚马逊使用亚马逊 DataZone Redshift 数据快速入门](quickstart-rs.md)
+ [使用示例脚本的 Amazon DataZone 快速入门](quickstart-apis.md)

# 亚马逊 DataZone 快速入门 Glue AWS 数据
<a name="quickstart-glue"></a>

完成以下快速入门步骤，使用示例 AWS Glue 数据在 Amazon 中运行完整的数据生成器和数据 DataZone 使用者工作流程。

**Topics**
+ [第 1 步-创建 Amazon DataZone 域名和数据门户](#create-domain-gs-glue)
+ [步骤 2 – 创建发布项目](#create-publishing-project-gs-glue)
+ [步骤 3 – 创建环境](#create-environment-gs-glue)
+ [步骤 4 – 创建数据以供发布](#produce-data-for-publishing-gs-glue)
+ [第 5 步-从 AWS Glue 收集元数据](#gather-metadata-from-glue-gs-glue)
+ [步骤 6 – 整理和发布数据资产](#curate-data-asset-gs-glue)
+ [步骤 7 – 创建用于数据分析的项目](#create-project-for-data-analysis-gs-glue)
+ [步骤 8 – 创建用于数据分析的环境](#create-environment-gs2-glue)
+ [步骤 9 – 搜索数据目录并订阅数据](#search-catalog-subscribe-gs-glue)
+ [步骤 10 – 批准订阅请求](#approve-subscription-request-gs-glue)
+ [步骤 11 – 在 Amazon Athena 中构建查询并分析数据](#analyze-data-gs-glue)

## 第 1 步-创建 Amazon DataZone 域名和数据门户
<a name="create-domain-gs-glue"></a>

本节介绍为此工作流程创建 Amazon DataZone 域和数据门户的步骤。

完成以下步骤以创建 Amazon DataZone 域名。有关 Amazon DataZone 域名的更多信息，请参阅[亚马逊 DataZone 术语和概念](datazone-concepts.md)。

1. **导航至 [https://console.aws.amazon.com/datazone](https://console.aws.amazon.com/datazone) 上的亚马逊 DataZone 控制台，登录，然后选择创建域名。**
**注意**  
如果您想在此工作流程中使用现有 Amazon DataZone **域名，请选择查看**域名，然后选择要使用的域名，然后继续执行创建发布项目的第 2 步。

1. 在**创建域**页面上，提供以下字段的值：
   + **名称** – 指定您的域的名称。在此工作流中，您可以将此域命名为 **Marketing**。
   + **描述** – 指定可选的域描述。
   + **数据加密**-默认情况下，您的数据使用为您 AWS 拥有和管理的密钥进行加密。在此应用场景中，您可以保留默认的数据加密设置。

     有关客户自主管理型密钥的更多信息，请参阅 [Amazon 的静态数据加密 DataZone](encryption-rest-datazone.md)。如果您使用自己的 KMS 密钥进行数据加密，则必须在默认 [AmazonDataZoneDomainExecutionRole](AmazonDataZoneDomainExecutionRole.md) 中包含以下语句。

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

****  

     ```
     {
         "Version":"2012-10-17",		 	 	 
         "Statement": [
             {
                 "Sid": "Statement1",
                 "Effect": "Allow",
                 "Action": [
                     "kms:Decrypt",
                     "kms:DescribeKey",
                     "kms:GenerateDataKey"
                 ],
                 "Resource": [
                     "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
                 ]
             }
         ]
     }
     ```

------
   + **服务访问权限** – 默认情况下，将已选定的**使用默认角色**选项保持不变。
**注意**  
如果您在此工作流程中使用现有 Amazon DataZone 域名，则可以选择 “**使用现有服务角色**” 选项，然后从下拉菜单中选择现有角色。
   + 在**快速设置功能**下，选择**设置此账户以使用和发布数据**。此选项启用内置的 Amazon **数据湖**和**数据仓库 DataZone **蓝图，并为该账户配置所需的权限、资源、默认项目以及默认数据湖和数据仓库环境配置文件。有关 Amazon DataZone 蓝图的更多信息，请参阅[亚马逊 DataZone 术语和概念](datazone-concepts.md)。
   + 将**权限详细信息**下的其余字段保持不变。
**注意**  
如果您已有 Amazon DataZone 域名，则可以选择 “**使用现有服务角色**” 选项，然后从 **Glue 管理访问角色、Redshift 管理访问角色****和**配置**角色的下拉菜单中选择现有角色**。
   + 将**标签**下的字段保持不变。
   + 选择**创建域**。

1. 成功创建一个域后，选择此域，然后在此域的摘要页面上记下此域的**数据门户 URL**。您可以使用此 URL 访问您的 Amazon DataZone 数据门户，以完成此工作流程中的其余步骤。您也可以通过选择**打开数据门户**来导航到数据门户。

**注意**  
在当前版本的 Amazon 中 DataZone，一旦创建了域，就无法修改为数据门户生成的 URL。

域创建过程可能需要几分钟的时间才能完成。等待域状态变为**可用**，然后再继续执行下一步。

## 步骤 2 – 创建发布项目
<a name="create-publishing-project-gs-glue"></a>

此部分介绍为此工作流创建发布项目所需的步骤。

1. 完成上述第 1 步并创建域名后，您将看到 “**欢迎来到亚马逊 DataZone！** 窗口。在此窗口中，选择**创建项目**。

1. 例如，为该工作流程指定项目名称，您可以为其命名 **SalesDataPublishingProject**，然后将其余字段保持不变，然后选择**创建**。

## 步骤 3 – 创建环境
<a name="create-environment-gs-glue"></a>

此部分介绍为此工作流创建环境所需的步骤。

1. 完成上述步骤 2 并创建项目后，您将看到**您的项目已准备就绪，可以开始使用了！**窗口。在此窗口中，选择**创建环境**。

1. 在**创建环境**页面上，指定以下内容，然后选择**创建环境**。

1. 为以下字段指定值：
   + **名称** – 指定环境的名称。在本演练中，您可以将它命名为 `Default data lake environment`。
   + **描述** – 指定环境的描述。
   + **环境配置文件**-选择**DataLakeProfile**环境配置文件。这使您能够在此工作流程 DataZone 中使用亚马逊来处理亚马逊 S3、 AWS Glue Catalog 和 Amazon Athena 中的数据。
   + 在本演练中，将其余字段保持不变。

1. 选择**创建环境**。

## 步骤 4 – 创建数据以供发布
<a name="produce-data-for-publishing-gs-glue"></a>

此部分介绍为此工作流创建数据以供发布所需的步骤。

1. 完成上述步骤 3 后，在 `SalesDataPublishingProject` 项目中，在右侧面板中的**分析工具**下，选择 **Amazon Athena**。这将打开 Athena 查询编辑器，使用项目的凭证进行身份验证。确保在 **Amazon 环境下拉列表中选择了您的发布 DataZone 环境**，并选择了查询编辑器中的`<environment_name>%_pub_db`数据库。

1. 在本演练中，您将使用 **“按选择创建表”** (CTAS) 查询脚本来创建要发布到 Amazon 的新表。 DataZone在查询编辑器中，执行此 CTAS 脚本来创建一个可发布并可供搜索和订阅的 `mkt_sls_table` 表。

   ```
   CREATE TABLE mkt_sls_table AS
   SELECT 146776932 AS ord_num, 23 AS sales_qty_sld, 23.4 AS wholesale_cost, 45.0 as lst_pr, 43.0 as sell_pr, 2.0 as disnt, 12 as ship_mode,13 as warehouse_id, 23 as item_id, 34 as ctlg_page, 232 as ship_cust_id, 4556 as bill_cust_id
   UNION ALL SELECT 46776931, 24, 24.4, 46, 44, 1, 14, 15, 24, 35, 222, 4551
   UNION ALL SELECT 46777394, 42, 43.4, 60, 50, 10, 30, 20, 27, 43, 241, 4565
   UNION ALL SELECT 46777831, 33, 40.4, 51, 46, 15, 16, 26, 33, 40, 234, 4563
   UNION ALL SELECT 46779160, 29, 26.4, 50, 61, 8, 31, 15, 36, 40, 242, 4562
   UNION ALL SELECT 46778595, 43, 28.4, 49, 47, 7, 28, 22, 27, 43, 224, 4555
   UNION ALL SELECT 46779482, 34, 33.4, 64, 44, 10, 17, 27, 43, 52, 222, 4556
   UNION ALL SELECT 46779650, 39, 37.4, 51, 62, 13, 31, 25, 31, 52, 224, 4551
   UNION ALL SELECT 46780524, 33, 40.4, 60, 53, 18, 32, 31, 31, 39, 232, 4563
   UNION ALL SELECT 46780634, 39, 35.4, 46, 44, 16, 33, 19, 31, 52, 242, 4557
   UNION ALL SELECT 46781887, 24, 30.4, 54, 62, 13, 18, 29, 24, 52, 223, 4561
   ```

   确保已在左侧的**表和视图**部分中成功创建 **mkt\$1sls\$1table** 表。现在，您有了可以发布到 Amazon DataZone 目录中的数据资产。

## 第 5 步-从 AWS Glue 收集元数据
<a name="gather-metadata-from-glue-gs-glue"></a>

本节介绍为该工作流程从 AWS Glue 收集元数据的步骤。

1. 完成上述步骤 4 后，在 Amazon DataZone 数据门户中，选择`SalesDataPublishingProject`项目，然后选择 “**数据**” 选项卡，然后在左侧面板中选择 “**数据源**”。

1. 选择在环境创建过程中创建的来源。

1. 选择**操作**下拉菜单旁边的**运行**，然后选择刷新按钮。数据源运行完成后，资产将添加到 Amazon DataZone 库存中。

## 步骤 6 – 整理和发布数据资产
<a name="curate-data-asset-gs-glue"></a>

此部分介绍在此工作流中整理和发布数据资产的步骤。

1. 完成上述步骤 5 后，在 Amazon DataZone 数据门户中，选择您在上一步中创建的`SalesDataPublishingProject`项目，选择 “**数据**” 选项卡，在左侧面板中选择 “**库存数据**”，然后找到`mkt_sls_table`表格。

1. 打开 `mkt_sls_table` 资产的详细信息页面以查看自动生成的企业名称。选择**自动生成的元数据**图标以查看自动生成的资产名称和列名称。您可以分别接受或拒绝每个名称，也可以选择**全部接受**以应用生成的名称。或者，您也可以将可用的元数据表单添加到资产中，并选择术语表术语来对数据进行分类。

1. 选择**发布资产**以发布 `mkt_sls_table` 资产。

## 步骤 7 – 创建用于数据分析的项目
<a name="create-project-for-data-analysis-gs-glue"></a>

此部分介绍创建用于数据分析的项目的步骤。这是此工作流包含的多个数据使用者步骤中的第一个步骤。

1. 完成上述步骤 6 后，在亚马逊 DataZone 数据门户中，从**项目下拉菜单中选择创建****项目**。

1. 在**创建项目**页面上，指定项目名称，例如，您可以为此工作流程命名 **MarketingDataAnalysisProject**，然后将其余字段保持不变，然后选择**创建**。

## 步骤 8 – 创建用于数据分析的环境
<a name="create-environment-gs2-glue"></a>

此部分介绍创建用于数据分析的环境的步骤。

1. 完成上述步骤 7 后，在 Amazon DataZone 数据门户中，选择`MarketingDataAnalysisProject`项目，然后选择**环境**选项卡，然后选择**创建环境**。

1. 在**创建环境**页面上，指定以下内容，然后选择**创建环境**。
   + **名称** – 指定环境的名称。在本演练中，您可以将它命名为 `Default data lake environment`。
   + **描述** – 指定环境的描述。
   + **环境配置文件**-选择内置**DataLakeProfile**环境配置文件。
   + 在本演练中，将其余字段保持不变。

## 步骤 9 – 搜索数据目录并订阅数据
<a name="search-catalog-subscribe-gs-glue"></a>

此部分介绍搜索数据目录和订阅数据的步骤。

1. 完成上述步骤 8 后，在亚马逊 DataZone 数据门户中，选择亚马逊 DataZone图标，然后在亚马逊 DataZone **搜索**字段中，使用数据门户搜索栏中的关键词（例如 “目录” 或 “销售”）**搜索**数据资产。

   如有必要，可应用筛选条件或排序，在找到**产品销售数据**资产后，可选择该资产以打开其详细信息页面。

1. 在**目录销售数据**资产的详细信息页面上，选择**订阅**。

1. 在 “**订阅**” 对话框中，从下拉列表中选择您的**MarketingDataAnalysisProject**消费者项目，然后指定订阅请求的原因，然后选择 “**订阅**”。

## 步骤 10 – 批准订阅请求
<a name="approve-subscription-request-gs-glue"></a>

此部分介绍批准订阅请求的步骤。

1. 完成上述步骤 9 后，在 Amazon DataZone 数据门户中，选择用于发布资产的**SalesDataPublishingProject**项目。

1. 选择**数据**选项卡，再选择**已发布的数据**，然后选择**传入的请求**。

1. 现在，您可以看到需审批的新请求所在的行。选择**查看请求**。提供审批的原因，然后选择**批准**。

## 步骤 11 – 在 Amazon Athena 中构建查询并分析数据
<a name="analyze-data-gs-glue"></a>

现在，您已成功将资产发布到 Amazon DataZone 目录并订阅了该资产，您可以对其进行分析。

1. 在亚马逊 DataZone 数据门户中，选择您的**MarketingDataAnalysisProject**消费者项目，然后从右侧面板的 “**分析工具**” 下，选择 Amazon Athena 的 “**查询数据**” 链接。这将打开 Amazon Athena 查询编辑器，使用项目的凭证进行身份验证。从查询编辑器的 **Amazon Environment 下拉列表中选择使用**MarketingDataAnalysisProject**者 DataZone 环境**，然后`<environment_name>%sub_db`从数据库下拉列表中选择您的项目。

1. 现在，您可以对订阅的表运行查询。您可以从**表和视图**中选择表，然后选择**预览**以在编辑器屏幕上显示 select 语句。运行查询以查看结果。

# 亚马逊使用亚马逊 DataZone Redshift 数据快速入门
<a name="quickstart-rs"></a>

完成以下快速入门步骤，使用 Amazon Redshift 示例数据在亚马逊中运行完整的数据生成器和数据 DataZone 使用者工作流程。

**Topics**
+ [第 1 步-创建 Amazon DataZone 域名和数据门户](#create-domain-gs-rs)
+ [步骤 2 – 创建发布项目](#create-publishing-project-gs-rs)
+ [步骤 3 – 创建环境](#create-environment-gs-rs)
+ [步骤 4 – 创建数据以供发布](#produce-data-for-publishing-gs-rs)
+ [步骤 5 – 从 Amazon Redshift 收集元数据](#gather-metadata-from-glue-gs-rs)
+ [步骤 6 – 整理和发布数据资产](#curate-data-asset-gs-rs)
+ [步骤 7 – 创建用于数据分析的项目](#create-project-for-data-analysis-gs-rs)
+ [步骤 8 – 创建用于数据分析的环境](#create-environment-gs2-rs)
+ [步骤 9 – 搜索数据目录并订阅数据](#search-catalog-subscribe-gs-rs)
+ [步骤 10 – 批准订阅请求](#approve-subscription-request-gs-rs)
+ [步骤 11 – 在 Amazon Redshift 中构建查询并分析数据](#analyze-data-gs-rs)

## 第 1 步-创建 Amazon DataZone 域名和数据门户
<a name="create-domain-gs-rs"></a>

完成以下步骤以创建 Amazon DataZone 域名。有关 Amazon DataZone 域名的更多信息，请参阅[亚马逊 DataZone 术语和概念](datazone-concepts.md)。

1. **导航至 [https://console.aws.amazon.com/datazone](https://console.aws.amazon.com/datazone) 上的亚马逊 DataZone 控制台，登录，然后选择创建域名。**
**注意**  
如果您想在此工作流程中使用现有 Amazon DataZone 域名，请选择查看域名，然后选择要使用的域名，然后继续执行创建发布项目的第 2 步。

1. 在**创建域**页面上，提供以下字段的值：
   + **名称** – 指定您的域的名称。在此工作流中，您可以将此域命名为 `Marketing`。
   + **描述** – 指定可选的域描述。
   + **数据加密**-默认情况下，您的数据使用为您 AWS 拥有和管理的密钥进行加密。在本演练中，您可以保留默认的数据加密设置。

     有关客户自主管理型密钥的更多信息，请参阅 [Amazon 的静态数据加密 DataZone](encryption-rest-datazone.md)。如果您使用自己的 KMS 密钥进行数据加密，则必须在默认 [AmazonDataZoneDomainExecutionRole](AmazonDataZoneDomainExecutionRole.md) 中包含以下语句。

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

****  

     ```
     {
         "Version":"2012-10-17",		 	 	 
         "Statement": [
             {
                 "Sid": "Statement1",
                 "Effect": "Allow",
                 "Action": [
                     "kms:Decrypt",
                     "kms:DescribeKey",
                     "kms:GenerateDataKey"
                 ],
                 "Resource": [
                     "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
                 ]
             }
         ]
     }
     ```

------
   + **服务访问权限**-选择 “**使用自定义服务角色**” 选项，然后**AmazonDataZoneDomainExecutionRole**从下拉菜单中选择。
   + 在**快速设置功能**下，选择**设置此账户以使用和发布数据**。此选项启用内置的 Amazon **数据湖**和**数据仓库 DataZone **蓝图，并配置完成此工作流程中其余步骤所需的权限和资源。有关 Amazon DataZone 蓝图的更多信息，请参阅[亚马逊 DataZone 术语和概念](datazone-concepts.md)。
   + 将**权限详细信息**和**标签**下的其余字段保持不变，然后选择**创建域**。

1. 成功创建一个域后，选择此域，然后在此域的摘要页面上记下此域的**数据门户 URL**。您可以使用此 URL 访问您的 Amazon DataZone 数据门户，以完成此工作流程中的其余步骤。

**注意**  
在当前版本的 Amazon 中 DataZone，一旦创建了域，就无法修改为数据门户生成的 URL。

域创建过程可能需要几分钟的时间才能完成。等待域状态变为**可用**，然后再继续执行下一步。

## 步骤 2 – 创建发布项目
<a name="create-publishing-project-gs-rs"></a>

以下部分介绍在此工作流中创建发布项目的步骤。

1. 完成步骤 1 后，使用数据门户 URL 导航至 Amazon DataZone 数据门户，然后使用单点登录 (SSO) 或 AWS IAM 凭证登录。

1. 选择 “**创建项目**”，指定项目名称，例如，为该工作流程指定项目名称 **SalesDataPublishingProject**，然后将其余字段保持不变，然后选择 “**创建**”。

## 步骤 3 – 创建环境
<a name="create-environment-gs-rs"></a>

以下部分介绍在此工作流中创建环境的步骤。

1. 完成步骤 2 后，在 Amazon DataZone 数据门户中，选择您在上一步中创建的`SalesDataPublishingProject`项目，然后选择**环境**选项卡，然后选择**创建环境**。

1. 在**创建环境**页面上，指定以下内容，然后选择**创建环境**。
   + **名称** – 指定环境的名称。在本演练中，您可以将它命名为 `Default data warehouse environment`。
   + **描述** – 指定环境的描述。
   + **环境配置文件**-选择**DataWarehouseProfile**环境配置文件。
   + 提供您的 Amazon Redshift 集群的名称、数据库名称以及存储数据的 Amazon Redshift 集群的密钥 ARN。
**注意**  
确保你在 Secrets Manager 中的 AWS 密钥包含以下标签（键/值）：  
对于 Amazon Redshift 集群 – datazone.rs.cluster：<cluster\$1name:database name>  
对于 Amazon Redshift Serverless 工作组 – datazone.rs.workgroup：<workgroup\$1name:database\$1name>
AmazonDataZoneProject: <projectID> 
AmazonDataZoneDomain: <domainID>
有关更多信息，请参阅在 S [AWS ecrets Manager 中存储数据库凭据](https://docs.aws.amazon.com//redshift/latest/mgmt/data-api-access.html#data-api-secrets)。  
您在 S AWS ecrets Manager 中提供的数据库用户必须具有超级用户权限。

## 步骤 4 – 创建数据以供发布
<a name="produce-data-for-publishing-gs-rs"></a>

以下部分介绍在此工作流中创建用于发布的数据的步骤。

1. 完成步骤 3 后，在亚马逊 DataZone 数据门户中，选择`SalesDataPublishingProject`项目，然后在右侧面板的 “**分析工具**” 下，选择 **Amazon** Redshift。这将打开 Amazon Redshift 查询编辑器，使用项目的凭证进行身份验证。

1. 在本演练中，您将使用 **“按选择创建表”** (CTAS) 查询脚本来创建要发布到 Amazon 的新表。 DataZone在查询编辑器中，执行此 CTAS 脚本来创建一个可发布并可供搜索和订阅的 `mkt_sls_table` 表。

   ```
   CREATE TABLE mkt_sls_table AS
   SELECT 146776932 AS ord_num, 23 AS sales_qty_sld, 23.4 AS wholesale_cost, 45.0 as lst_pr, 43.0 as sell_pr, 2.0 as disnt, 12 as ship_mode,13 as warehouse_id, 23 as item_id, 34 as ctlg_page, 232 as ship_cust_id, 4556 as bill_cust_id
   UNION ALL SELECT 46776931, 24, 24.4, 46, 44, 1, 14, 15, 24, 35, 222, 4551
   UNION ALL SELECT 46777394, 42, 43.4, 60, 50, 10, 30, 20, 27, 43, 241, 4565
   UNION ALL SELECT 46777831, 33, 40.4, 51, 46, 15, 16, 26, 33, 40, 234, 4563
   UNION ALL SELECT 46779160, 29, 26.4, 50, 61, 8, 31, 15, 36, 40, 242, 4562
   UNION ALL SELECT 46778595, 43, 28.4, 49, 47, 7, 28, 22, 27, 43, 224, 4555
   UNION ALL SELECT 46779482, 34, 33.4, 64, 44, 10, 17, 27, 43, 52, 222, 4556
   UNION ALL SELECT 46779650, 39, 37.4, 51, 62, 13, 31, 25, 31, 52, 224, 4551
   UNION ALL SELECT 46780524, 33, 40.4, 60, 53, 18, 32, 31, 31, 39, 232, 4563
   UNION ALL SELECT 46780634, 39, 35.4, 46, 44, 16, 33, 19, 31, 52, 242, 4557
   UNION ALL SELECT 46781887, 24, 30.4, 54, 62, 13, 18, 29, 24, 52, 223, 4561
   ```

   确保已成功创建 **mkt\$1sls\$1table** 表。现在，您有了可以发布到 Amazon DataZone 目录中的数据资产。

## 步骤 5 – 从 Amazon Redshift 收集元数据
<a name="gather-metadata-from-glue-gs-rs"></a>

以下部分介绍从 Amazon Redshift 收集元数据的步骤。

1. 完成步骤 4 后，在 Amazon DataZone 数据门户中，选择`SalesDataPublishingProject`项目，然后选择 “**数据**” 选项卡，然后选择 “**数据源**”。

1. 选择在环境创建过程中创建的来源。

1. 选择**操作**下拉菜单旁边的**运行**，然后选择刷新按钮。数据源运行完成后，资产将添加到 Amazon DataZone 库存中。

## 步骤 6 – 整理和发布数据资产
<a name="curate-data-asset-gs-rs"></a>

以下部分介绍在此工作流中整理和发布数据资产的步骤。

1. 完成第 5 步后，在 Amazon DataZone 数据门户中，选择`SalesDataPublishingProject`项目，然后选择**数据**选项卡，选择**库存数据**，然后找到`mkt_sls_table`表。

1. 打开 `mkt_sls_table` 资产的详细信息页面以查看自动生成的企业名称。选择**自动生成的元数据**图标以查看自动生成的资产名称和列名称。您可以分别接受或拒绝每个名称，也可以选择**全部接受**以应用生成的名称。或者，您也可以将可用的元数据表单添加到资产中，并选择术语表术语来对数据进行分类。

1. 选择**发布**以发布 `mkt_sls_table` 资产。

## 步骤 7 – 创建用于数据分析的项目
<a name="create-project-for-data-analysis-gs-rs"></a>

以下部分介绍在此工作流中创建用于数据分析的项目的步骤。

1. 完成步骤 6 后，在 Amazon DataZone 数据门户中，选择**创建项目**。

1. 在 “**创建项目**” 页面中，指定项目名称，例如，为该工作流程命名 **MarketingDataAnalysisProject**，然后将其余字段保持不变，然后选择 “**创建**”。

## 步骤 8 – 创建用于数据分析的环境
<a name="create-environment-gs2-rs"></a>

以下部分介绍在此工作流中创建用于数据分析的环境的步骤。

1. 完成步骤 7 后，在 Amazon DataZone 数据门户中，选择您在上一步中创建的`MarketingDataAnalysisProject`项目，然后选择**环境**选项卡，然后选择**添加环境**。

1. 在**创建环境**页面上，指定以下内容，然后选择**创建环境**。
   + **名称** – 指定环境的名称。在本演练中，您可以将它命名为 `Default data warehouse environment`。
   + **描述** – 指定环境的描述。
   + **环境配置文件**-选择**DataWarehouseProfile**环境配置文件。
   + 提供您的 Amazon Redshift 集群的名称、数据库名称以及存储数据的 Amazon Redshift 集群的密钥 ARN。
**注意**  
确保你在 Secrets Manager 中的 AWS 密钥包含以下标签（键/值）：  
对于 Amazon Redshift 集群 – datazone.rs.cluster：<cluster\$1name:database name>  
对于 Amazon Redshift Serverless 工作组 – datazone.rs.workgroup：<workgroup\$1name:database\$1name>
AmazonDataZoneProject: <projectID> 
AmazonDataZoneDomain: <domainID>
有关更多信息，请参阅在 S [AWS ecrets Manager 中存储数据库凭据](https://docs.aws.amazon.com//redshift/latest/mgmt/data-api-access.html#data-api-secrets)。  
您在 S AWS ecrets Manager 中提供的数据库用户必须具有超级用户权限。
   + 在本演练中，将其余字段保持不变。

## 步骤 9 – 搜索数据目录并订阅数据
<a name="search-catalog-subscribe-gs-rs"></a>

以下部分介绍搜索数据目录和订阅数据的步骤。

1. 完成步骤 8 后，在亚马逊 DataZone 数据门户中，使用数据门户搜索栏中的关键词（例如 “目录” 或 “销售”）**搜索**数据资产。

   如有必要，可应用筛选条件或排序，在找到产品销售数据资产后，可选择该资产以打开其详细信息页面。

1. 在产品销售数据资产的详细信息页面上，选择**订阅**。

1. 在对话框中，从下拉列表中选择使用者项目，提供访问请求的原因，然后选择**订阅**。

## 步骤 10 – 批准订阅请求
<a name="approve-subscription-request-gs-rs"></a>

以下部分介绍在此工作流中批准订阅请求的步骤。

1. 完成步骤 9 后，在 Amazon DataZone 数据门户中，选择用于发布资产的**SalesDataPublishingProject**项目。

1. 选择**数据**选项卡，再选择**已发布的数据**，然后选择**传入的请求**。

1. 选择查看请求链接，然后选择**批准**。

## 步骤 11 – 在 Amazon Redshift 中构建查询并分析数据
<a name="analyze-data-gs-rs"></a>

现在，您已成功将资产发布到 Amazon DataZone 目录并订阅了该资产，您可以对其进行分析。

1. 在亚马逊 DataZone 数据门户网站的右侧面板上，单击 Amazon Redshift 链接。这将打开 Amazon Redshift 查询编辑器，使用项目的凭证进行身份验证。

1. 现在，您可以对订阅的表运行查询（select 语句）。您可以单击表格（three-vertical-dots 选项），然后选择预览以在编辑器屏幕上显示选择语句。执行查询以查看结果。

# 使用示例脚本的 Amazon DataZone 快速入门
<a name="quickstart-apis"></a>

您可以 DataZone 通过管理门户网站或亚马逊 DataZone 数据门户网站访问亚马逊，也可以使用亚马逊 DataZone HTTPS API 以编程方式访问亚马逊，它允许您直接向服务发出 HTTPS 请求。本节包含调用 Amazon 的示例脚本 DataZone APIs ，您可以使用这些脚本来完成以下常见任务：

**Topics**
+ [创建 Amazon DataZone 域名和数据门户](#create-domain-gs-glue-api)
+ [创建发布项目](#create-publishing-project-gs-glue-api)
+ [创建环境配置文件](#create-environment-profile-gs-glue-api)
+ [创建环境](#create-environment-gs-glue-api)
+ [从 AWS Glue 收集元数据](#gather-metadata-from-glue-gs-glue-api)
+ [整理和发布数据资产](#curate-data-asset-gs-glue-api)
+ [搜索数据目录并订阅数据](#search-catalog-subscribe-gs-glue-api)
+ [在数据目录中搜索资产](#search-catalog-subscribe-gs-glue-api)
+ [其他有用的示例脚本](#other-useful-scripts-api)

## 创建 Amazon DataZone 域名和数据门户
<a name="create-domain-gs-glue-api"></a>

您可以使用以下示例脚本创建 Amazon DataZone 域名。有关 Amazon DataZone 域名的更多信息，请参阅[亚马逊 DataZone 术语和概念](datazone-concepts.md)。

```
import sys
import boto3

// Initialize datazone client
region = 'us-east-1'
dzclient = boto3.client(service_name='datazone', region_name='us-east-1')

// Create DataZone domain
def create_domain(name):
    return dzclient.create_domain(
        name = name,
        description = "this is a description",
        domainExecutionRole = "arn:aws:iam::<account>:role/AmazonDataZoneDomainExecutionRole",
    )
```

## 创建发布项目
<a name="create-publishing-project-gs-glue-api"></a>

您可以使用以下示例脚本在 Amazon 中创建发布项目 DataZone。

```
// Create Project
def create_project(domainId):
    return dzclient.create_project(
        domainIdentifier = domainId,
        name = "sample-project"
    )
```

## 创建环境配置文件
<a name="create-environment-profile-gs-glue-api"></a>

您可以使用以下示例脚本在 Amazon 中创建环境配置文件 DataZone。

调用 `CreateEnvironmentProfile` API 时将使用以下示例有效载荷：

```
Sample Payload
{
    "Content":{
        "project_name": "Admin_project",
        "domain_name": "Drug-Research-and-Development",
        "blueprint_account_region": [
            {
                "blueprint_name": "DefaultDataLake",
                "account_id": ["066535990535",
                "413878397724",
                "676266385322", 
                "747721550195", 
                "755347404384"
                ],
                "region": ["us-west-2", "us-east-1"]
            },
            {
                "blueprint_name": "DefaultDataWarehouse",
                "account_id": ["066535990535",
                "413878397724",
                "676266385322", 
                "747721550195", 
                "755347404384"
                ],
                "region":["us-west-2", "us-east-1"]
            }
        ]
    }
}
```

此示例脚本调用 `CreateEnvironmentProfile` API：

```
def create_environment_profile(domain_id, project_id, env_blueprints)    
        try:
            response = dz.list_environment_blueprints(
                domainIdentifier=domain_id,
                managed=True
            )
            env_blueprints = response.get("items")
            env_blueprints_map = {}
            for i in env_blueprints:
                env_blueprints_map[i["name"]] = i['id']
            
            print("Environment Blueprint map", env_blueprints_map)
            for i in blueprint_account_region:
                print(i)
                for j in i["account_id"]:
                    for k in i["region"]:
                        print("The env blueprint name is", i['blueprint_name'])
                        dz.create_environment_profile(
                            description='This is a test environment profile created via lambda function',
                            domainIdentifier=domain_id,
                            awsAccountId=j,
                            awsAccountRegion=k,
                            environmentBlueprintIdentifier=env_blueprints_map.get(i["blueprint_name"]),
                            name=i["blueprint_name"] + j + k + "_profile",
                            projectIdentifier=project_id
                        )
        except Exception as e:
            print("Failed to created Environment Profile")
            raise e
```

这是调用 `CreateEnvironmentProfile` API 后的示例输出有效载荷：

```
{
    "Content":{
        "project_name": "Admin_project",
        "domain_name": "Drug-Research-and-Development",
        "blueprint_account_region": [
            {
                "blueprint_name": "DefaultDataWarehouse",
                "account_id": ["111111111111"],
                "region":["us-west-2"],
                "user_parameters":[
                    {
                        "name": "dataAccessSecretsArn",
                        "value": ""
                    }
                ] 
            }
        ]
    }
}
```

## 创建环境
<a name="create-environment-gs-glue-api"></a>

您可以使用以下示例脚本在 Amazon 中创建环境 DataZone。

```
def create_environment(domain_id, project_id,blueprint_account_region ):
         try:
            #refer to get_domain_id and get_project_id for fetching ids using names.
            sts_client = boto3.client("sts")
            # Get the current account ID
            account_id = sts_client.get_caller_identity()["Account"]
            print("Fetching environment profile ids")
            env_profile_map = get_env_profile_map(domain_id, project_id)

            for i in blueprint_account_region:
                for j in i["account_id"]:
                    for k in i["region"]:
                        print(" env blueprint name", i['blueprint_name'])
                        profile_name = i["blueprint_name"] + j + k + "_profile"
                        env_name = i["blueprint_name"] + j + k + "_env"
                        description = f'This is environment is created for {profile_name}, Account {account_id} and region {i["region"]}'
                        try:
                            dz.create_environment(
                                description=description,
                                domainIdentifier=domain_id,
                                environmentProfileIdentifier=env_profile_map.get(profile_name),
                                name=env_name,
                                projectIdentifier=project_id
                            )
                            print(f"Environment created - {env_name}")
                        except:
                            dz.create_environment(
                                description=description,
                                domainIdentifier=domain_id,
                                environmentProfileIdentifier=env_profile_map.get(profile_name),
                                name=env_name,
                                projectIdentifier=project_id,
                                userParameters= i["user_parameters"] 
                            )
                            print(f"Environment created - {env_name}")
        except Exception as e:
            print("Failed to created Environment")
            raise e
```

## 从 AWS Glue 收集元数据
<a name="gather-metadata-from-glue-gs-glue-api"></a>

您可以使用此示例脚本从 AWS Glue 收集元数据。此脚本按标准计划运行。可从示例脚本中检索参数并将它们设置为全局参数。使用标准函数获取项目、环境和域 ID。 AWS Glue 数据来源按标准时间创建和运行，可以在脚本的 cron 部分进行更新。

```
def crcreate_data_source(domain_id, project_id,data_source_name)
        print("Creating Data Source")
        data_source_creation = dz.create_data_source(
            # Define data source : Customize the data source to which you'd like to connect
            # define the name of the Data source to create, example: name ='TestGlueDataSource'
            name=data_source_name,
            # give a description for the datasource (optional), example: description='This is a dorra test for creation on DZ datasources'
            description=data_source_description,
            # insert the domain identifier corresponding to the domain to which the datasource will belong, example: domainIdentifier= 'dzd_6f3gst5jjmrrmv'
            domainIdentifier=domain_id,
            # give environment identifier , example: environmentIdentifier= '3weyt6hhn8qcvb'
            environmentIdentifier=environment_id,
            # give corresponding project identifier, example: projectIdentifier= '6tl4csoyrg16ef',
            projectIdentifier=project_id,
            enableSetting="ENABLED",
            # publishOnImport used to select whether assets are added to the inventory and/or discovery catalog .
            # publishOnImport = True : Assets will be added to project's inventory as well as published to the discovery catalog
            # publishOnImport = False : Assets will only be added to project's inventory.
            # You can later curate the metadata of the assets and choose subscription terms to publish them from the inventory to the discovery catalog.
            publishOnImport=False,
            # Automated business name generation : Use AI to automatically generate metadata for assets as they are published or updated by this data source run.
            # Automatically generated metadata can be be approved, rejected, or edited by data publishers.
            # Automatically generated metadata is badged with a small icon next to the corresponding metadata field.
            recommendation={"enableBusinessNameGeneration": True},
            type="GLUE",
            configuration={
                "glueRunConfiguration": {
                    "dataAccessRole": "arn:aws:iam::"
                    + account_id
                    + ":role/service-role/AmazonDataZoneGlueAccess-"
                    + current_region
                    + "-"
                    + domain_id
                    + "",
                    "relationalFilterConfigurations": [
                        {
                            #
                            "databaseName": glue_database_name,
                            "filterExpressions": [
                                {"expression": "*", "type": "INCLUDE"},
                            ],
                            #    "schemaName": "TestSchemaName",
                        },
                    ],
                },
            },
            # Add metadata forms to the data source (OPTIONAL).
            # Metadata forms will be automatically applied to any assets that are created by the data source.
            # assetFormsInput=[
            #     {
            #         "content": "string",
            #         "formName": "string",
            #         "typeIdentifier": "string",
            #         "typeRevision": "string",
            #     },
            # ],
            schedule={
                "schedule": "cron(5 20 * * ? *)",
                "timezone": "UTC",
            },
        )
        # This is a suggested syntax to return values
        #        return_values["data_source_creation"] = data_source_creation["items"]
        print("Data Source Created")


//This is the sample response payload after the CreateDataSource API is invoked:

{
    "Content":{
        "project_name": "Admin",
        "domain_name": "Drug-Research-and-Development",
        "env_name": "GlueEnvironment",
        "glue_database_name": "test",
        "data_source_name" : "test",
        "data_source_description" : "This is a test data source"
    }
}
```

## 整理和发布数据资产
<a name="curate-data-asset-gs-glue-api"></a>

您可以使用以下示例脚本在 Amazon DataZone 中整理和发布数据资产。

可使用以下脚本创建自定义表单类型：

```
 
def create_form_type(domainId, projectId):
    return dzclient.create_form_type(
        domainIdentifier = domainId,
        name = "customForm",
        model = {
            "smithy": "structure customForm { simple: String }"
        },
        owningProjectIdentifier = projectId,
        status = "ENABLED"
    )
```

可使用以下示例脚本创建自定义资产类型：

```
def create_custom_asset_type(domainId, projectId):
    return dzclient.create_asset_type(
        domainIdentifier = domainId,
        name = "userCustomAssetType",
        formsInput = {
            "Model": {
                "typeIdentifier": "customForm",
                "typeRevision": "1",
                "required": False
            }
        },
        owningProjectIdentifier = projectId,
    )
```

可使用以下示例脚本创建自定义资产：

```
def create_custom_asset(domainId, projectId):
    return dzclient.create_asset(
        domainIdentifier = domainId,
        name = 'custom asset',
        description = "custom asset",
        owningProjectIdentifier = projectId,
        typeIdentifier = "userCustomAssetType",
        formsInput = [
            {
                "formName": "UserCustomForm",
                "typeIdentifier": "customForm",
                "content": "{\"simple\":\"sample-catalogId\"}"
            }
        ]
    )
```

可使用以下示例脚本创建术语表：

```
def create_glossary(domainId, projectId):
    return dzclient.create_glossary(
        domainIdentifier = domainId,
        name = "test7",
        description = "this is a test glossary",
        owningProjectIdentifier = projectId
    )
```

可使用以下示例脚本创建术语表术语：

```
def create_glossary_term(domainId, glossaryId):
    return dzclient.create_glossary_term(
        domainIdentifier = domainId,
        name = "soccer",
        shortDescription = "this is a test glossary",
        glossaryIdentifier = glossaryId,
    )
```

可使用以下示例脚本通过系统定义的资产类型创建资产：

```
def create_asset(domainId, projectId):
    return dzclient.create_asset(
        domainIdentifier = domainId,
        name = 'sample asset name',
        description = "this is a glue table asset",
        owningProjectIdentifier = projectId,
        typeIdentifier = "amazon.datazone.GlueTableAssetType",
        formsInput = [
            {
                "formName": "GlueTableForm",
                "content": "{\"catalogId\":\"sample-catalogId\",\"columns\":[{\"columnDescription\":\"sample-columnDescription\",\"columnName\":\"sample-columnName\",\"dataType\":\"sample-dataType\",\"lakeFormationTags\":{\"sample-key1\":\"sample-value1\",\"sample-key2\":\"sample-value2\"}}],\"compressionType\":\"sample-compressionType\",\"lakeFormationDetails\":{\"lakeFormationManagedTable\":false,\"lakeFormationTags\":{\"sample-key1\":\"sample-value1\",\"sample-key2\":\"sample-value2\"}},\"primaryKeys\":[\"sample-Key1\",\"sample-Key2\"],\"region\":\"us-east-1\",\"sortKeys\":[\"sample-sortKey1\"],\"sourceClassification\":\"sample-sourceClassification\",\"sourceLocation\":\"sample-sourceLocation\",\"tableArn\":\"sample-tableArn\",\"tableDescription\":\"sample-tableDescription\",\"tableName\":\"sample-tableName\"}"
            }
        ]
    )
```

可使用以下示例脚本创建资产修订并附加术语表术语：

```
def create_asset_revision(domainId, assetId):
    return dzclient.create_asset_revision(
        domainIdentifier = domainId,
        identifier = assetId,
        name = 'glue table asset 7',
        description = "glue table asset description update",
        formsInput = [
            {
                "formName": "GlueTableForm",
                "content": "{\"catalogId\":\"sample-catalogId\",\"columns\":[{\"columnDescription\":\"sample-columnDescription\",\"columnName\":\"sample-columnName\",\"dataType\":\"sample-dataType\",\"lakeFormationTags\":{\"sample-key1\":\"sample-value1\",\"sample-key2\":\"sample-value2\"}}],\"compressionType\":\"sample-compressionType\",\"lakeFormationDetails\":{\"lakeFormationManagedTable\":false,\"lakeFormationTags\":{\"sample-key1\":\"sample-value1\",\"sample-key2\":\"sample-value2\"}},\"primaryKeys\":[\"sample-Key1\",\"sample-Key2\"],\"region\":\"us-east-1\",\"sortKeys\":[\"sample-sortKey1\"],\"sourceClassification\":\"sample-sourceClassification\",\"sourceLocation\":\"sample-sourceLocation\",\"tableArn\":\"sample-tableArn\",\"tableDescription\":\"sample-tableDescription\",\"tableName\":\"sample-tableName\"}"
            }
        ],
        glossaryTerms = ["<glossaryTermId:>"]
    )
```

可使用以下示例脚本发布资产：

```
def publish_asset(domainId, assetId):
    return dzclient.create_listing_change_set(
        domainIdentifier = domainId,
        entityIdentifier = assetId,
        entityType = "ASSET",
        action = "PUBLISH",
    )
```

## 搜索数据目录并订阅数据
<a name="search-catalog-subscribe-gs-glue-api"></a>

可使用以下示例脚本搜索数据目录并订阅数据：

```
def search_asset(domainId, projectId, text):
    return dzclient.search(
        domainIdentifier = domainId,
        owningProjectIdentifier = projectId,
        searchScope = "ASSET",
        searchText = text,
    )
```

可使用以下示例脚本获取资产的列表 ID：

```
def search_listings(domainId, assetName, assetId):
    listings = dzclient.search_listings(
        domainIdentifier=domainId,
        searchText=assetName,
        additionalAttributes=["FORMS"]
    )
    
    assetListing = None
    for listing in listings['items']:
        if listing['assetListing']['entityId'] == assetId: 
            assetListing = listing
    
    return listing['assetListing']['listingId']
```

可使用以下示例脚本通过列表 ID 创建订阅请求：

```
create_subscription_response = def create_subscription_request(domainId, projectId, listingId):
    return dzclient.create_subscription_request(
        subscribedPrincipals=[{
            "project": {
                "identifier": projectId
            }
        }],
        subscribedListings=[{
            "identifier": listingId
        }],
        requestReason="Give request reason here."
    )
```

使用`create_subscription_response`上述方法，使用以下示例脚本获取订阅，然后 accept/approve 进行订阅：` subscription_request_id`

```
subscription_request_id = create_subscription_response["id"]

def accept_subscription_request(domainId, subscriptionRequestId): 
    return dzclient.accept_subscription_request(
        domainIdentifier=domainId,
        identifier=subscriptionRequestId
    )
```

## 在数据目录中搜索资产
<a name="search-catalog-subscribe-gs-glue-api"></a>

您可以使用以下利用自由文本搜索的示例脚本在 Amazon DataZone 目录中查找您发布的数据资产（清单）。
+ 以下示例在域中执行自由文本关键字搜索，并返回与提供的关键字“credit”匹配的所有列表：

  ```
  aws datazone search-listings \
    --domain-identifier dzd_c1s7uxe71prrtz \
    --search-text "credit"
  ```
+ 也可以组合多个关键字以进一步缩小搜索范围。例如，如果要查找所有已发布的数据资产（列表），其中包含与墨西哥的销量相关的数据，则可以使用两个关键字“Mexico”和“sales”来制定查询。

  ```
              aws datazone search-listings \
    --domain-identifier dzd_c1s7uxe71prrtz \
    --search-text "mexico sales"
  ```

也可以使用筛选条件搜索列表。 SearchListings API 中的`filters`参数允许您从网域中检索经过筛选的结果。此 API 支持多个默认筛选条件，您也可以组合两个或更多筛选条件并对它们执行 AND/OR 操作。筛选条件句采用两个参数：属性和值。默认支持的筛选条件属性为 `typeName`、`owningProjectId` 和 `glossaryTerms`。
+ 以下示例使用 `assetType` 筛选条件（其中列表类型为 Redshift 表）在给定域中搜索所有列表。

  ```
              aws datazone search-listings \
  --domain-identifier dzd_c1s7uxe71prrtz \
  --filters '{"or":[{"filter":{"attribute":"typeName","value":"RedshiftTableAssetType"}} ]}'
  ```
+ 您也可以使用 AND/OR 操作将多个过滤器组合在一起。在以下示例中，可以组合 `typeName` 和 `project` 筛选条件。

  ```
              aws datazone search-listings \
  --domain-identifier dzd_c1s7uxe71prrtz \
  --filters '{"or":[{"filter":{"attribute":"typeName","value":"RedshiftTableAssetType"}},  {"filter":{"attribute":"owningProjectId","value":"cwrrjch7f5kppj"}} ]}'
  ```
+ 您甚至可以将自由文本搜索与过滤器结合使用来查找确切的结果，并按列表的 creation/last 更新时间对其进行进一步排序，如以下示例所示：

  ```
              aws datazone search-listings \
  --domain-identifier dzd_c1s7uxe71prrtz \
  --search-text "finance sales" \
  --filters '{"or":[{"filter":{"attribute":"typeName","value":"GlueTableViewType"}} ]}' \
  --sort '{"attribute": "UPDATED_AT", "order":"ASCENDING"}'
  ```

## 其他有用的示例脚本
<a name="other-useful-scripts-api"></a>

在 Amazon 中处理数据时，您可以使用以下示例脚本来完成各种任务 DataZone。

使用以下示例脚本列出现有的 Amazon DataZone 域名：

```
def list_domains():
    datazone = boto3.client('datazone')
    response = datazone.list_domains(status='AVAILABLE')
    [print("%12s | %16s | %12s | %52s" % (item['id'], item['name'], item['managedAccountId'], item['portalUrl'])) for item in response['items']]
    return
```

使用以下示例脚本列出现有的 Amazon DataZone 项目：

```
def list_projects(domain_id):
    datazone = boto3.client('datazone')
    response = datazone.list_projects(domainIdentifier=domain_id)
    [print("%12s | %16s " % (item['id'], item['name'])) for item in response['items']]
    return
```

使用以下示例脚本列出现有的 Amazon DataZone 元数据表单：

```
def list_metadata_forms(domain_id):
    datazone = boto3.client('datazone')
    response = datazone.search_types(domainIdentifier=domain_id, 
        managed=False,
        searchScope='FORM_TYPE')
    [print("%16s | %16s | %3s | %8s" % (item['formTypeItem']['name'], item['formTypeItem']['owningProjectId'],item['formTypeItem']['revision'], item['formTypeItem']['status'])) for item in response['items']]
    return
```