

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

# 分析
<a name="analytics-pattern-list"></a>

**Topics**
+ [在 Microsoft SQL Server Analysis Services 中分析 Amazon Redshift 数据](analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services.md)
+ [使用 Amazon Athena 和 Amazon Quick Sight 分析和可视化嵌套的 JSON 数据](analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.md)
+ [自动将数据从 Amazon S3 AWS Data Exchange 中提取数据](automate-data-ingestion-from-aws-data-exchange-into-amazon-s3.md)
+ [使用 AWS CloudFormation 模板在 AWS Glue 中自动执行加密](automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template.md)
+ [使用 AWS DataOps 开发套件构建数据管道以提取、转换和分析 Google Analytics 数据](build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit.md)
+ [通过 Amazon Kinesis Video Streams 和 AWS Fargate 构建视频处理管道](build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate.md)
+ [使用 AWS Glue 构建 ETL 服务管道以增量方式将数据从 Amazon S3 加载到 Amazon Redshift](build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue.md)
+ [使用 Amazon 构建企业数据网格 DataZone AWS CDK，以及 AWS CloudFormation](build-enterprise-data-mesh-amazon-data-zone.md)
+ [通过 Amazon Web Services 计算风险价值 (VaR)](calculate-value-at-risk-var-by-using-aws-services.md)
+ [使用 Amazon Athena 来配置对共享 AWS Glue Data Catalog 的跨账户存取](configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena.md)
+ [将 Teradata 标准化时态功能转换为 Amazon Redshift SQL](convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql.md)
+ [将 Teradata RESET WHEN 功能转换为 Amazon Redshift SQL](convert-the-teradata-reset-when-feature-to-amazon-redshift-sql.md)
+ [使用基础设施即代码，在 Amazon Web Services Cloud 上部署和管理无服务器数据湖](deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code.md)
+ [启动时强制标记 Amazon EMR 集群](enforce-tagging-of-amazon-emr-clusters-at-launch.md)
+ [确保在启动时启用 Amazon EMR 日志记录到 Amazon S3](ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch.md)
+ [使用 AWS Glue 作业和 Python 生成测试数据](generate-test-data-using-an-aws-glue-job-and-python.md)
+ [使用 Amazon IoT Greengrass 将物联网数据直接摄取至 Amazon S3，经济实惠](cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.md)
+ [使用 Lambda 函数在瞬态 EMR 集群中启动 Spark 作业](launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function.md)
+ [使用 AWS Glue 将 Apache Cassandra 工作负载迁移到 Amazon Keyspaces](migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.md)
+ [将 Oracle 商业智能 12c 从本地服务器迁移到 Amazon Web Services Cloud](migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.md)
+ [将 ELK 堆栈迁移至 Elastic Cloud on AWS](migrate-an-elk-stack-to-elastic-cloud-on-aws.md)
+ [使用 Starburs AWS 云 t 将数据迁移到](migrate-data-to-the-aws-cloud-by-using-starburst.md)
+ [优化 AWS 输入文件大小的 ETL 摄取](optimize-the-etl-ingestion-of-input-file-size-on-aws.md)
+ [使用验证、转换和分区编排 ETL 管道 AWS Step Functions](orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.md)
+ [使用 Amazon Redshift ML 执行高级分析](perform-advanced-analytics-using-amazon-redshift-ml.md)
+ [使用 Amazon Athena 通过 SQL 查询 Amazon DynamoDB 表](query-amazon-dynamodb-tables-sql-amazon-athena.md)
+ [使用 Athena 访问、查询和联接 Amazon DynamoDB 表](access-query-and-join-amazon-dynamodb-tables-using-athena.md)
+ [使用标量 Python UDF 为 Amazon Redshift 查询结果设置特定于语言的排序](set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf.md)
+ [将 Lambda 函数，以接收来自不同 AWS 区域中的 S3 存储桶的事件通知](subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions.md)
+ [三种用于将数据转换为 Apache Parquet 的 AWS Glue ETL 作业类型](three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet.md)
+ [使用亚马逊 Athena 和亚马逊可视化 Amazon Redshift 审计日志 QuickSight](visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight.md)
+ [使用 Amazon Quick Sight 可视化所有 AWS 账户的 IAM 凭证报告](visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.md)
+ [更多模式](analytics-more-patterns-pattern-list.md)

# 在 Microsoft SQL Server Analysis Services 中分析 Amazon Redshift 数据
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services"></a>

*Sunil Vora，Amazon Web Services*

## Summary
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-summary"></a>

此模式描述了如何使用 Intellisoft OLE 数据库提供程序或 CData ADO.NET 提供程序进行数据库访问来连接和分析微软 SQL Server 分析服务中的 Amazon Redshift 数据。

Amazon Redshift 是云中一种完全托管的 PB 级数据仓库服务。SQL Server Analysis Services 是一种联机分析处理（OLAP）系统工具，可用于分析来自数据集市和数据仓库（如 Amazon Redshift）的数据。可以使用SQL Server Analysis Services从数据创建 OLAP 多维数据集，以便进行快速、高级的数据分析。 

## 先决条件和限制
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-prereqs"></a>

**假设**
+ 此模式描述了如何在亚马逊弹性计算云（亚马逊）实例上为亚马逊 Redshift 设置 SQL Server 分析服务和 Intellisof CData t OLE 数据库提供商或 ADO.NET 提供商。 EC2或者，您可以将两者安装在公司数据中心的主机上。

**先决条件**
+ 一个活跃的 AWS 账户
+ 具有凭证的 Amazon Redshift 集群

## 架构
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-architecture"></a>

**源技术堆栈**
+ Amazon Redshift 集群

**目标技术堆栈**
+ Microsoft SQL Server Analysis Services

**源架构和目标架构**

![\[在 Microsoft SQL Server Analysis Services 中分析 Amazon Redshift 数据\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e444fec0-e00f-4cc6-acc6-4ffc61b654a0/images/6f29dab5-1ea7-452f-9b07-d1d23ae469a2.png)


## 工具
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-tools"></a>
+ [Microsoft Visual Studio 2019 (Community Edition)](https://visualstudio.microsoft.com/vs/)
+ [适用于亚马逊 Redshift 的 Intellisoft OLE 数据库提供商（试用版）或亚马逊 Redshift 的 ADO.NET CData 提供商](https://www.cdata.com/kb/tech/redshift-ado-ssas.rst)[（试用版）](https://www.pgoledb.com/index.php?option=com_filecabinet&view=files&id=1&Itemid=68)

## 操作说明
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-epics"></a>

### 分析表
<a name="analyze-tables"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 分析要导入的表和数据。 | 确定要导入的 Amazon Redshift 表及其大小。 | 数据库管理员 | 

### 设置 EC2 实例并安装工具
<a name="set-up-ec2-instance-and-install-tools"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 EC2 实例。 | 在您的 AWS 账户中，在私有或公有子网中创建 EC2 实例。 | 系统管理员 | 
| 安装用于数据库访问的工具。 | 下载并安装适用于亚马逊 [Redshift 的 Intellisoft OLE 数据库提供程序（或亚马逊 Redshift](https://www.pgoledb.com/index.php?option=com_filecabinet&view=files&id=1&Itemid=68) 的 ADO.NET [CData 提供商](https://www.cdata.com/kb/tech/redshift-ado-ssas.rst)）。  | 系统管理员 | 
| 安装 Visual Studio。 | 下载并安装 [Visual Studio 2019（社区版）](https://visualstudio.microsoft.com/vs/)。  | 系统管理员 | 
| 安装扩展。 | 在 Visual Studio 中安装 **Microsoft Analysis Services 项目**扩展。 | 系统管理员 | 
| 创建项目。 | 在 Visual Studio 中创建新的表格模型项目以存储 Amazon Redshift 数据。在 Visual Studio 中，创建项目时选择 **Analysis Services 表格项目**选项。 | 数据库管理员 | 

### 创建数据来源和导入表
<a name="create-data-source-and-import-tables"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon Redshift 数据来源。 | 使用适用于亚马逊 Redshift 的 Intellisoft OLE 数据库提供商（或亚马逊 Redshift 的 ADO.NET 提供商 CData ）和您的亚马逊 Redshift 凭证创建亚马逊 Redshift 数据源。 | Amazon Redshift、数据库管理员 | 
| 导入表。 | 从 Amazon Redshift 选择表和视图并将其导入到 SQL Server Analysis Services 项目中。 | Amazon Redshift、数据库管理员 | 

### 迁移后清理
<a name="clean-up-after-migration"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除实 EC2 例。 | 删除您之前启动的 EC2 实例。 | 系统管理员 | 

## 相关资源
<a name="analyze-amazon-redshift-data-in-microsoft-sql-server-analysis-services-resources"></a>
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/)（AWS 文档）
+ [安装 SQL Server Analysis Services](https://docs.microsoft.com/en-us/analysis-services/instances/install-windows/install-analysis-services?view=asallproducts-allversions)（Microsoft 文档）
+ [表格模型设计器](https://docs.microsoft.com/en-us/analysis-services/tabular-models/tabular-model-designer-ssas?view=asallproducts-allversions)（Microsoft 文档）
+ [用于高级分析的 OLAP 多维数据集概述](https://docs.microsoft.com/en-us/system-center/scsm/olap-cubes-overview?view=sc-sm-2019)（Microsoft 文档）
+ [Microsoft Visual Studio 2019 (Community Edition)](https://visualstudio.microsoft.com/vs/)
+ [适用于 Amazon Redshift 的 Intellisoft OLE DB Provider（试用版）](https://www.pgoledb.com/index.php?option=com_filecabinet&view=files&id=1&Itemid=68) 
+ [CData 亚马逊 Redshift 的 ADO.NET 提供商（试用版）](https://www.cdata.com/kb/tech/redshift-ado-ssas.rst)

# 使用 Amazon Athena 和 Amazon Quick Sight 分析和可视化嵌套的 JSON 数据
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight"></a>

*Anoop Singh，Amazon Web Services*

## Summary
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-summary"></a>

此模式说明了如何使用 Amazon Athena 将嵌套的、JSON 格式的数据结构转换为表格视图，然后在 Amazon Quick Sight 中可视化数据。

您可以将 JSON 格式的数据用于来自操作系统的 API 驱动的数据源，以创建数据产品。这些数据还可以帮助您更好地了解客户及其与产品的互动，便于您量身定制用户体验并预测结果。

## 先决条件和限制
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 表示嵌套数据结构的 JSON 文件（此模式提供了示例文件）

**限制:**
+ JSON 功能与 Athena 中现有的面向 SQL 的函数很好地集成。但是，它们与 ANSI SQL 不兼容，并且 JSON 文件应将每条记录放在单独的行中。您可能需要使用 Athena 中的 `ignore.malformed.json` 属性来指示是否应将格式错误的 JSON 记录转换为空字符或生成错误。有关更多信息，请参阅 Athena 文档中的[读取 JSON 数据的最佳实践](https://docs.aws.amazon.com/athena/latest/ug/parsing-JSON.html)。
+ 此模式仅考虑简单、少量的 JSON 格式数据。如果要大规模使用这些概念，可以考虑应用数据分区并将数据整合到更大的文件中。

## 架构
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-architecture"></a>

下图显示了此模式的架构和工作流。嵌套的数据结构以 JSON 格式存储在 Amazon Simple Storage Service（Amazon S3）中。在 Athena 中，JSON 数据映射到 Athena 数据结构。然后，您可以创建一个视图来分析数据，并在 Quick Sight 中可视化数据结构。

![\[在 AWS 上分析和可视化嵌套的 JSON 数据。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e9ad39a1-e0a4-4429-bdc0-594b68707761/images/474e8747-626f-468c-9c27-c007af79bf2d.png)


## 工具
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-tools"></a>

**Amazon Web Services**
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。此模式使用 Amazon S3 来存储 JSON 文件。
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一种交互式查询服务，可帮助您使用标准 SQL 直接在 Amazon S3 中分析数据。此模式使用 Athena 来查询和转换 JSON 数据。只需在中执行一些操作 AWS 管理控制台，您就可以将 Athena 指向您在 Amazon S3 中的数据，然后使用标准 SQL 来运行一次性查询。Athena 没有服务器，因此您无需设置或管理任何基础设施，且只需为您运行的查询付费。Athena 可自动扩展且并行执行查询，因此，即使在数据集很大、查询很复杂的情况下也能很快获得结果。    
+ [Amazon Quick Sight](https://docs.aws.amazon.com/quicksuite/latest/userguide/quick-bi.html) 是一项云规模的商业智能 (BI) 服务，可帮助您在单个控制面板上可视化、分析和报告数据。Quick Sight 可让您轻松创建和发布包含机器学习 (ML) 见解的交互式仪表板。您可以从任何设备访问这些控制面板，并将其嵌入到您的应用程序、门户和网站中。

**示例代码**

下面的 JSON 文件提供了可以在此模式中使用的嵌套数据结构。

```
{
  "symbol": "AAPL",
  "financials": [
    {
      "reportDate": "2017-03-31",
      "grossProfit": 20591000000,
      "costOfRevenue": 32305000000,
      "operatingRevenue": 52896000000,
      "totalRevenue": 52896000000,
      "operatingIncome": 14097000000,
      "netIncome": 11029000000,
      "researchAndDevelopment": 2776000000,
      "operatingExpense": 6494000000,
      "currentAssets": 101990000000,
      "totalAssets": 334532000000,
      "totalLiabilities": 200450000000,
      "currentCash": 15157000000,
      "currentDebt": 13991000000,
      "totalCash": 67101000000,
      "totalDebt": 98522000000,
      "shareholderEquity": 134082000000,
      "cashChange": -1214000000,
      "cashFlow": 12523000000,
      "operatingGainsLosses": null
    }
  ]
}
```

## 操作说明
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-epics"></a>

### 设置 S3 存储桶
<a name="set-up-an-s3-bucket"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 S3 存储桶。 | 要创建用于存储 JSON 文件的存储桶，请登录并打开 [Amazon S3 控制台](https://console.aws.amazon.com/s3/)，然后选择**创建存储桶**。 AWS 管理控制台有关更多信息，请参阅 Amazon S3 文档中的[创建存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)。  | 系统管理员 | 
| 添加嵌套 JSON 数据。 | 将您的 JSON 文件上传到 S3 存储桶。有关示例 JSON 文件，请参阅上一部分的内容。有关说明，请参阅 Amazon S3 文档中的[上传对象](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)。 | 系统管理员 | 

### 在 Athena 中分析数据
<a name="analyze-data-in-ate"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建用于映射 JSON 数据的表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html)有关创建表的更多信息，请参阅 [Athena 文档](https://docs.aws.amazon.com/athena/latest/ug/creating-tables.html)。 | 开发者版 | 
| 创建数据分析的视图。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html)有关创建视图的更多信息，请参阅 [Athena 文档](https://docs.aws.amazon.com/athena/latest/ug/create-view.html)。 | 开发者版 | 
| 分析和验证数据。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html) | 开发者版 | 

### 在快速视图中可视化数据
<a name="visualize-data-in-qsight"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 Quick Sight 中将 Athena 设置为数据源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html) | 系统管理员 | 
| 使用 Quick Sight 可视化数据 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight.html) | 数据分析人员 | 

## 相关资源
<a name="analyze-and-visualize-nested-json-data-with-amazon-athena-and-amazon-quicksight-resources"></a>
+ [Amazon Athena 文档](https://docs.aws.amazon.com/athena/latest/ug/getting-started.html)
+ [Amazon 快速瞄准教程](https://docs.aws.amazon.com/quicksuite/latest/userguide/example-analysis.html)
+ [使用嵌套 JSON](https://aws.amazon.com/blogs/big-data/create-tables-in-amazon-athena-from-nested-json-and-mappings-using-jsonserde/)（博客文章）

# 自动将数据从 Amazon S3 AWS Data Exchange 中提取数据
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3"></a>

*Adnan Alvee 和 Manikanta Gona，Amazon Web Services*

## Summary
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-summary"></a>

此模式提供了一个 CloudFormation 模板，使您能够自动将数据从亚马逊简单存储服务 (Amazon S3) 中的数据提取 AWS Data Exchange 到您的数据湖中。 

AWS Data Exchange 是一项服务，可让您轻松安全地在 AWS 云中交换基于文件的数据集。 AWS Data Exchange 数据集是基于订阅的。作为订阅用户，您还可以在提供程序发布新数据时访问数据集修订版。 

该 CloudFormation 模板在 Amazon Events 中创建了一个 CloudWatch 事件和一个 AWS Lambda 函数。该事件将监视您所订阅的数据集是否有任何更新。如果有更新，则 CloudWatch 启动 Lambda 函数，该函数会将数据复制到您指定的 S3 存储桶。成功复制数据后，Lambda 将向您发送 Amazon Simple Notification Service(Amazon SNS) 通知。

## 先决条件和限制
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 订阅中的数据集 AWS Data Exchange

**限制**
+ 必须为中的每个订阅数据集单独部署 CloudFormation 模板。 AWS Data Exchange

## 架构
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-architecture"></a>

**目标技术堆栈**
+ AWS Lambda
+ Amazon S3
+ AWS Data Exchange
+ Amazon CloudWatch
+ Amazon SNS

**目标架构**

![\[CloudWatch 启动 Lambda 函数将数据复制到 S3 存储桶并发送 Amazon SNS 通知。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/059816dc-5a71-4942-9c7f-ac977072eebc/images/ec021620-47c1-4fb5-95a9-3b8985accc56.png)


**自动化和扩展**

对于要导入到数据湖中的数据集，您可以多次使用该 CloudFormation 模板。

## 工具
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-tools"></a>
+ [AWS Data Exchange](https://docs.aws.amazon.com/data-exchange/latest/userguide/what-is.html)使 AWS 客户可以轻松安全地交换中基于文件的数据集。 AWS 云作为订阅用户，您可查找和订阅来自合格数据提供商的数百种产品。然后，您可以快速下载数据集或将其复制到 Amazon S3，以便在各种 AWS 分析和机器学习服务中使用。任何拥有的人 AWS 账户 都可以成为 AWS Data Exchange 订阅者。
+ 利用 [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)，您可以运行代码，而无需预调配或管理服务器。Lambda 只在需要时运行您的代码，并自动进行扩展，从每天几个请求扩展到每秒数千个请求。您只需按消耗的计算时间付费；代码未运行时不产生费用。借助 Lambda，您几乎可以为任何类型的应用程序或后端服务运行代码，并且不必进行任何管理。Lambda 可在高可用性计算基础设施上运行代码，管理所有计算资源，其中包括服务器和操作系统维护、容量预调配和自动扩缩、代码监控和日志记录。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/gsg/GetStartedWithS3.html) 提供面向互联网的存储服务。您可以通过 Amazon S3 随时在 Web 上的任何位置存储和检索的任意大小的数据。
+ [Amazon CloudWatch ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) Events 提供近乎实时的系统事件流，这些事件描述了 AWS 资源的变化。使用可以快速设置的简单规则，您可以匹配事件并将它们路由到一个或多个目标函数或流。 CloudWatch 事件在发生时就会意识到操作变化。其可响应这些操作更改并在必要时采取纠正措施，方式是发送消息以响应环境、激活函数、进行更改并捕获状态信息。您还可以使用 Ev CloudWatch ents 来安排自动操作，这些操作在特定时间使用 **cron** 或**速率**表达式自行启动。
+ [Amazon Simple Notification Service（Amazon SNS）](https://docs.aws.amazon.com/sns/latest/dg/welcome.html)让应用程序、终端用户和设备可以即时发送和接收来自云的通知。Amazon SNS 为高吞吐量、基于推送的消息传递提供主题（通信渠道）。 many-to-many使用亚马逊 SNS 主题，发布者可以向大量订阅者分发消息以进行并行处理，包括亚马逊简单队列服务 (Amazon SQS) Simple Queue Service 队列、Lambda 函数和 webhook。 HTTP/S 您还可以使用 Amazon SNS，通过移动推送、SMS 和电子邮件向最终用户发送通知。

## 操作说明
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-epics"></a>

### 订阅数据集
<a name="subscribe-to-a-data-set"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 订阅数据集。 | 在 AWS Data Exchange 控制台中，订阅数据集。有关说明，请参阅 AWS 文档 AWS Data Exchange中的[订阅数据产品](https://docs.aws.amazon.com/data-exchange/latest/userguide/subscribe-to-data-sets.html)。 | 常规 AWS | 
| 注意数据集的属性。 | 记下数据集的 AWS 区域、ID 和修订版 ID。在下一步中，你将需要这个作为 CloudFormation 模板。 | 常规 AWS | 

### 部署 CloudFormation 模板
<a name="deploy-the-cfn-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 S3 存储桶和文件夹。 | 如果您在 Amazon S3 中已经有数据湖，请创建一个文件夹来存储要从中 AWS Data Exchange提取的数据。如果您要为测试部署模板，请创建新的 S3 存储桶，并记下存储桶名称和文件夹前缀，以供下一步使用。 | 常规 AWS | 
| 部署 CloudFormation 模板。 | 部署作为该模式附件提供的 CloudFormation 模板。有关说明，请参阅 [CloudFormation 文档](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。将以下参数配置为与您的 AWS 账户、数据集和 S3 存储桶设置相对应：**数据集 AWS 区域****、数据集 ID**、**修订版 ID**、**S3 存储桶名称**（例如`DOC-EXAMPLE-BUCKET`）、**文件夹前缀**（例如`myfolder/`）和用**于 SNS 通知的电子邮件**。您可将**数据集名称**参数设置为任何名称。部署模板时，它会运行 Lambda 函数，以自动摄取数据集中可用的第一组数据。随后，当新数据到达数据集时，后续摄取将自动进行。 | 常规 AWS | 

## 相关资源
<a name="automate-data-ingestion-from-aws-data-exchange-into-amazon-s3-resources"></a>
+ [在 AWS Data Exchange（AWS Data Exchange 文档）上订阅数据产品](https://docs.aws.amazon.com/data-exchange/latest/userguide/subscribe-to-data-sets.html)

## 附件
<a name="attachments-059816dc-5a71-4942-9c7f-ac977072eebc"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/059816dc-5a71-4942-9c7f-ac977072eebc/attachments/attachment.zip)

# 使用 AWS CloudFormation 模板在 AWS Glue 中自动执行加密
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template"></a>

*Diogo Guedes，Amazon Web Services*

## Summary
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-summary"></a>

此模式向您展示如何使用 AWS CloudFormation 模板在 AWS Glue 中设置和自动执行加密。该模板创建强制加密所需所有配置和资源。这些资源包括初始配置、由亚马逊 EventBridge 规则创建的预防性控制和 AWS Lambda 函数。

## 先决条件和限制
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户
+ 部署 CloudFormation 模板及其资源的权限

**限制**

这种安全控制为区域性的。您必须在每个要对 AWS Glue 中设置加密强制性的AWS 区域 部署安全控件。

## 架构
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-architecture"></a>

**目标技术堆栈**
+ 亚马逊 CloudWatch 日志（来自 AWS Lambda）
+ 亚马逊 EventBridge 规则
+ AWS CloudFormation 堆栈
+ AWS CloudTrail
+ AWS Identity and Access Management (IAM) 托管角色和策略
+ AWS Key Management Service (AWS KMS)
+ AWS KMS 别名
+ AWS Lambda 函数
+ AWS Systems Manager Parameter Store

**目标架构**

下图显示了如何在 AWS Glue 中自动执行加密。

![\[该图显示了如何使用 CloudFormation 模板在 AWS Glue 中自动执行加密。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/d50d0659-5592-44d0-8fcb-7a2983712640/images/272a7fb2-ecbc-41f7-a556-d555e4e39a59.png)


下图显示了如下工作流：

1. [CloudFormation 模板](https://github.com/aws-samples/aws-custom-guardrail-event-driven/blob/main/CloudFormation/aws-custom-guardrail-event-driven.yaml)可创建所有资源，包括在 AWS Glue 中强制执行加密的初始配置和侦测控制。

1.  EventBridge 规则检测到加密配置中的状态变化。

1. 通过 CloudWatch 日志调用 Lambda 函数进行评估和记录。对于不合规性检测，通过 AWS KMS 密钥的 Amazon 资源名称（ARN）恢复 Parameter Store。该服务已修复为启用加密的合规状态。

**自动化和扩展**

如果您使用的是 [AWS Org](https://aws.amazon.com/organizations/) anizations，则可以使用 [AWS](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) 将此模板部署 CloudFormation StackSets到要在 AWS Glue 中启用加密强制执行的多个账户中。

## 工具
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-tools"></a>
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和在 AWS 上运行的应用程序的指标。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一项无服务器事件总线服务，可帮助您将应用程序与来自各种来源的实时数据连接起来。例如，Lambda 函数、使用 API 目标的 HTTP 调用端点或其他 AWS 账户中的事件总线。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可帮助您设置 AWS 资源，快速一致地配置这些资源，并在 AWS 账户和区域的整个生命周期中对其进行管理。
+ [AWS CloudTrail 可帮助您对 AWS](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) 账户进行运营和风险审计、监管和合规。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一项完全托管的提取、转换、加载（ETL）服务。它可以帮助您在数据存储和数据流之间对数据进行可靠地分类、清理、扩充和移动。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可帮助您创建和控制加密密钥，以帮助保护您的数据。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，而无需预置或管理服务器。它仅在需要时运行您的代码，并且能自动扩缩，因此您只需为使用的计算时间付费。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可帮助您管理在 Amazon Web Services Cloud 中运行的应用程序和基础设施。它简化了应用程序和资源管理，缩短了检测和解决操作问题的时间，并帮助您大规模安全地管理 AWS 资源。

**代码**

此模式的代码可在 GitHub [aws-custom-guardrail-event驱动的存储库中](https://github.com/aws-samples/aws-custom-guardrail-event-driven/blob/main/CloudFormation/aws-custom-guardrail-event-driven.yaml)找到。

## 最佳实践
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-best-practices"></a>

AWS Glue 支持静态数据加密，用于[在 AWS Glue 中编写作业](https://docs.aws.amazon.com/glue/latest/dg/author-job-glue.html)和[使用开发端点开发脚本](https://docs.aws.amazon.com/glue/latest/dg/dev-endpoint.html)。

考虑下面的最佳实践：
+ 配置 ETL 作业和开发端点，以使用 AWS KMS 密钥写入加密的静态数据。
+ 您可通过 AWS KMS 托管的密钥，对存储在 [AWS Glue Data Catalog](https://docs.aws.amazon.com/glue/latest/dg/components-overview.html#data-catalog-intro) 中的元数据加密。
+ 使用AWS KMS 密钥来加密作业书签以及[爬网程序](https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html)和 ETL 作业生成的日志。

## 操作说明
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-epics"></a>

### 启动 CloudFormation 模板
<a name="launch-the-cloudformation-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 CloudFormation 模板。 | 从 GitHub [存储库](https://github.com/aws-samples/aws-custom-guardrail-event-driven/blob/main/CloudFormation/aws-custom-guardrail-event-driven.yaml)下载`aws-custom-guardrail-event-driven.yaml`模板，然后[部署](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/deploy/index.html)该模板。`CREATE_COMPLETE` 状态表示您的模板已成功部署。此模板不需要输入参数。 | 云架构师 | 

### 验证 AWS Glue 中的加密设置
<a name="verify-the-encryption-settings-in-aws-glue"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 检查 AWS KMS 密钥配置。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template.html) | 云架构师 | 

### 测试加密强制执行
<a name="test-the-encryption-enforcement"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在中标识加密设置 CloudFormation。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template.html) | 云架构师 | 
| 将已配置的基础设施切换至不合规状态。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template.html)在您清除复选框后，防护机制会检测 AWS Glue 中的不合规状态，然后通过自动修复加密错误配置来强制合规。因此刷新页面后，应再次选中加密复选框。 | 云架构师 | 

## 相关资源
<a name="automate-encryption-enforcement-in-aws-glue-using-an-aws-cloudformation-template-resources"></a>
+ 在 [AWS CloudFormation 控制台上创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)（AWS CloudFormation 文档）
+ 使用 [AWS 创建在 AWS API 调用时触发 CloudWatch 的事件规则 CloudTrail](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/Create-CloudWatch-Events-CloudTrail-Rule.html)（亚马逊 CloudWatch 文档）
+ [在 AWS Glue 中设置加密](https://docs.aws.amazon.com/glue/latest/dg/set-up-encryption.html)（AWS Glue 文档）

# 使用 AWS DataOps 开发套件构建数据管道以提取、转换和分析 Google Analytics 数据
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit"></a>

*Anton Kukushkin 和 Rudy Puig，Amazon Web Services*

## Summary
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-summary"></a>

此模式描述了如何使用 AWS DataOps 开发套件 (AWS DDK) 等构建数据管道来提取、转换和分析 Google Analytics 数据。 AWS 服务 AWS DDK 是一个开源开发框架，可帮助您在上 AWS面构建数据工作流程和现代数据架构。 AWS DDK 的主要目标之一是为您节省通常用于劳动密集型数据管道任务的时间和精力，例如协调管道、构建基础设施和创建基础架构。 DevOps 您可以将这些劳动密集型任务卸载到 AWS DDK，这样您就可以专注于编写代码和其他高价值的活动。

## 先决条件和限制
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 已[配置](https://docs.aws.amazon.com/appflow/latest/userguide/google-analytics.html)用于谷歌分析的 Amazon AppFlow 连接器
+ [Python](https://www.python.org/downloads/) 和 [pip](https://pip.pypa.io/en/stable/cli/pip_download/)（Python 的包管理器）
+ Git，已安装和[配置](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup)
+ AWS Command Line Interface (AWS CLI)，[已安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)并[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)
+ AWS Cloud Development Kit (AWS CDK)，[已安装](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install)

**产品版本**
+ Python 3.7 或更高版本
+ pip 9.0.3 或更高版本

## 架构
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-architecture"></a>

**技术堆栈**
+ Amazon AppFlow
+ Amazon Athena
+ Amazon CloudWatch
+ Amazon EventBridge
+ Amazon Simple Storage Service（Amazon S3）
+ Amazon Simple Queue Service（Amazon SQS）
+ AWS DataOps 开发套件 (AWS DDK)
+ AWS Lambda

**目标架构**

下图显示了摄取、转换和分析 Google Analytics 数据的事件驱动流程。

![\[使用 AWS 服务摄取、转换和分析 Google Analytics 数据。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/edf40222-2867-4d4a-9153-ab29785b6662/images/8c38b472-153b-4497-982c-8efb97d2f7a5.png)


下图显示了如下工作流：

1. 亚马逊 CloudWatch 计划的事件规则会调用亚马逊。 AppFlow

1. 亚马逊将谷 AppFlow 歌分析数据提取到 S3 存储桶中。

1. 在 S3 存储桶提取数据后，将生成中的 EventBridge 事件通知，由 CloudWatch 事件规则捕获，然后将其放入 Amazon SQS 队列中。

1. Lambda 函数使用来自 Amazon SQS 队列的事件，读取相应的 S3 对象，将对象转换为 Apache Parquet 格式，将转换后的对象写入 S3 存储桶，然后创建或更新表定义。 AWS Glue Data Catalog 

1. Athena 查询针对此表运行。

## 工具
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-tools"></a>

**AWS 工具**
+ [Amazon AppFlow](https://docs.aws.amazon.com/appflow/latest/userguide/what-is-appflow.html) 是一项完全托管的集成服务，使您能够在软件即服务 (SaaS) 应用程序之间安全地交换数据。
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一种交互式查询服务，可帮助您使用标准 SQL 直接在 Amazon S3 中分析数据。
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和运行的应用程序 AWS 的指标。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一项无服务器事件总线服务，可帮助您将应用程序与来自各种来源的实时数据连接起来。例如， AWS Lambda 函数、使用 API 目的地的 HTTP 调用端点或其他 AWS 账户目的地的事件总线。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [Amazon Simple Queue Service（Amazon SQS）](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html)提供了一个安全、持久且可用的托管队列，它可帮助您集成和分离分布式软件系统与组件。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)是一个框架，用于在代码中定义云基础架构并通过它进行配置 CloudFormation。
+ [AWS DataOps 开发套件 (AWS DDK)](https://github.com/awslabs/aws-ddk) 是一个开源开发框架，可帮助您在上 AWS面构建数据工作流程和现代数据架构。

**代码**

此模式的代码可在 GitHub [AWS DataOps 开发套件 (AWS DDK)](https://github.com/awslabs/aws-ddk) 和[使用亚马逊 AppFlow、Amazon Athena AWS DataOps 和开发套件存储库分析谷歌分析数据](https://github.com/aws-samples/aws-ddk-examples/tree/main/google-analytics-data-using-appflow/python)中找到。

## 操作说明
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-epics"></a>

### 准备环境
<a name="prepare-the-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆源代码。 | 要克隆源代码，请运行以下命令：<pre>git clone https://github.com/aws-samples/aws-ddk-examples.git</pre> | DevOps 工程师 | 
| 创建虚拟环境。 | 导航到源代码目录，然后运行以下命令创建虚拟环境：<pre>cd google-analytics-data-using-appflow/python && python3 -m venv .venv</pre> | DevOps 工程师 | 
| 安装依赖项。 | 要激活虚拟环境并安装依赖项，请运行以下命令：<pre>source .venv/bin/activate && pip install -r requirements.txt</pre> | DevOps 工程师 | 

### 部署使用您数据管线的应用程序
<a name="deploy-the-application-that-uses-your-data-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 引导 环境。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit.html) | DevOps 工程师 | 
| 部署数据。 | 要部署数据管线，请运行 `cdk deploy --profile [AWS_PROFILE]` 命令。 | DevOps 工程师 | 

### 测试部署
<a name="test-the-deployment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证堆栈状态。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit.html) | DevOps 工程师 | 

## 问题排查
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 如果在创建 `AWS::AppFlow::Flow` 资源期间部署失败，您会收到以下错误：`Connector Profile with name ga-connection does not exist` | 确认您已为 Google Analytics（分析）创建了亚马逊 AppFlow 连接器并将其命名`ga-connection`。有关说明，请参阅亚马逊 AppFlow 文档中的[谷歌分析](https://docs.aws.amazon.com/appflow/latest/userguide/google-analytics.html)。 | 

## 相关资源
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-resources"></a>
+ [AWS DataOps 开发套件 (AWS DDK) (GitHub)](https://github.com/awslabs/aws-ddk)
+ [AWS DDK 示例](https://github.com/aws-samples/aws-ddk-examples) () GitHub

## 附加信息
<a name="build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit-additional"></a>

AWS DDK 数据管道由一个或多个阶段组成。在以下代码示例中，您使用 `AppFlowIngestionStage` 从 Google Analytics 摄取数据，使用 `SqsToLambdaStage` 处理数据转换，使用 `AthenaSQLStage` 运行 Athena 查询。

首先，创建数据转换和摄取阶段，如以下代码示例所示：

```
        appflow_stage = AppFlowIngestionStage(
            self,
            id="appflow-stage",
            flow_name=flow.flow_name,
        )
        sqs_lambda_stage = SqsToLambdaStage(
            self,
            id="lambda-stage",
            lambda_function_props={
                "code": Code.from_asset("./ddk_app/lambda_handlers"),
                "handler": "handler.lambda_handler",
                "layers": [
                    LayerVersion.from_layer_version_arn(
                        self,
                        id="layer",
                        layer_version_arn=f"arn:aws:lambda:{self.region}:336392948345:layer:AWSDataWrangler-Python39:1",
                    )
                ],
                "runtime": Runtime.PYTHON_3_9,
            },
        )
        # Grant lambda function S3 read & write permissions
        bucket.grant_read_write(sqs_lambda_stage.function)
        # Grant Glue database & table permissions
        sqs_lambda_stage.function.add_to_role_policy(
            self._get_glue_db_iam_policy(database_name=database.database_name)
        )
        athena_stage = AthenaSQLStage(
            self,
            id="athena-sql",
            query_string=[
                (
                    "SELECT year, month, day, device, count(user_count) as cnt "
                    f"FROM {database.database_name}.ga_sample "
                    "GROUP BY year, month, day, device "
                    "ORDER BY cnt DESC "
                    "LIMIT 10; "
                )
            ],
            output_location=Location(
                bucket_name=bucket.bucket_name, object_key="query-results/"
            ),
            additional_role_policy_statements=[
                self._get_glue_db_iam_policy(database_name=database.database_name)
            ],
        )
```

接下来，使用该`DataPipeline`构造通过使用 EventBridge 规则将各个阶段 “连接” 在一起，如以下代码示例所示：

```
        (
            DataPipeline(self, id="ingestion-pipeline")
            .add_stage(
                stage=appflow_stage,
                override_rule=Rule(
                    self,
                    "schedule-rule",
                    schedule=Schedule.rate(Duration.hours(1)),
                    targets=appflow_stage.targets,
                ),
            )
            .add_stage(
                stage=sqs_lambda_stage,
                # By default, AppFlowIngestionStage stage emits an event after the flow run finishes successfully
                # Override rule below changes that behavior to call the the stage when data lands in the bucket instead
                override_rule=Rule(
                    self,
                    "s3-object-created-rule",
                    event_pattern=EventPattern(
                        source=["aws.s3"],
                        detail={
                            "bucket": {"name": [bucket.bucket_name]},
                            "object": {"key": [{"prefix": "ga-data"}]},
                        },
                        detail_type=["Object Created"],
                    ),
                    targets=sqs_lambda_stage.targets,
                ),
            )
            .add_stage(stage=athena_stage)
        )
```

有关更多代码示例，请参阅[使用亚马逊、Amazon AppFlow Athena AWS DataOps 和开发套件 GitHub 分析谷歌分析数据存储库](https://github.com/aws-samples/aws-ddk-examples/tree/main/google-analytics-data-using-appflow/python)。

# 通过 Amazon Kinesis Video Streams 和 AWS Fargate 构建视频处理管道
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate"></a>

*Piotr Chotkowski 和 Pushparaju Thangavel，Amazon Web Services*

## Summary
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-summary"></a>

此模式演示了如何使用[Amazon Kinesis Video Streams](https://aws.amazon.com/kinesis/video-streams/) 和 [AWS Fargate](https://aws.amazon.com/fargate) 从视频流中提取帧并将其存储为图像文件，以便 [Amazon Simple Storage Service (Amazon S3](https://aws.amazon.com/s3/)) 进行进一步处理。 

该模式以 Java Maven 项目的形式提供了示例应用程序。此应用程序使用 [AWS Cloud Development Kit](https://aws.amazon.com/cdk/) (AWS CDK) 定义 AWS 基础设施。帧处理逻辑和基础设施定义均采用 Java 编程语言编写。您可将此示例应用程序用作开发自己的实时视频处理管道或构建机器学习管道的视频预处理步骤的基础。 

## 先决条件和限制
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户
+ Java SE Development Kit (JDK) 11，已安装
+ [Apache Maven](https://maven.apache.org/)，已安装
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)，已安装
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)版本 2，已安装
+ [Docker](https://docs.docker.com/get-docker/)（构建 Docker 映像以在 AWS Fargate 任务定义中使用）

**限制**

该模式旨在作为概念证明，或作为进一步开发的基础。不应在生产部署中以当前形式使用它。

**产品版本**
+ [此模式已在 AWS CDK 版本 1.77.0 中进行了测试（参见 AWS CDK 版本）](https://docs.aws.amazon.com/cdk/api/latest/versions.html)
+ JDK 11
+ AWS CLI 版本 2

## 架构
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-architecture"></a>

**目标技术堆栈**
+ Amazon Kinesis Video Streams
+ AWS Fargate 任务
+ Amazon Simple Queue Service（Amazon SQS）队列
+ 亚马逊 S3 存储桶

**目标架构**

![\[使用 Kinesis Video Streams 和 Fargate 构建视频处理管道的架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/9d1442c2-f3ee-47fd-8cce-90d9206ce4d4/images/a60e585f-27be-4dd6-897b-c38adf1d283f.png)


用户创建 Kinesis 视频流、上传视频并将包含有关输入 Kinesis 视频流和输出 S3 存储桶的详细信息的 JSON 消息发送到 SQS 队列。AWS Fargate 在容器中运行主应用程序，从 SQS 队列中提取消息并开始提取帧。每帧都保存在图像文件中，并存储在目标 S3 存储桶中。

**自动化和扩缩**

该示例应用程序可以在单个 AWS 区域内进行水平和垂直扩展。可以通过增加从 SQS 队列读取的已部署 AWS Fargate 任务的数量来实现水平扩展。垂直缩放可以通过增加应用程序中的帧分割和图像发布线程的数量来实现。在 AWS CDK 的[QueueProcessingFargateService](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs-patterns.QueueProcessingFargateService.html)资源定义中，这些设置作为环境变量传递给应用程序。由于 AWS CDK 堆栈部署的性质，您无需额外努力即可在多个 AWS 区域和账户中部署此应用程序。

## 工具
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-tools"></a>

**工具**
+ [AWS CDK](https://aws.amazon.com/cdk/) 是一个软件开发框架，用于使用编程语言（例如、、Python TypeScript JavaScript、Java 和 C\$1/Net）来定义您的云基础设施和资源。
+ [Amazon Kinesis Video Streams](https://aws.amazon.com/kinesis/video-streams/) 是一项完全托管的 Amazon Web Services，您可使用该服务将实时视频从各个设备流式传输到 Amazon Web Services Cloud，或者构建应用程序以进行实时视频处理或进行面向批处理的视频分析。
+ [AWS Fargate](https://aws.amazon.com/fargate) 是适用于容器的无服务器计算引擎。Fargate 无需配置和管理服务器，让您可专注于开发应用程序。
+ [Amazon S3](https://aws.amazon.com/s3/) 是一种对象存储服务，提供可扩展性、数据可用性、安全性和性能。
+ [Amazon SQS](https://aws.amazon.com/sqs/) 是一种完全托管的消息队列服务，使您能够分离和扩展微服务、分布式系统和无服务器应用程序。

**代码**
+ 随附示例应用程序项目 (`frame-splitter-code.zip`) 的 .zip 文件。

## 操作说明
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-epics"></a>

### 部署基础设施
<a name="deploy-the-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动 Docker 守护程序。 | 在本地系统上启动 Docker 进程守护程序。AWS CDK 使用 Docker 构建 AWS Fargate 任务中使用的映象。继续执行下一步操作之前，必须运行 Docker。 | 开发人员、 DevOps 工程师 | 
| 构建项目。 | 下载 `frame-splitter-code` 示例应用程序（附件）并将其内容解压缩到本地计算机上的文件夹中。在部署基础设施之前，必须要先构建 [Java Maven](https://maven.apache.org/) 项目。在命令提示符处，导航至项目的根目录，然后通过运行以下命令来生成项目： <pre>mvn clean install</pre> | 开发人员、 DevOps 工程师 | 
| 引导 AWS CDK。 | （仅限首次使用 AWS CDK 的用户）如果这是您首次使用 AWS CDK，则可能需要通过运行 AWS CLI 命令来引导环境：<pre>cdk bootstrap --profile "$AWS_PROFILE_NAME" </pre>其中 `$AWS_PROFILE_NAME` 包含您的 AWS 凭证中的 AWS 个人资料的名称。或者，您可删除此参数以使用默认配置文件。有关更多信息，请参阅 [AWS CDK 文档](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)。 | 开发人员、 DevOps 工程师 | 
| 部署 AWS CDK 堆栈。 | 在此步骤中，您将在 AWS 账户中创建所需基础设施资源（SQS 队列、S3 存储桶、AWS Fargate 任务定义），构建 AWS Fargate 任务所需 Docker 映像，然后部署应用程序。在命令提示符处，导航至项目的根目录，然后运行以下命令：<pre>cdk deploy --profile "$AWS_PROFILE_NAME" --all </pre>其中 `$AWS_PROFILE_NAME` 包含您的 AWS 凭证中的 AWS 个人资料的名称。或者，您可删除此参数以使用默认配置文件。确认部署。注意 CDK 部署输出中的**QueueUrl**和**存储桶**值；您将在以后的步骤中使用这些值。AWS CDK 创建资产，将其上传至您的 AWS 账户，然后创建所有基础设施资源。您可以在 [AWS CloudFormation 控制台](https://console.aws.amazon.com/cloudformation/)中观察资源创建过程。有关更多信息，请参阅 [AWS CloudFormation 文档](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)和 [AWS CDK 文档](https://docs.aws.amazon.com/cdk/latest/guide/hello_world.html#hello_world_tutorial_deploy)。 | 开发人员、 DevOps 工程师 | 
| 创建视频流 | 在此步骤中，您将创建 Kinesis 视频流，该视频流将用作视频处理的输入流。确保您已经安装并配置 AWS CLI。在 AWS CLI 中运行：<pre>aws kinesisvideo --profile "$AWS_PROFILE_NAME" create-stream --stream-name "$STREAM_NAME" --data-retention-in-hours "24" </pre>其中，`$AWS_PROFILE_NAME` 包含您的 AWS 凭证中的 AWS 配置文件名称（或删除此参数以使用默认配置文件），`$STREAM_NAME` 是任何有效的直播名称。 或者，您可按照 [Kinesis Video Streams](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/gs-createstream.html#gs-createstream-console) 文档中的步骤使用 Kinesis 控制台创建视频流。记下创建的流的 AWS Resource Name (ARN)；稍后您会需要它。 | 开发人员、 DevOps 工程师 | 

### 运行示例
<a name="run-an-example"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将视频上传至流数据。 | 在示例 `frame-splitter-code` 应用程序的项目文件夹中，打开 `src/test/java/amazon/awscdk/examples/splitter` 文件夹中的 `ProcessingTaskTest.java` 文件。将 `profileName`** **和 `streamName`** **变量替换为您在前面的步骤中使用的值。若要将示例视频上传到您在上一步中创建的 Kinesis 视频流，请运行： <pre>amazon.awscdk.examples.splitter.ProcessingTaskTest#testExample test</pre>或者，您可使用 [Kinesis Video Streams](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk.html) 文档中描述的方法之一上传视频。 | 开发人员、 DevOps 工程师 | 
| 启动视频处理。 | 现在，您已将视频上传到 Kinesis 视频流，您可开始处理该视频了。要启动处理逻辑，您须向 AWS CDK 在部署期间创建的 SQS 队列发送一条包含详细信息的消息。要使用 AWS CLI 发送消息，请运行：<pre>aws sqs --profile "$AWS_PROFILE_NAME" send-message --queue-url QUEUE_URL --message-body MESSAGE </pre>其中`$AWS_PROFILE_NAME`包含您的 AWS 凭证中的 AWS 配置文件名称（删除此参数以使用默认配置文件），`QUEUE_URL`是 AWS CDK 输出中的**QueueUrl**值，`MESSAGE`是以下格式的 JSON 字符串： <pre>{ "streamARN": "STREAM_ARN", "bucket": "BUCKET_NAME", "s3Directory": "test-output" }</pre>其中，`STREAM_ARN` 是您在前面步骤中创建的视频流的 ARN，`BUCKET_NAME` 也是 AWS CDK 输出中的**存储桶**值。 发送此消息将启动视频处理。或者，您也可以使用 Amazon SQS 控制台发送消息，如 [Amazon SQS 文档](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-using-send-messages.html)中所述。 | 开发人员、 DevOps 工程师 | 
| 查看视频帧图像。 | 您可在 S3 输出存储桶 `s3://BUCKET_NAME/test-output` 中看到生成的图像，其中 `BUCKET_NAME` 是 AWS CDK 输出中的**存储桶**值。 | 开发人员、 DevOps 工程师 | 

## 相关资源
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-resources"></a>
+ [AWS CDK 文档](https://docs.aws.amazon.com/cdk/latest/guide/home.html)
+ [AWS CDK API 参考](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html)
+ [AWS CDK 入门研讨会](https://cdkworkshop.com/)
+ [Amazon Kinesis Video Streams 文档](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/what-is-kinesis-video.html)
+ [示例：使用识别视频流中的对象 SageMaker](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-sagemaker.html)
+ [示例：解析和渲染 Kinesis 视频流片段](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-renderer.html)
+ [使用 Amazon Kinesis Video Streams 和亚马逊实时大规模分析直播视频（AWS Machin SageMaker](https://aws.amazon.com/blogs/machine-learning/analyze-live-video-at-scale-in-real-time-using-amazon-kinesis-video-streams-and-amazon-sagemaker/) e Learning 博客文章）
+ [AWS Fargate 入门](https://aws.amazon.com/fargate/getting-started/)

## 附加信息
<a name="build-a-video-processing-pipeline-by-using-amazon-kinesis-video-streams-and-aws-fargate-additional"></a>

**选择 IDE**

我们建议您使用自己喜欢的 Java IDE 构建和探索此项目。 

**清理**

运行完此示例后，请移除所有已部署的资源，以免产生额外的 AWS 基础设施成本。 

要删除基础设施和视频流，请在 AWS CLI 中使用以下两个命令：

```
cdk destroy --profile "$AWS_PROFILE_NAME" --all
```

```
aws kinesisvideo --profile "$AWS_PROFILE_NAME" delete-stream --stream-arn "$STREAM_ARN"
```

或者，您可以手动删除资源，方法是使用 AWS CloudFormation 控制台移除 AWS CloudFormation 堆栈，使用 Kinesis 控制台移除 Kinesis 视频流。请注意，`cdk destroy` 不会移除输出 S3 存储桶或 Amazon Elastic Container Registry (Amazon ECR) 存储库 (`aws-cdk/assets`) 中的图像。您必须手动将其移除。

## 附件
<a name="attachments-9d1442c2-f3ee-47fd-8cce-90d9206ce4d4"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/9d1442c2-f3ee-47fd-8cce-90d9206ce4d4/attachments/attachment.zip)

# 使用 AWS Glue 构建 ETL 服务管道以增量方式将数据从 Amazon S3 加载到 Amazon Redshift
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue"></a>

*Rohan Jamadagni 和 Arunabha Datta，Amazon Web Services*

## Summary
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-summary"></a>

此模式提供有关如何配置 Amazon Simple Storage Service (Amazon S3) 以获得最佳数据湖性能，然后使用 AWS Glue 将增量数据更改从 Amazon S3 加载到 Amazon Redshift 中，执行提取、转换、加载（ETL）操作的指导 。 

Amazon S3 中的源文件可以具有不同的格式，包括逗号分隔值 (CSV)、XML 和 JSON 文件。本示例介绍了如何使用 AWS Glue 将源文件转换为成本优化且性能优化的格式，例如 Apache Parquet。您可以直接从 Amazon Athena 和 Amazon Redshift Spectrum 查询 Parquet 文件。您还可以将 Parquet 文件加载到 Amazon Redshift 中，对其进行聚合，然后与消费者共享汇总数据，或者使用 Amazon Quick Sight 对数据进行可视化。

## 先决条件和限制
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 具有正确权限并包含 CSV、XML 或 JSON 文件的 S3 源存储桶。

**假设**
+ CSV、XML 或 JSON 源文件已加载到 Amazon S3 中，可以从配置 AWS Glue 和 Amazon Redshift 的账户进行访问。
+ 如 [Amazon Redshift 文档](https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-S3.html)中所述，遵循加载文件、拆分文件、压缩和使用清单的最佳实践。
+ 源文件结构保持不变。
+ 源系统能够按照 Amazon S3 中定义的文件夹结构将数据提取至 Amazon S3 中。
+ Amazon Redshift 集群可跨越单个可用区。(这种架构很合适，因为 AWS Lambda、AWS Glue 和 Amazon Athena 为无服务器。) 为了实现高可用性，定期拍摄集群快照。

**限制**
+ 文件格式仅限于 [AWS Glue 当前支持的格式](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-format.html)。
+ 不支持实时下游报告。

## 架构
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-architecture"></a>

**源技术堆栈**
+ 包含 CSV、XML 或 JSON 文件的 S3 存储桶

**目标技术堆栈**
+ S3 数据湖（带有分区 Parquet 文件存储）
+ Amazon Redshift

**目标架构**

![\[使用 AWS Glue 从 Amazon S3 到 Amazon Redshift 加载增量更改的架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/105b58ec-56c1-464a-8e69-f625360caa14/images/626aa365-e6e6-4874-a873-1c71adbe5306.png)


 

**数据流**

![\[使用 AWS Glue 从 Amazon S3 到 Amazon Redshift 加载增量更改的数据流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/105b58ec-56c1-464a-8e69-f625360caa14/images/29569e48-9f2d-4f48-bc59-1f33949d01ca.png)


## 工具
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-tools"></a>
+ [Amazon S3](https://aws.amazon.com/s3/) — Amazon Simple Storage Service（Amazon S3）是一项可扩展的数据存储服务。Amazon S3 可用于各种存储解决方案，包括网站、移动应用程序、备份和数据湖。
+ [AWS Lambda](https://aws.amazon.com/lambda/) – AWS Lambda 让您无需预置或管理服务器即可运行代码。AWS Lambda 是一项事件驱动的服务，您可以将代码设置为自动从其他 Amazon Web Services 启动。
+ [Amazon Redshift](https://aws.amazon.com/redshift/) — Amazon Redshift 是一种完全托管的 PB 级数据仓库服务。借助 Amazon Redshift，您可以使用标准 SQL 跨数据仓库和数据湖查询 PB 级的结构化和半结构化数据。
+ [AWS Glue](https://aws.amazon.com/glue/) — AWS Glue 是一项完全托管的 ETL 服务，可让客户轻松准备和加载数据以进行分析。AWS Glue 发现您的数据并将关联的元数据（例如表定义和架构）存储在 AWS Glue Data Catalog 中。分类后的数据立即变得可搜索、可查询和可用于 ETL。
+ [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/) — AWS Secrets Manager 有助于保护和集中管理应用程序或服务访问所需密钥。该服务存储数据库凭证、API 密钥和其他机密，并且无需以明文格式对敏感信息进行硬编码。Secrets Manager 还提供密钥轮换，以满足安全和合规性需求。它内置了 Amazon Redshift、Amazon Relational Database Service（Amazon RDS）和 Amazon DocumentDB 的集成。你可以使用 Secrets Manager 控制台、命令行界面 (CLI) 或 Secrets Manager API 来存储和集中管理密钥。 SDKs
+ [Amazon Athena](https://aws.amazon.com/athena/) — Amazon Athena 是一种交互式查询服务，可让您轻松分析存储在 Amazon S3 中的数据。Athena 是无服务器的，可与 AWS Glue 集成，因此它可以直接查询使用 AWS Glue 编目的数据。Athena 可弹性扩展以提供交互式查询性能。

## 操作说明
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-epics"></a>

### 创建 S3 存储桶与文件夹结构
<a name="create-the-s3-buckets-and-folder-structure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 分析源系统的数据结构与属性。 | 对参与 Amazon S3 数据湖的每个数据来源执行此任务。 | 数据工程师 | 
| 定义分区与访问策略。 | 该策略应基于数据捕获的频率、增量处理以及消耗需求。确保 S3 存储桶不向公众开放，并且访问仅由基于特定服务角色的策略控制。有关更多信息，请参阅 [Amazon S3 文档](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/using-folders.html)。 | 数据工程师 | 
| 为每种数据来源类型创建单独的 S3 存储桶，为每个数据来源创建单独的 S3 存储桶 (Parquet)，为每个数据来源创建单独的 S3 存储桶。 | 为每个源创建一个单独的存储桶，然后根据源系统的数据提取频率创建文件夹结构，例如 `s3://source-system-name/date/hour`。对于已处理的 (转换为 Parquet 格式) 文件，请创建类似的结构，例如 `s3://source-processed-bucket/date/hour`。有关创建 S3 存储桶的更多信息，请参阅 [Amazon S3 文档](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/create-bucket.html)。 | 数据工程师 | 

### 在 Amazon Redshift 中创建数据仓库
<a name="create-a-data-warehouse-in-amazon-redshift"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用适当的参数组以及维护和备份策略启动 Amazon Redshift 集群。 | 创建 Amazon Redshift 集群时，使用 Secrets Manager 数据库密钥作为管理员用户凭证。有关创建和调整 Amazon Redshift 集群规模的信息，请参阅 [Amazon Redshift 文档](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/event-publishing-redshift-cluster.html)和 [Sizing Cloud Data Warehouses](https://d1.awsstatic.com/whitepapers/Size-Cloud-Data-Warehouse-on-AWS.pdf) 白皮书。 | 数据工程师 | 
| 创建 IAM 服务角色，并将其附加至 Amazon Redshift 集群。 | AWS Identity and Access Management (IAM) 服务角色确保对 Secrets Manager 和源 S3 存储桶的访问。有关更多信息，请参阅有关[授权](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html)和[添加角色](https://docs.aws.amazon.com/redshift/latest/dg/c-getting-started-using-spectrum-add-role.html)的 AWS 文档。 | 数据工程师 | 
| 创建数据库架构。 | 遵循设计表的 Amazon Redshift 最佳实践。根据用例，选择适当的排序和分配键，以及最佳的压缩编码。有关最佳实践，请参阅 [AWS 文档](https://docs.aws.amazon.com/redshift/latest/dg/c_designing-tables-best-practices.html)。 | 数据工程师 | 
| 配置工作负载管理。 | 根据您的要求配置工作负载管理 (WLM) 队列、短查询加速 (SQA) 或者并发扩展。有关更多信息，请参阅 Amazon Redshift 文档中的[实施工作负载管理](https://docs.aws.amazon.com/redshift/latest/dg/cm-c-implementing-workload-management.html)。 | 数据工程师 | 

### 在 Secrets Manager 中创建密钥
<a name="create-a-secret-in-secrets-manager"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个新密钥以将 Amazon Redshift 登录凭证存储在 Secrets Manager 中。 | 此机密存储管理员用户以及各个数据库服务用户的凭证。有关说明，请参阅 [Secrets Manager 文档](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)。选择 **Amazon Redshift 集群**作为密钥类型。此外，在**密钥轮换**页面，打开轮换。这将在 Amazon Redshift 集群中创建适当的用户，并按定义的时间间隔轮换密钥。 | 数据工程师 | 
| 创建 IAM policy 以限制 Secrets Manager 访问权限。 | 将 Secrets Manager 的访问权限限制为仅限 Amazon Redshift 管理员和 AWS Glue。 | 数据工程师 | 

### 配置 AWS Glue
<a name="configure-aws-glue"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 AWS Glue Data Catalog 中，为 Amazon Redshift 添加连接。 | 有关说明，请参阅 [AWS Glue 文档](https://docs.aws.amazon.com/glue/latest/dg/console-connections.html)。 | 数据工程师 | 
| 创建并附加 AWS Glue 的 IAM 服务角色，以访问 Secrets Manager、Amazon Redshift 和 S3 存储桶。 | 有关更多信息，请参阅 [AWS Glue 文档](https://docs.aws.amazon.com/glue/latest/dg/create-service-policy.html)。 | 数据工程师 | 
| 为数据源定义 AWS Glue Data Catalog。 | 此步骤涉及在 AWS Glue Data Catalog 中创建数据库和所需表。您可使用爬网程序对 AWS Glue 数据库中的表进行编目，也可以将其定义为 Amazon Athena 外部表。您还可以通过 AWS Glue Data Catalog 访问在 Athena 中定义的外部表。有关在 Athena 中[定义数据目录](https://docs.aws.amazon.com/glue/latest/dg/populate-data-catalog.html)和[创建外部表](https://docs.aws.amazon.com/athena/latest/ug/creating-tables.html)的更多信息，请参阅 AWS 文档。 | 数据工程师 | 
| 创建 AWS Glue 作业来处理源数据。 | AWS Glue 任务可以是 Python 外壳，也可以 PySpark 用于对源数据文件进行标准化、重复数据删除和清理。为了优化性能并避免查询整个 S3 源存储桶，请按日期对 S3 存储桶进行分区，按年、月、日和小时细分，作为 AWS Glue 作业的下推谓词。有关更多信息，请参阅 [AWS Glue 文档](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-partitions.html)。将处理和转换后的数据以 Parquet 格式加载至已处理的 S3 存储桶分区。您可从 Athena 查询 Parquet 文件。 | 数据工程师 | 
| 创建 AWS Glue 作业以将数据加载至 Amazon Redshift 中。 | AWS Glue 任务可以是 Python 外壳，也可以 PySpark 通过更新数据然后完全刷新来加载数据。有关详细信息，请参阅 [AWS Glue 文档](https://docs.aws.amazon.com/glue/latest/dg/author-job.html)和*其他信息*部分。 | 数据工程师 | 
| （可选）必要时使用触发器安排 AWS Glue 作业。 | 增量数据加载主要由 Amazon S3 事件驱动，该事件导致 AWS Lambda 函数调用 AWS Glue 作业。对于需要基于时间而不是基于事件的调度的任何数据加载，使用基于 AWS Glue 触发器的调度。 | 数据工程师 | 

### 创建 Lambda 函数
<a name="create-a-lambda-function"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 AWS Lambda 创建并附加 IAM 服务相关角色，以访问 S3 存储桶和 AWS Glue 作业。 | 为 AWS Lambda 创建 IAM 服务相关角色，并使用读取 Amazon S3 对象和存储桶的策略以及访问 AWS Glue API 以启动 AWS Glue 作业的策略。有关更多信息，请参阅[知识中心](https://aws.amazon.com/premiumsupport/knowledge-center/lambda-execution-role-s3-bucket/)。 | 数据工程师 | 
| 创建 Lambda 函数，以根据定义的 Amazon S3 事件运行 AWS Glue 任务。 | Lambda 函数应通过创建 Amazon S3 清单文件来启动。Lambda 函数应将 Amazon S3 文件夹位置（例如 source\$1bucket/year/month/date/hour）作为参数传递给 AWS Glue 作业。AWS Glue 作业将使用此参数作为下推谓词，以优化文件访问和作业处理性能。有关更多信息，请参阅 [AWS Glue 文档](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-calling.html)。 | 数据工程师 | 
| 创建 Amazon S3 PUT 对象事件以检测对象创建，并调用相应的 Lambda 函数。 | Amazon S3 PUT 对象事件只能通过创建清单文件启动。清单文件控制 Lambda 函数和 AWS Glue 作业并发性，并批量处理负载，而不是处理到达 S3 源存储桶的特定分区的单个文件。有关更多信息，请参阅 [Lambda 文档](https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html)。 | 数据工程师 | 

## 相关资源
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-resources"></a>
+ [Amazon S3 文档](https://docs.aws.amazon.com/AmazonS3/latest/gsg/GetStartedWithS3.html)
+ [AWS Glue 文档](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html)
+ [Amazon Redshift 文档](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html)
+ [AWS Lambda](https://aws.amazon.com/lambda/)
+ [Amazon Athena](https://aws.amazon.com/athena/)
+ [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/)

## 附加信息
<a name="build-an-etl-service-pipeline-to-load-data-incrementally-from-amazon-s3-to-amazon-redshift-using-aws-glue-additional"></a>

**更新插入和完全刷新的详细方法**

**更新插入**：这适用于需要历史汇总的数据集，具体取决于业务用例。根据您的业务需求，按照[更新和插入新数据](https://docs.aws.amazon.com/redshift/latest/dg/t_updating-inserting-using-staging-tables-.html)（Amazon Redshift 文档）中描述的方法之一进行操作。

**完全刷新**：适用于不需要历史聚合的小数据集。请遵循以下方法之一：

1. 截断 Amazon Redshift 表。

1. 从暂存区加载当前分区

或者：

1. 创建包含当前分区数据的临时表。

1. 删除目标 Amazon Redshift 表。

1. 将临时表重命名至目标表。

# 使用 Amazon 构建企业数据网格 DataZone AWS CDK，以及 AWS CloudFormation
<a name="build-enterprise-data-mesh-amazon-data-zone"></a>

*Dhrubajyoti Mukherjee、Ravi Kumar、Weizhou Sun 和 Adjoa Taylor，Amazon Web Services*

## Summary
<a name="build-enterprise-data-mesh-amazon-data-zone-summary"></a>

在 Amazon Web Services（AWS），客户明白数据是加速创新和提高企业商业价值的关键。为了管理这些海量数据，您可以采用分散式架构，例如数据网格。数据网格架构促进了产品思维，这种思维方式会考虑到客户、目标和市场。数据网格还有助于建立联合治理模型，通过该模型可以快速、安全地访问您的数据。

[在 AWS上构建基于数据网格的企业解决方案的策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/strategy-data-mesh/introduction.html)讨论了如何使用数据网格策略框架为组织制定和实施数据网格策略。通过使用数据网格策略框架，您可以优化团队的组织及其互动，从而加快数据网格之旅。

本文档提供了有关如何使用 [Amazon](https://docs.aws.amazon.com/datazone/latest/userguide/what-is-datazone.html) 构建企业数据网格的指导 DataZone。Amazon DataZone 是一项数据管理服务，用于编目、发现、共享和管理存储在本地和第三方来源的数据。 AWS该模式包括代码工件，可帮助您使用和部署基于数据网格的数据解决方案基础架构。 AWS Cloud Development Kit (AWS CDK) AWS CloudFormation此模式适用于云架构师和 DevOps 工程师。

有关此模式的目标和解决方案范围的信息，请参阅[其他信息](#build-enterprise-data-mesh-amazon-data-zone-additional)部分。

## 先决条件和限制
<a name="build-enterprise-data-mesh-amazon-data-zone-prereqs"></a>

**先决条件**
+ 至少有两个活跃账户 AWS 账户：一个用于中央治理账户，另一个用于成员账户
+ AWS 开发环境中中央治理账户的管理员凭证
+ AWS Command Line Interface (AWS CLI) [已安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)，用于 AWS 服务 从命令行管理你的
+ [安装](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)了 Node.js 和 Node Package Manager (npm) 来管理应用程序 AWS CDK 
+ AWS CDK 使用 npm 在全球范围内[安装](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install)工具包，用于合成和部署应用程序 AWS CDK 

  ```
  npm install -g aws-cdk
  ```
+ 您的开发环境中安装了 3.12 版 Python
+ TypeScript 安装在您的开发环境中或使用 npm 编译器全局安装：

  ```
  npm install -g typescript
  ```
+ Docker 已安装在您的开发环境中
+ 使用版本控制系统（例如 Git）来维护解决方案的源代码（推荐）
+ 支持 Python 和（强烈推荐）的集成开发环境 TypeScript (IDE) 或文本编辑器

**限制**
+ 此解决方案仅在运行 Linux 或 macOS 的计算机上进行了测试。
+ 在当前版本中，该解决方案默认不支持Amazon DataZone AWS IAM Identity Center 的集成。但是，您可以将其配置为支持此集成。

**产品版本**
+ Python 版本 3.12

## 架构
<a name="build-enterprise-data-mesh-amazon-data-zone-architecture"></a>

下图显示的是数据网格参考架构。该架构基于亚马逊，使用亚马逊 DataZone 简单存储服务 (Amazon S3) Simple S3 作为数据 AWS Glue Data Catalog 源。根据贵组织的要求 AWS 服务 ，您在数据网格实施 DataZone 中与 Amazon 搭配使用的可能有所不同。

![\[成员账户和中央治理账户的五步工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/79056dd9-e669-4302-afb8-21e3e0e8a136/images/eacbffca-4f25-405a-a7c8-f89d0fee5682.png)


1. 在生产者账户中，原始数据要么适合以当前形式使用，要么通过使用进行转换以供使用 AWS Glue。数据的技术元数据存储在 Amazon S3 中，并使用 AWS Glue 数据爬虫进行评估。数据质量使用 [AWS Glue 数据质量](https://docs.aws.amazon.com/glue/latest/dg/glue-data-quality.html)来衡量。数据目录中的源数据库已注册为亚马逊 DataZone 目录中的资产。亚马逊 DataZone 目录使用亚马逊 DataZone 数据源任务托管在中央管理账户中。

1. 中央管理账户托管亚马逊 DataZone 域名和亚马逊 DataZone 数据门户。数据生产者和使用者与 Amazon DataZone 域名相关联。 AWS 账户 数据生产者和消费者的亚马逊 DataZone 项目是在相应的亚马逊 DataZone 域名单位下组织的。

1. 数据资产的最终用户使用其 AWS Identity and Access Management (IAM) 证书或单点登录（通过 IAM 身份中心集成）登录亚马逊 DataZone 数据门户。他们搜索、筛选和查看 Amazon 数据目录中的资产信息（例如，数据质量信息或业务和技术元 DataZone 数据）。

1. 最终用户找到他们想要的数据资产后，他们会使用 Amazon DataZone 订阅功能来请求访问权限。创建者团队的数据所有者会收到通知，并在 Amazon DataZone 数据门户中评估订阅请求。数据所有者根据订阅请求的有效性批准或拒绝订阅请求。

1. 在批准并完成订阅请求后，可以在消费者账户中访问该资产，用于进行以下活动：
   + 使用 Amazon AI 开发人工智能/机器学习模型 SageMaker 
   + 使用 Amazon Athena 和 Amazon Quick 进行分析和报告

## 工具
<a name="build-enterprise-data-mesh-amazon-data-zone-tools"></a>

**AWS 服务**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一种交互式查询服务，可帮助您通过使用标准 SQL 直接分析 Amazon Simple Storage Service（Amazon S3）中的数据。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)是一个软件开发框架，可帮助您在代码中定义和配置 AWS 云 基础架构。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在和的整个 AWS 账户 生命周期中对其进行管理 AWS 区域。
+ [Amazon DataZone](https://docs.aws.amazon.com/datazone/latest/userguide/what-is-datazone.html) 是一项数据管理服务，可帮助您编目、发现、共享和管理存储在本地和第三方来源中的数据。 AWS
+ [Amazon Quick](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) 是一项云规模的商业智能 (BI) 服务，可帮助您在单个控制面板中可视化、分析和报告数据。
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/?id=docs_gateway) 是一项托管机器学习 (ML) 服务，可帮助您构建和训练机器学习模型，然后将其部署到生产就绪的托管环境中。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [Amazon Simple Queue Service（Amazon SQS）](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html)提供了一个安全、持久且可用的托管队列，它可帮助您集成和分离分布式软件系统与组件。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**代码存储库 **

该解决方案可在 GitHub [data-mesh-datazone-cdk-cloudformation 存储库](https://github.com/aws-samples/data-mesh-datazone-cdk-cloudformation)中找到。

## 操作说明
<a name="build-enterprise-data-mesh-amazon-data-zone-epics"></a>

### 设置环境
<a name="set-up-the-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要克隆存储库，请在您的本地开发环境（Linux 或 macOS）中运行以下命令：<pre>git clone https://github.com/aws-samples/data-mesh-datazone-cdk-cloudformation</pre> | 云架构师、 DevOps 工程师 | 
| 创建环境。 | 要创建 Python 虚拟环境，请运行以下命令：<pre> python3 -m venv .venv<br /> source .venv/bin/activate<br /> pip install -r requirements.txt</pre> | 云架构师、 DevOps 工程师 | 
| 引导账户。 | 要使用引导中央治理帐户 AWS CDK，请运行以下命令：<pre>cdk bootstrap aws://<GOVERNANCE_ACCOUNT_ID>/<AWS_REGION></pre>登录 AWS 管理控制台，打开中央治理账户控制台，获取 AWS CDK 执行角色的 Amazon 资源名称 (ARN)。 | 云架构师、 DevOps 工程师 | 
| 构造 `DzDataMeshMemberStackSet.yaml` 文件。 | 要从存储库的根目录构造 `DzDataMeshMemberStackSet.yaml` 文件，请启动以下 bash 脚本：<pre>./lib/scripts/create_dz_data_mesh_member_stack_set.sh</pre> | 云架构师、 DevOps 工程师 | 
| 确认模板创建。 | 确保 CloudFormation 模板文件是在该`lib/cfn-templates/DzDataMeshMemberStackSet.yaml`位置创建的。 | 云架构师、 DevOps 工程师 | 

### 在中央治理账户中部署资源
<a name="deploy-resources-in-the-central-governance-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 修改配置。 | 在 `config/Config.ts` 文件中，修改以下参数：<pre>DZ_APPLICATION_NAME - Name of the application.<br />DZ_STAGE_NAME - Name of the stage. <br />DZ_DOMAIN_NAME - Name of the Amazon DataZone domain<br />DZ_DOMAIN_DESCRIPTION - Description of the Amazon DataZone domain<br />DZ_DOMAIN_TAG - Tag of the Amazon DataZone domain<br />DZ_ADMIN_PROJECT_NAME - Name of the Amazon DataZone project for administrators<br />DZ_ADMIN_PROJECT_DESCRIPTION - Description of the Amazon DataZone project for administrators<br />CDK_EXEC_ROLE_ARN - ARN of the cdk execution role<br />DZ_ADMIN_ROLE_ARN - ARN of the administrator role</pre>将其余参数留空。 | 云架构师、 DevOps 工程师 | 
| 更新 Amazon DataZone 词汇表配置。 | 要更新`lib/utils/glossary_config.json`文件中的 Amazon DataZone 词汇表配置，请使用以下示例配置：<pre>{<br />    "GlossaryName": "PII Data",<br />    "GlossaryDescription": "If data source contains PII attributes",<br />    "GlossaryTerms": [{<br />            "Name": "Yes",<br />            "ShortDescription": "Yes",<br />            "LongDescription": "Yes Glossary Term"<br />        },<br />        {<br />            "Name": "No",<br />            "ShortDescription": "No",<br />            "LongDescription": "No Glossary Term"<br />        }<br />    ]<br />}</pre> | 云架构师、 DevOps 工程师 | 
| 更新 Amazon DataZone 元数据表单配置。 | 要更新中的 Amazon DataZone 元数据表单配置`lib/utils/metadata_form_config.json file`，请使用以下示例配置：<pre>{<br />    "FormName": "ScheduleDataRefresh",<br />    "FormDescription": "Form for data refresh schedule",<br />    "FormSmithyModel": "@amazon.datazone#displayname(defaultName: \"Data Refresh Schedule\")\nstructure ScheduleDataRefresh {\n    @documentation(\"Schedule of Data Refresh\")\n    @required\n    @amazon.datazone#searchable\n    @amazon.datazone#displayname(defaultName: \"Data Refresh Schedule\")\n    data_refresh_schedule: String\n}"<br />}</pre> | 云架构师、 DevOps 工程师 | 
| 导出 AWS 凭证。 | 要将具有管理权限的 IAM 角色的 AWS 证书导出到您的开发环境，请使用以下格式：<pre>export AWS_ACCESS_KEY_ID=<br />export AWS_SECRET_ACCESS_KEY=<br />export AWS_SESSION_TOKEN=</pre> | 云架构师、 DevOps 工程师 | 
| 合成模板。 | 要合成 CloudFormation 模板，请运行以下命令：<pre>npx cdk synth</pre> | 云架构师、 DevOps 工程师 | 
| 部署解决方案。 | 要部署解决方案，请运行以下命令：<pre>npx cdk deploy --all</pre> | 云架构师、 DevOps 工程师 | 

### 配置新成员账户
<a name="configure-new-member-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 模板。 | 使用以下输入参数部署`lib/cfn-templates/DzDataMeshCfnStackSetExecutionRole.yaml`位于成员账户中的 CloudFormation 模板： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 云架构师、 DevOps 工程师 | 
| 更新 ARNs. | 要更新成员账户的 CloudFormation StackSet 执行角色 ARNs 列表，请使用以下代码：<pre>DZ_MEMBER_STACK_SET_EXEC_ROLE_LIST  - List of Stack set execution role arns for the member accounts.</pre> | 云架构师、 DevOps 工程师 | 
| 合成和部署。 | 要合成 CloudFormation 模板并部署解决方案，请运行以下命令：<pre>npx cdk synth<br />npx cdk deploy --all</pre> | 云架构师、 DevOps 工程师 | 
| 关联成员账户。 | 要将成员账户与中央治理账户关联，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 云架构师、 DevOps 工程师 | 
| 更新参数。 | 要更新 `config/Config.ts` 的配置文件中特定于成员账户的参数，请使用以下格式：<pre>export const DZ_MEMBER_ACCOUNT_CONFIG: memberAccountConfig = {<br />  '123456789012' : {<br />    PROJECT_NAME: 'TEST-PROJECT-123456789012',<br />    PROJECT_DESCRIPTION: 'TEST-PROJECT-123456789012',<br />    PROJECT_EMAIL: 'user@xyz.com'<br />  }<br />}</pre> | 云架构师、 DevOps 工程师 | 
| 合成和部署模板。 | 要合成 CloudFormation 模板并部署解决方案，请运行以下命令：<pre>npx cdk synth<br />npx cdk deploy --all</pre> | 云架构师、 DevOps 工程师 | 
| 添加成员账户。 | 要在数据解决方案中创建和配置其他成员账户，请对每个成员账户重复上述步骤。该解决方案不区分数据生产者和使用者。 | 云架构师、 DevOps 工程师 | 

### 清理
<a name="clean-up"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 取消成员账户的关联。 | 要解除账户关联，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 云架构师、 DevOps 工程师 | 
| 删除堆栈实例。 | 要删除 CloudFormation 堆栈实例，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 云架构师、 DevOps 工程师 | 
| 销毁所有资源。 | 要销毁资源，请在本地开发环境（Linux 或 macOS）中执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/build-enterprise-data-mesh-amazon-data-zone.html) | 云架构师、 DevOps 工程师 | 

## 相关资源
<a name="build-enterprise-data-mesh-amazon-data-zone-resources"></a>
+ [Amazon DataZone 数据快速入 AWS Glue 门](https://docs.aws.amazon.com/datazone/latest/userguide/quickstart-glue.html)
+ [教程：创建你的第一个 AWS CDK 应用程序](https://docs.aws.amazon.com/cdk/v2/guide/hello_world.html)
+ [入门 CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/GettingStarted.html)
+ [在上构建基于数据网格的企业解决方案的策略 AWS](https://docs.aws.amazon.com/prescriptive-guidance/latest/strategy-data-mesh/introduction.html)

## 附加信息
<a name="build-enterprise-data-mesh-amazon-data-zone-additional"></a>

**目标**

实施此模式可实现以下效果：
+ **分散的数据所有权** –将数据所有权从中央团队转移到代表组织源系统、业务部门或使用案例的团队。
+ **产品思维** − 在考虑组织中的数据资产时，引入了一种基于产品的思维方式，包括客户、市场和其他因素。
+ **联合治理** ‒ 改善组织数据产品的安全护栏、控制和合规性。
+ **多账户和多项目支持** − 支持组织各业务部门或项目之间高效、安全地共享数据和协作。
+ **集中监控和通知**-使用 Amazon 监控数据网格的云资源 CloudWatch，并在关联新成员账户时通知用户。
+ **可扩展性和可延伸性** − 随着组织的发展，向数据网格中添加新的使用案例。

**解决方案范围**

使用此解决方案时，您可以从小规模开始，并随着数据网格之旅的进展进行扩展。通常，当成员账户采用数据解决方案时，它包含特定于组织、项目或业务部门的账户配置。该解决方案通过支持以下功能来适应这些不同的 AWS 账户 配置：
+ AWS Glue 数据目录作为亚马逊的数据源 DataZone
+ 管理 Amazon DataZone 数据域和相关数据门户
+ 管理在基于数据网格的数据解决方案中添加成员账户
+ Amazon DataZone 项目和环境的管理
+ 管理 Amazon DataZone 词汇表和元数据表单
+ 管理与基于数据网格的数据解决方案用户相对应的 IAM 角色
+ 通知基于数据网格的数据解决方案用户
+ 监控已预调配的云基础设施

  该解决方案使用 AWS CDK 和 CloudFormation 来部署云基础架构。它 CloudFormation 用于执行以下操作：
  + 在较低的抽象级别上定义和部署云资源。
  + 部署来自的云资源 AWS 管理控制台。使用这种方法，您可以在没有开发环境的情况下部署基础设施。

  数据网格解决方案用于 AWS CDK 在更高的抽象级别上定义资源。因此，该解决方案通过选择相关工具来部署云资源，提供了一种解耦、模块化且可扩展的方法。

**后续步骤**

您可以联系 AWS[专家](https://aws.amazon.com/professional-services)，获取有关使用 Amazon 构建数据网格的指导 DataZone。

该解决方案的模块化性质支持使用不同的架构（例如数据纺织架构和数据湖）构建数据管理解决方案。此外，根据贵组织的要求，您可以将解决方案扩展到其他 Amazon DataZone 数据源。

# 通过 Amazon Web Services 计算风险价值 (VaR)
<a name="calculate-value-at-risk-var-by-using-aws-services"></a>

*Sumon Samanta，Amazon Web Services*

## Summary
<a name="calculate-value-at-risk-var-by-using-aws-services-summary"></a>

此示例介绍了如何使用 Amazon Web Services 实现风险价值 (VaR) 计算系统。在本地环境中，大多数 VaR 系统使用大型专用基础设施以及内部或商用电网调度软件来运行批处理流程。这种模式提供了一种简单、可靠且可扩展的架构，用于处理 Amazon Web Services Cloud 中的 VaR 处理。它构建了一个无服务器架构，该架构使用亚马逊Kinesis Data Streams作为流媒体服务，使用亚马逊简单队列服务 (Amazon SQS) Simple Queue Service作为托管队列服务，使用 ElastiCache 亚马逊作为缓存服务，使用AWS Lambda来处理订单和计算风险。

VaR 是一种统计指标，交易者和风险经理使用它来估算其投资组合中超过一定信心水平的潜在损失。大多数 VaR 系统都需要运行大量数学和统计计算并存储结果。这些计算需要大量计算资源，因此 VaR 批处理过程必须分解为较小的计算任务集。可以将大批次拆分为较小的任务，因为这些任务大多是独立的（也就是说，一项任务的计算不依赖于其他任务）。 

VaR 架构的另一重要要求是计算可扩展性。这种模式采用无服务器架构，可根据计算负载自动向内或向外扩展。由于批处理或在线计算需求难以预测，因此需要动态扩展才能在服务水平协议（SLA）规定的时间计划内完成该过程。此外，成本优化架构应该能够在每个计算资源的任务完成后，立即缩减该资源的规模。 

Amazon Web Services 非常适合 VaR 计算，因为它们提供可扩展计算和存储容量、用于以成本优化的方式处理的分析服务，以及用于运行风险管理工作流的不同类型的调度程序。此外，您只需为在 AWS 上使用的计算与存储资源付费。

## 先决条件和限制
<a name="calculate-value-at-risk-var-by-using-aws-services-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 输入文件，具体取决于业务需求。典型的用例涉及以下输入文件：
  + 市场数据文件（输入到 VaR 计算引擎）
  + 交易数据文件（除非交易数据通过数据流传输）。
  + 配置数据文件（模型和其他静态配置数据）
  + 计算引擎模型文件（定量库）
  + 时间序列数据文件（用于历史数据，例如过去五年的股价）
+ 如果市场数据或其他输入通过直播传入，则设置 Amazon Kinesis Data Streams，并将 Amazon Identity and Access Management (IAM) 权限配置为写入该流。 

这种模式构建了一个架构，在此架构中，交易数据从交易系统写入到 Kinesis 数据流。您可以不使用 Storage 服务，而是将您的交易数据存储在小批量文件中，将它们存储在 Amazon Simple Storage Service (Amazon S3) 存储桶中，然后调用事件开始处理数据。

**限制**
+ Kinesis 数据流排序在每个分片都有保证，因此不能保证写入多个分片的交易订单的交付顺序与写入操作的顺序相同。
+ AWS Lambda 的运行时间限制目前为 15 分钟。（有关更多信息，请参阅 [Lambda 常见问题](https://aws.amazon.com/lambda/faqs/)。）

## 架构
<a name="calculate-value-at-risk-var-by-using-aws-services-architecture"></a>

**目标架构**

以下架构图介绍了风险评测系统的 Amazon Web Services 和工作流。

![\[使用 Amazon Web Services 的 VaR 计算系统\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/eb615fc5-3cc3-445a-af2c-8446ee7b5276/images/c60aec03-ff6c-410c-8ee8-f1f6efa22cf7.png)


下图说明了以下内容：

1. 交易从订单管理系统流入。

1. *票据头寸净额结算* Lambda 函数处理订单，并将每个指示器的合并消息写入到 Amazon SQS 中的风险队列中。

1. *风险计算引擎* Lambda 函数处理来自亚马逊 SQS 的消息，执行风险计算，并更新亚马逊风险缓存中的 VaR 损益 (PnL) 信息。 ElastiCache

1. *读取 ElastiCache 数据* Lambda 函数从中检索风险结果并将其存储在数据库 ElastiCache 和 S3 存储桶中。

有关这些服务和步骤的更多信息，请参见*操作说明*部分。

**自动化和扩展**

您可以使用 AWS Cloud Development Kit (AWS CDK) 或 AWS CloudFormation 模板部署整个架构。该架构可以支持批处理和盘中（实时）处理。

架构内置了扩展功能。随着越来越多的交易被写入 Kinesis 数据流并等待处理，可以调用其他 Lambda 函数处理这些交易，然后可以在处理完成后缩小规模。也可以选择通过多个 Amazon SQS 风险计算队列处理。如果需要对队列进行严格的排序或者整合，则无法并行处理。但是，对于 end-of-the-day批次或小型盘中批次，Lambda 函数可以并行处理并将最终结果存储在中。 ElastiCache 

## 工具
<a name="calculate-value-at-risk-var-by-using-aws-services-tools"></a>

**Amazon Web Services**
+ [Amazon Aurora MySQL 兼容版](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.AuroraMySQL.html)是一个完全托管的、与 MySQL 兼容的关系数据库引擎，可帮助您建立、运行和扩展 MySQL 部署。此示例以 MySQL 为例，但您可以使用任何 RDBMS 系统来存储数据。
+ [Amazon ElastiCache](https://docs.aws.amazon.com/elasticache/) 可帮助您在 AWS 云中设置、管理和扩展分布式内存缓存环境。
+ [Amazon Kinesis Data Streams](https://docs.aws.amazon.com/streams/latest/dev/introduction.html) 可帮助您实时收集和处理大型数据记录流。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，而无需预置或管理服务器。它仅在需要时运行您的代码，并且能自动扩缩，因此您只需为使用的计算时间付费。
+ [Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) 提供了一个安全、持久且可用的托管队列，它可帮助您集成和分离分布式软件系统与组件。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**代码**

此模式为 Amazon Web Services Cloud 中的 VaR 系统提供了示例架构，并描述了如何使用 Lambda 函数进行 VaR 计算。要创建您的 Lambda 函数，请参阅 [Lambda 文档](https://docs.aws.amazon.com/lambda/latest/dg/service_code_examples.html)中的代码示例。如果需要帮助，请联系 [AWS Professional Services](https://pages.awscloud.com/AWS-Professional-Services.html)。

## 最佳实践
<a name="calculate-value-at-risk-var-by-using-aws-services-best-practices"></a>
+ 让每个 VaR 计算任务尽可能小巧。在每个计算任务中尝试不同数量交易，看看哪个任务在计算时间和成本方面最为优化。
+ 在 Amazon 中存储可重复使用的对象 ElastiCache。使用 Apache Arrow 等框架来减少序列化和反序列化。
+ 考虑 Lambda 的时间限制。如果您认为自己的计算任务可能会超过 15 分钟，请尝试将其分解为较小的任务，以避免 Lambda 超时。如果无法实现，您可以考虑使用 AWS Fargate、Amazon Elastic Container Service (Amazon ECS) 以及 Amazon Elastic Kubernetes Service (Amazon EKS) 等容器编排解决方案。

## 操作说明
<a name="calculate-value-at-risk-var-by-using-aws-services-epics"></a>

### 交易流向风险系统
<a name="trade-flow-to-risk-system"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 开始写入交易。 | 新建、已结算或部分结算的交易从订单管理系统写入风险流。这种模式使用 Amazon Kinesis 作为托管流媒体服务。交易订单代码哈希值用于在多个分片上放置交易订单。 | Amazon Kinesis | 

### 运行 Lambda 函数进行订单处理
<a name="run-lambda-functions-for-order-processing"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 Lambda 开始执行风险处理。 | 为新订单运行 AWS Lambda 函数。根据待处理交易订单数量，Lambda 将自动扩缩。每个 Lambda 实例都有一个或多个订单，并从亚马逊检索每张股票的最新头寸。 ElastiCache（您可以使用CUSIP ID、Curve名称或其他金融衍生产品的指数名称作为存储和检索数据的密钥 ElasticCache。） 在中 ElastiCache，总持仓（数量）和键值对 < *股票代码*、*净头寸 >（其中净持**仓*是缩放因子）为每个股票更新一次。  | 亚马逊 Kinesis、AWS Lambda、亚马逊 ElastiCache | 

### 将每个指示器消息写入队列
<a name="write-messages-for-each-ticker-into-queue"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将合并的消息写入至风险队列。 | 将消息写入至队列。此模式使用 Amazon SQS 提供托管队列服务。单个 Lambda 实例可能在任何给定时间收到一小批交易订单，但只会为每个指示器写一条消息至 Amazon SQS。计算比例系数：（*旧净头寸* \$1 *当前头寸*）/*旧净头寸*。 | Amazon SQS、AWS Lambda | 

### 调用风险引擎
<a name="invoke-risk-engine"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 开始风险计算。 | 调用风险引擎 lambda 的 Lambda 函数。每个位置都由单个 Lambda 函数处理。但是，出于优化目的，每个 Lambda 函数都可以处理来自 Amazon SQS 的多条消息。 | Amazon SQS、AWS Lambda | 

### 在缓存中检索风险结果
<a name="retrieve-risk-results-from-cache"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 检索与更新风险缓存。 | Lambda 从中检索每个股票的当前净头寸。 ElastiCache它还会从中检索每个股票的VaR损益 (PnL) 数组。 ElastiCache 如果 pNL 数组已经存在，则 Lambda 函数会使用扩展更新数组和 VaR，该扩展来自净额结算 Lambda 函数所编写的 Amazon SQS 消息。如果盈亏数组不存在 ElasticCache，则使用模拟股票价格序列数据计算出新的盈亏和VaR。 | 亚马逊 SQS、AWS Lambda、亚马逊 ElastiCache | 

### 更新 Elastic Cache 中的数据，并存储在数据库中
<a name="update-data-in-elastic-cache-and-store-in-database"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 存储风险结果。 | 更新 VaR 和 PnL 数字后 ElastiCache，每五分钟调用一次新的 Lambda 函数。此函数读取所有存储的数据，并将其存储在兼容 Aurora MySQL 的数据库和 S3 存储桶中。 ElastiCache  | AWS Lambda、亚马逊 ElastiCache | 

## 相关资源
<a name="calculate-value-at-risk-var-by-using-aws-services-resources"></a>
+ [Basel VaR Framework](https://www.bis.org/basel_framework/chapter/DIS/50.htm)

# 使用 Amazon Athena 来配置对共享 AWS Glue Data Catalog 的跨账户存取
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena"></a>

*Denis Avdonin，Amazon Web Services*

## Summary
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-summary"></a>

此模式提供了使用AWS Glue数据目录配置存储在亚马逊简单存储服务 (Amazon S3) 存储桶中的数据集的跨账户共享的 step-by-step说明，包括AWS Identity and Access Management (IAM) 策略示例。您可将数据集存储在 S3 存储桶中。元数据由 AWS Glue 爬网程序收集并放入 AWS Glue Data Catalog 中。S3 存储桶和 AWS Glue Data Catalog 位于称为*数据账户*的 Amazon Web Services account 中。您可向另一个 Amazon Web Services account（称为*使用者账户*）中的 IAM 主体提供访问权限。用户可以使用 Amazon Athena 无服务器查询引擎查询使用者账户中的数据。

## 先决条件和限制
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-prereqs"></a>

**先决条件**
+ 两个活动 [Amazon Web Services account ](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html)
+ 一个 Amazon Web Services account 中的 [S3 存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)
+ [Athena 引擎版本 2](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference.html#engine-versions-reference-0002)
+ 已安装[并](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)配置 AWS 命令行接口 (AWS CLI) Line [In](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) terface（或者用于运行 [AW CloudShell](https://aws.amazon.com/cloudshell/) S CLI 命令的 AWS）

**产品版本**

此模式仅适用于 [Athena 引擎版本 2](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference-0002.html) 和 [Athena 引擎版本 3](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference-0003.html)。我们建议您升级到 Athena 引擎版本 3。如果您无法从 Athena 引擎版本 1 升级到 Athena 引擎版本 3，请按照 AWS 大数据博客中的[使用 Amazon Athena 跨账户访问 AWS Glue Data Catalog](https://aws.amazon.com/blogs/big-data/cross-account-aws-glue-data-catalog-access-with-amazon-athena/) 中讨论的方法进行操作。

## 架构
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-architecture"></a>

**目标技术堆栈**
+ Amazon Athena
+ Amazon Simple Storage Service（Amazon S3）
+ AWS Glue
+ AWS Identity and Access Management (IAM)
+ AWS Key Management Service (AWS KMS)

下图显示了一种架构，该架构使用 IAM 权限通过 AWS Glue Data Catalog 与另一个 Amazon Web Services account（使用者账户）共享一个 Amazon Web Services account（数据账户）中 S3 存储桶中的数据。

![\[使用 AWS Glue Data Catalog 在数据账户和使用者账户之间共享 S3 存储桶中的数据集。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/4ee1d6f5-f8e1-4acb-8a9c-7601c832a87d/images/e73a2b47-c0b1-49f1-be66-9c563c11c9f9.png)


下图显示了如下工作流：

1. 数据账户中的 S3 存储桶策略向使用者账户中的 IAM 角色以及数据账户中的 AWS Glue 爬网程序服务角色授予权限。

1. 数据账户中的 AWS KMS 密钥政策向使用者账户中的 IAM 角色以及数据账户中的 AWS Glue 爬网程序服务角色授予权限。

1. 数据账户中的 AWS Glue 爬网程序会发现存储在 S3 存储桶中的数据的架构。

1. 数据账户中 AWS Glue Data Catalog 的资源策略授予对使用者账户中 IAM 角色的访问权限。

1. 用户通过 AWS CLI 命令在使用者账户中创建命名目录引用。

1. IAM policy 授予使用者账户中的 IAM 角色对数据账户中资源的访问权限。IAM 角色的信任策略允许用户在使用者账户中代入 IAM 角色。

1. 使用者账户中的用户承担 IAM 角色并使用 SQL 查询访问数据目录中的对象。

1.  Athena 无服务器引擎运行 SQL 查询。

**注意**  
[IAM 最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)建议您向 IAM 角色授予权限并使用[身份联合验证](https://aws.amazon.com/identity/federation/)。

## 工具
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-tools"></a>
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一种交互式查询服务，它可帮助您通过使用标准 SQL 直接在 Amazon S3 中分析数据。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一项完全托管的提取、转换、加载（ETL）服务。它可以帮助您在数据存储和数据流之间对数据进行可靠地分类、清理、扩充和移动。
+ [AWS Identity and Access Management (AWS IAM) ](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)通过控制验证和授权使用您 AWS 资源的用户，帮助您安全地管理对您 AWS 资源的访问。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可帮助您创建和控制加密密钥以保护您的数据。

## 操作说明
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-epics"></a>

### 设置数据账户权限
<a name="set-up-permissions-in-the-data-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 授予对 S3 存储桶中数据的访问权限。 | 根据以下模板[创建 S3 存储桶策略](https://docs.aws.amazon.com/AmazonS3/latest/userguide/add-bucket-policy.html)，并将该策略分配给存储数据的存储桶。<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Effect": "Allow",<br />            "Principal": {<br />                "AWS": [<br />                     "arn:aws:iam::<consumer account id>:role/<role name>",<br />                     "arn:aws:iam::<data account id>:role/service-role/AWSGlueServiceRole-data-bucket-crawler"<br />                ]<br />            },<br />            "Action": "s3:GetObject",<br />            "Resource": "arn:aws:s3:::data-bucket/*"<br />        },<br />        {<br />            "Effect": "Allow",<br />            "Principal": {<br />                "AWS": [<br />                      "arn:aws:iam::<consumer account id>:role/<role name>",<br />                      "arn:aws:iam::<data account id>:role/service-role/AWSGlueServiceRole-data-bucket-crawler"<br />                ]<br />            },<br />            "Action": "s3:ListBucket",<br />            "Resource": "arn:aws:s3:::data-bucket"<br />        }<br />    ]<br />}</pre>存储桶策略向使用者账户中的 IAM 角色和数据账户中的 AWS Glue 爬网程序服务角色授予权限。 | 云管理员 | 
| (如果需要)授予对数据加密密钥的访问权限。 | 如果 S3 存储桶由 AWS KMS 密钥加密，请向使用者账户中的 IAM 角色和数据账户中的 AWS Glue 爬网程序服务角色授予密钥 `kms:Decrypt` 权限。使用以下语句更新[密钥政策](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html)：<pre>{<br />    "Effect": "Allow",<br />    "Principal": {<br />        "AWS": [<br />            "arn:aws:iam::<consumer account id>:role/<role name>",<br />            "arn:aws:iam::<data account id>:role/service-role/AWSGlueServiceRole-data-bucket-crawler"<br />        ]<br />    },<br />    "Action": "kms:Decrypt",<br />    "Resource": "arn:aws:kms:<region>:<data account id>:key/<key id>"<br />}</pre> | 云管理员 | 
| 授予爬网程序对数据的访问权限。 | 将以下 IAM policy 附加到爬网程序的服务角色：<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Effect": "Allow",<br />            "Action": "s3:GetObject",<br />            "Resource": "arn:aws:s3:::data-bucket/*"<br />        },<br />        {<br />            "Effect": "Allow",<br />            "Action": "s3:ListBucket",<br />            "Resource": "arn:aws:s3:::data-bucket"<br />        }<br />    ]<br />} </pre> | 云管理员 | 
| （如果需要）授予爬网程序访问数据加密密钥的权限。 | 如果 S3 存储桶由 AWS KMS 密钥加密，则通过向爬网程序的服务角色附加以下策略，向其授予密钥 `kms:Decrypt` 权限：<pre>{<br />    "Effect": "Allow",<br />    "Action": "kms:Decrypt",<br />    "Resource": "arn:aws:kms:<region>:<data account id>:key/<key id>"<br />}</pre> | 云管理员 | 
| 向使用者账户中的 IAM 角色和爬网程序授予对数据目录的访问权限。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena.html)<pre>{<br />    "Version" : "2012-10-17",<br />    "Statement" : [ <br />        {<br />            "Effect" : "Allow",<br />            "Principal" : {<br />                "AWS" : [<br />                     "arn:aws:iam::<consumer account id>:role/<role name>",<br />                    "arn:aws:iam::<data account id>:role/service-role/AWSGlueServiceRole-data-bucket-crawler"<br />                ]<br />            },<br />            "Action" : "glue:*",<br />            "Resource" : [ <br />                 "arn:aws:glue:<region>:<data account id>:catalog", <br />                 "arn:aws:glue:<region>:<data account id>:database/*", <br />                 "arn:aws:glue:<region>:<data account id>:table/*" <br />            ]<br />        } <br />    ]<br />}</pre>此策略允许对数据账户中的所有数据库和表执行所有 AWS Glue 操作。您可对策略进行自定义，使其仅向使用者主体授予所需权限。例如，您可提供对数据库中特定表或视图的只读访问权限。 | 云管理员 | 

### 通过使用者账户访问数据
<a name="access-data-from-the-consumer-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 数据目录命名引用。 | 要创建命名的数据目录引用，请使用[CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/getting-started.html)或本地安装的 AWS CLI 运行以下命令：<pre>aws athena create-data-catalog --name <shared catalog name> --type GLUE --parameters catalog-id=<data account id></pre> | 云管理员 | 
| 授予使用者账户中的 IAM 角色对数据的访问权限。 | 将以下策略附加到使用者账户中的 IAM 角色，以授予该角色跨账户存取数据的权限：<pre>{<br />     "Version": "2012-10-17",		 	 	 <br />     "Statement": [<br />        {<br />             "Effect": "Allow",<br />             "Action": "s3:GetObject",<br />             "Resource": "arn:aws:s3:::data-bucket/*"<br />        },<br />        {<br />             "Effect": "Allow",<br />             "Action": "s3:ListBucket",<br />             "Resource": "arn:aws:s3:::data-bucket"<br />        },<br />        {<br />            "Effect": "Allow",<br />            "Action": "glue:*",<br />            "Resource": [<br />                 "arn:aws:glue:<region>:<data account id>:catalog",<br />                 "arn:aws:glue:<region>:<data account id>:database/*",<br />                 "arn:aws:glue:<region>:<data account id>:table/*"<br />            ]<br />        }<br />    ]<br />}</pre>接下来，使用以下模板指定哪些用户可以按其信任策略接受 IAM 角色：<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />       {<br />            "Effect": "Allow",<br />            "Principal": {<br />                "AWS": "arn:aws:iam::<consumer account id>:user/<IAM user>"<br />            },<br />            "Action": "sts:AssumeRole"<br />        }<br />    ]<br />}</pre>最后，通过将相同的策略附加到用户组所属的用户组，授予其代入 IAM 角色的权限。 | 云管理员 | 
| （如果需要）授予使用者账户中的 IAM 角色访问数据加密密钥的权限。 | 如果 S3 存储桶由 AWS KMS 密钥加密，请向使用者账户中的 IAM 角色授予密钥 `kms:Decrypt` 权限，方法是向该角色附加以下策略：<pre>{<br />     "Effect": "Allow",<br />     "Action": "kms:Decrypt",<br />     "Resource": "arn:aws:kms:<region>:<data account id>:key/<key id>"<br />}</pre> | 云管理员 | 
| 切换到使用者账户中的 IAM 角色以访问数据。 | 作为数据使用者，[切换至 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html)以访问数据账户中的数据。 | 数据使用者 | 
| 访问数据。 | 使用 Athena 查询数据。例如，打开 Athena 查询编辑器，并运行以下查询：<pre>SELECT *<br />  FROM <shared catalog name>.<database name>.<table name></pre>您还可以使用 Amazon 资源名称（ARN）引用该目录，而不必使用命名目录引用。如您在查询或视图中使用动态目录引用，请使用转义双引号（\$1"）。例如：<pre>SELECT * <br />  FROM \"glue:arn:aws:glue:<region>:<data account id>:catalog\".<database name>.<table name></pre>有关更多信息，请参阅 Amazon Athena 用户指南中的[跨账户存取 AWS Glue Data Catalog](https://docs.aws.amazon.com/athena/latest/ug/security-iam-cross-account-glue-catalog-access.html)。 | 数据使用者 | 

## 相关资源
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-resources"></a>
+ [跨账户存取 AWS Glue Data Catalog](https://docs.aws.amazon.com/athena/latest/ug/security-iam-cross-account-glue-catalog-access.html)（Athena 文档）
+ [(AWS CLI) create-data-catalog](https://docs.aws.amazon.com/cli/latest/reference/athena/create-data-catalog.html)（AWS CLI 命令参考）
+ [使用 Amazon Athena 跨账户存取 AWS Glue Data Catalog](https://aws.amazon.com/blogs/big-data/cross-account-aws-glue-data-catalog-access-with-amazon-athena/)（AWS 大数据博客）
+ [IAM 中的安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)（IAM 文档）

## 附加信息
<a name="configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena-additional"></a>

**使用 Lake Formation 作为共享跨账户替代方案**

您还可使用 AWS Lake Formation 在账户之间共享对 AWS Glue 目录对象的访问权限。Lake Formation 提供列和行级别的精细访问控制、基于标签的访问控制、ACID 事务的受控表以及其他功能。尽管 Lake Formation 与 Athena 集成良好，但与此模式的仅 IAM 方法相比，它确实需要额外的配置。我们建议您在整体解决方案架构的更广泛背景下考虑决定使用 Lake Formation 或仅 IAM 访问控制。需要考虑的因素包括涉及哪些其他服务以及它们如何与这两种方法集成。

# 将 Teradata 标准化时态功能转换为 Amazon Redshift SQL
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql"></a>

*Po Hong，Amazon Web Services*

## Summary
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-summary"></a>

**NORMALIZE** 是 ANSI SQL 标准的 Teradata 扩展。当 SQL 表包含具有 **PERIOD** 数据类型的列时，**NORMALIZE** 会组合该列中相交或重叠的值，形成一个整合多个单独周期值的单个周期。要使用 **NORMALIZE**，SQL **SELECT** 列表中至少有一列必须是 Teradata 的时态**周期**数据类型。有关 **NORMALIZE** 的更多信息，请参阅 [Teradata 文档](https://docs.teradata.com/reader/2_MC9vCtAJRlKle2Rpb0mA/MIGI5UMEwgERC3Un7tEZ6g)。 

Amazon Redshift 不支持 **NORMALIZE**，但您可以使用原生 SQL 语法和 Amazon Redshift 中的 **LAG** 窗口函数来实现此功能。这种模式侧重于使用带有 **ON MEETS OR OVERLAPS** 条件的 Teradata **NORMALIZE** 扩展，这是最流行的格式。它解释了该功能在 Teradata 中的工作原理，以及如何将其转换为 Amazon Redshift 原生 SQL 语法。

## 先决条件和限制
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-prereqs"></a>

**先决条件**
+ 基本 Teradata SQL 知识和经验
+ Amazon Redshift 知识和经验

## 架构
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-architecture"></a>

**源技术堆栈**
+ Teradata 数据仓库

**目标技术堆栈**
+ Amazon Redshift

**目标架构**

有关将 Teradata 数据库迁移至 Amazon Redshift 的高级架构，请参阅使用 AWS SCT 数据提取代理[将 Teradata 数据库迁移至 Amazon Redshift](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/migrate-a-teradata-database-to-amazon-redshift-using-aws-sct-data-extraction-agents.html) 模式。迁移不会自动将 Teradata **NORMALIZE** 短语转换为Amazon Redshift SQL。您可按照此模式中的指导方针转换此 Teradata 扩展。

## 工具
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-tools"></a>

**代码**

为了说明 **NORMALIZE** 的概念和功能，请考虑 Teradata 中的下表定义：

```
CREATE TABLE systest.project
     (    emp_id        INTEGER,
          project_name  VARCHAR(20),
          dept_id       INTEGER,
          duration      PERIOD(DATE)
     );
```

运行以下 SQL 代码，以将示例数据插入表中：

```
BEGIN TRANSACTION;

INSERT INTO systest.project VALUES (10, 'First Phase', 1000,  PERIOD(DATE '2010-01-10', DATE '2010-03-20') );
INSERT INTO systest.project VALUES (10, 'First Phase', 2000,  PERIOD(DATE '2010-03-20', DATE '2010-07-15') );

INSERT INTO systest.project VALUES (10, 'Second Phase', 2000,  PERIOD(DATE '2010-06-15', DATE '2010-08-18') );
INSERT INTO systest.project VALUES (20, 'First Phase', 2000,  PERIOD(DATE '2010-03-10', DATE '2010-07-20') );

INSERT INTO systest.project VALUES (20, 'Second Phase', 1000,  PERIOD(DATE '2020-05-10', DATE '2020-09-20') );

END TRANSACTION;
```

结果：

```
select * from systest.project order by 1,2,3;
 
 *** Query completed. 4 rows found. 4 columns returned.
 *** Total elapsed time was 1 second.
 
     emp_id  project_name              dept_id  duration
-----------  --------------------  -----------  ------------------------
         10  First Phase                  1000  ('10/01/10', '10/03/20')        
         10  First Phase                  2000  ('10/03/20', '10/07/15')
         10  Second Phase                 2000  ('10/06/15', '10/08/18')
         20  First Phase                  2000  ('10/03/10', '10/07/20')
         20  Second Phase                 1000  ('20/05/10', '20/09/20')
```

*Teradata NORMALIZE 用例*

现在将 Teradata **NORMALIZE** SQL 子句添加至 **SELECT** 语句：

```
SELECT NORMALIZE ON MEETS OR OVERLAPS emp_id, duration 
FROM systest.project 
ORDER BY 1,2;
```

这个 “**归一化**” 操作是在单列 (`emp_id`) 上执行的。对于`emp_id=10`，持续时间中的三个重叠周期值合并为一个周期值，如下所示： 

```
     emp_id  duration
-----------  ------------------------
         10  ('10/01/10', '10/08/18')
         20  ('10/03/10', '10/07/20')
         20  ('20/05/10', '20/09/20')
```

以下 SE **LE** CT 语句对`project_name`和`dept_id`执行**标准化**操作。请注意，SE **LECT** 列表仅包含一个 “**周期**” 列`duration`。

```
SELECT NORMALIZE project_name, dept_id, duration 
FROM systest.project;
```

输出：

```
project_name              dept_id  duration
--------------------  -----------  ------------------------
First Phase                  1000  ('10/01/10', '10/03/20')
Second Phase                 1000  ('20/05/10', '20/09/20')
First Phase                  2000  ('10/03/10', '10/07/20')
Second Phase                 2000  ('10/06/15', '10/08/18')
```

*Amazon Redshift 等效 SQL*

Amazon Redshift 目前不支持表中的 **PERIOD** 数据类型。相反，您需要将 Teradata PERIO **D** 数据字段分为两部分：`start_date, end_date`，如下所示： 

```
CREATE TABLE systest.project
     (    emp_id        INTEGER,
          project_name  VARCHAR(20),
          dept_id       INTEGER,
          start_date  DATE,
          end_date    DATE
     );
```

在表中插入示例数据：

```
BEGIN TRANSACTION;
 
INSERT INTO systest.project VALUES (10, 'First Phase', 1000,  DATE '2010-01-10', DATE '2010-03-20' );
INSERT INTO systest.project VALUES (10, 'First Phase', 2000,  DATE '2010-03-20', DATE '2010-07-15');
 
INSERT INTO systest.project VALUES (10, 'Second Phase', 2000,  DATE '2010-06-15', DATE '2010-08-18' );
INSERT INTO systest.project VALUES (20, 'First Phase', 2000,  DATE '2010-03-10', DATE '2010-07-20' );
 
INSERT INTO systest.project VALUES (20, 'Second Phase', 1000,  DATE '2020-05-10', DATE '2020-09-20' );
 
END TRANSACTION;
```

输出：

```
 emp_id | project_name | dept_id | start_date |  end_date
--------+--------------+---------+------------+------------
     10 | First Phase  |    1000 | 2010-01-10 | 2010-03-20
     10 | First Phase  |    2000 | 2010-03-20 | 2010-07-15
     10 | Second Phase |    2000 | 2010-06-15 | 2010-08-18
     20 | First Phase  |    2000 | 2010-03-10 | 2010-07-20
     20 | Second Phase |    1000 | 2020-05-10 | 2020-09-20
(5 rows)
```

要重写 Teradata 的 **NORMALIZE** 子句，您可以使用 Amazon Redshift 中的 [LAG 窗口函数](https://docs.aws.amazon.com/redshift/latest/dg/r_WF_LAG.html)。此函数返回位于分区中当前行的上方（之前）的某个给定偏移量位置的行的值。

您可使用 **LAG** 函数通过确定一个时段是否与前一时段相交或重叠来识别开始新时段的每一行（如果是，则为 0，如果不是，则为 1）。累积汇总此标志后，它会提供组标识符，该标识符可用于外部 **Group By** 子句中，从而在 Amazon Redshift 中得出所需结果。 

以下是使用 **LAG()** 的 Amazon Redshift SQL 语句示例：

```
SELECT emp_id, start_date, end_date, 
            (CASE WHEN start_date <= LAG(end_date) OVER (PARTITION BY emp_id ORDER BY start_date, end_date) THEN 0 ELSE 1 END) AS GroupStartFlag
FROM systest.project 
ORDER BY 1,2;
```

输出：

```
 emp_id | start_date |  end_date  | groupstartflag
--------+------------+------------+----------------
     10 | 2010-01-10 | 2010-03-20 |              1
     10 | 2010-03-20 | 2010-07-15 |              0
     10 | 2010-06-15 | 2010-08-18 |              0
     20 | 2010-03-10 | 2010-07-20 |              1
     20 | 2020-05-10 | 2020-09-20 |              1
(5 rows)
```

以下 Amazon Redshift SQL 语句仅对列进行标准化处理：`emp_id`

```
SELECT T2.emp_id, MIN(T2.start_date) as new_start_date, MAX(T2.end_date) as new_end_date
FROM 
( SELECT T1.*, SUM(GroupStartFlag) OVER (PARTITION BY emp_id ORDER BY start_date ROWS UNBOUNDED PRECEDING) As GroupID
FROM ( SELECT emp_id, start_date, end_date, 
            (CASE WHEN start_date <= LAG(end_date) OVER (PARTITION BY emp_id ORDER BY start_date, end_date) THEN 0 ELSE 1 END) AS GroupStartFlag
FROM systest.project ) T1
) T2
GROUP BY T2.emp_id, T2.GroupID
ORDER BY 1,2;
```

输出： 

```
 emp_id | new_start_date | new_end_date
--------+----------------+------------------------------------
     10 | 2010-01-10     | 2010-08-18
     20 | 2010-03-10     | 2010-07-20
     20 | 2020-05-10     | 2020-09-20
(3 rows)
```

** **

以下 Amazon Redshift SQL 语句对和列进行了标准化处理：`project_name``dept_id`

```
SELECT T2.project_name, T2.dept_id, MIN(T2.start_date) as new_start_date, MAX(T2.end_date) as new_end_date
FROM 
( SELECT T1.*, SUM(GroupStartFlag) OVER (PARTITION BY project_name, dept_id ORDER BY start_date ROWS UNBOUNDED PRECEDING) As GroupID
FROM ( SELECT project_name, dept_id, start_date, end_date, 
            (CASE WHEN start_date <= LAG(end_date) OVER (PARTITION BY project_name, dept_id ORDER BY start_date, end_date) THEN 0 ELSE 1 END) AS GroupStartFlag
FROM systest.project ) T1
) T2
GROUP BY T2.project_name, T2.dept_id, T2.GroupID
ORDER BY 1,2,3;
```

输出：

```
 project_name | dept_id | new_start_date | new_end_date
--------------+---------+----------------+--------------
 First Phase  |    1000 | 2010-01-10     | 2010-03-20
 First Phase  |    2000 | 2010-03-10     | 2010-07-20
 Second Phase |    1000 | 2020-05-10     | 2020-09-20
 Second Phase |    2000 | 2010-06-15     | 2010-08-18
(4 rows)
```

## 操作说明
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-epics"></a>

### 将 NORMALIZE 转换为 Amazon Redshift SQL
<a name="convert-normalize-to-amazon-redshift-sql"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建您的 Teradata SQL 代码。 | 根据自身需求使用 NORMALIZE 短语。 | SQL Developer | 
| 将代码转换为 Amazon Redshift SQL。 | 若要转换您的代码，请按照此模式的“工具”部分中的指南进行操作。 | SQL Developer | 
| 在 Amazon Redshift 中运行代码。 | 创建您的表，将数据加载至表中，然后在 Amazon Redshift 中运行您的代码。 | SQL Developer | 

## 相关资源
<a name="convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql-resources"></a>

**参考**
+ [Teradata NORMALIZE 时态功能](https://docs.teradata.com/reader/2_MC9vCtAJRlKle2Rpb0mA/MIGI5UMEwgERC3Un7tEZ6g)（Teradata 文档）
+ [LAG 窗口函数](https://docs.aws.amazon.com/redshift/latest/dg/r_WF_LAG.html)（Amazon Redshift 文档）
+ [迁移至 Amazon Redshift](https://aws.amazon.com/redshift/data-warehouse-migration/)（AWS 网站）
+ [使用 AWS SCT 数据提取代理，将 Teradata 数据库迁移至 Amazon Redshift](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/migrate-a-teradata-database-to-amazon-redshift-using-aws-sct-data-extraction-agents.html) (AWS Prescriptive Guidance)
+ [将 Teradata RESET WHEN 功能转换为 Amazon Redshift SQL](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/convert-the-teradata-reset-when-feature-to-amazon-redshift-sql.html) (AWS Prescriptive Guidance)

**工具**
+ [AWS Schema Conversion Tool (AWS SCT)](https://aws.amazon.com/dms/schema-conversion-tool/)

**合作伙伴**
+ [AWS Migration Competency Partners](https://aws.amazon.com/migration/partner-solutions/#delivery)

# 将 Teradata RESET WHEN 功能转换为 Amazon Redshift SQL
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql"></a>

*Po Hong，Amazon Web Services*

## Summary
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-summary"></a>

**RESET WHEN**是 SQL 分析窗口函数中使用的 Teradata 功能。它是 ANSI SQL 标准的扩展。**RESET WHEN** 根据某些指定条件确定 SQL 窗口函数在其上运行的分区。如果条件计算结果为 **TRUE**，则会在现有窗口分区内创建新的动态子分区。有关 **RESET WHEN** 的更多信息，请参阅 [Teradata 文档](https://docs.teradata.com/reader/1DcoER_KpnGTfgPinRAFUw/b7wL86OoMTPno6hrSPNdDg)。

Amazon Redshift 不支持 SQL 窗口函数中的 **RESET WHEN**。若要实现此功能，您必须将 **RESET WHEN** 转换为 Amazon Redshift 中的原生 SQL 语法，并使用多个嵌套函数。此模式演示了如何使用 Teradata **RESET WHEN** 功能以及如何将其转换为 Amazon Redshift SQL 语法。 

## 先决条件和限制
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-prereqs"></a>

**先决条件**
+ Teradata 数据仓库及其 SQL 语法的基础知识
+ 对 Amazon Redshift 及其 SQL 语法有很好的了解

## 架构
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-architecture"></a>

**源技术堆栈**
+ Teradata 数据仓库

**目标技术堆栈**
+ Amazon Redshift

**架构**

有关将 Teradata 数据库迁移至 Amazon Redshift 的高级架构，请参阅使用 AWS SCT 数据提取代理[将 Teradata 数据库迁移至 Amazon Redshift](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/migrate-a-teradata-database-to-amazon-redshift-using-aws-sct-data-extraction-agents.html)模式。迁移不会自动将 Teradata **NORMALIZE** 短语转换为 Amazon Redshift SQL。您可以按照下一节中的指导原则转换此 Teradata 扩展。

## 工具
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-tools"></a>

**代码**

为了说明 **RESET WHEN** 的概念，请考虑 Teradata 中的下表定义：

```
create table systest.f_account_balance                                
( account_id integer NOT NULL,
  month_id integer,
  balance integer )
unique primary index (account_id, month_id);
```

运行以下 SQL 代码，以将示例数据插入表中：

```
BEGIN TRANSACTION;
Insert Into systest.f_account_balance values (1,1,60);
Insert Into systest.f_account_balance values (1,2,99);
Insert Into systest.f_account_balance values (1,3,94);
Insert Into systest.f_account_balance values (1,4,90);
Insert Into systest.f_account_balance values (1,5,80);
Insert Into systest.f_account_balance values (1,6,88);
Insert Into systest.f_account_balance values (1,7,90);
Insert Into systest.f_account_balance values (1,8,92);
Insert Into systest.f_account_balance values (1,9,10);
Insert Into systest.f_account_balance values (1,10,60);
Insert Into systest.f_account_balance values (1,11,80);
Insert Into systest.f_account_balance values (1,12,10);
END TRANSACTION;
```

该示例表具有以下数据：


| 
| 
| account\$1id | month\$1id | balance | 
| --- |--- |--- |
| 1 | 1 | 60 | 
| 1 | 2 | 99 | 
| 1 | 3 | 94 | 
| 1 | 4 | 90 | 
| 1 | 5 | 80 | 
| 1 | 6 | 88 | 
| 1 | 7 | 90 | 
| 1 | 8 | 92 | 
| 1 | 9 | 10 | 
| 1 | 10 | 60 | 
| 1 | 11 | 80 | 
| 1 | 12 | 10 | 

对于每个账户，假设您想要分析每月余额连续增加的顺序。当一个月的余额小于或等于上个月的余额时，要求将计数器重置为零，并重新启动。

*Teradata RESET WHEN 用例*

若要分析此数据，Teradata SQL 使用了带有嵌套聚合和 **RESET WHEN** 短语的窗口函数，如下所示：

```
SELECT account_id, month_id, balance,
 ( ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY month_id
RESET WHEN balance <= SUM(balance) over (PARTITION BY account_id ORDER BY month_id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) ) -1 ) as balance_increase
FROM systest.f_account_balance
ORDER BY 1,2;
```

输出：


| 
| 
|  account\$1id | month\$1id | balance | balance\$1increase | 
| --- |--- |--- |--- |
| 1 | 1 | 60 | 0 | 
| 1 | 2 | 99 | 1 | 
| 1 | 3 | 94 | 0 | 
| 1 | 4 | 90 | 0 | 
| 1 | 5 | 80 | 0 | 
| 1 | 6 | 88 | 1 | 
| 1 | 7 | 90 | 2 | 
| 1 | 8 | 92 | 3 | 
| 1 | 9 | 10 | 0 | 
| 1 | 10 | 60 | 1 | 
| 1 | 11 | 80 | 2 | 
| 1 | 12 | 10 | 0 | 

在 Teradata 中，查询处理方式如下：

1. **SUM（余额）**汇总函数计算给定账户在给定月份内所有余额的总和。

1. 我们会检查给定月份（给定账户）的余额是否大于上个月的余额。

1. 如果余额增加，我们将跟踪累积计数值。如果 **RESET WHEN** 条件的计算结果为 **false**，这意味着余额在连续几个月中有所增加，则我们会继续增加计数。

1. **ROW\$1NUMBER ()** 有序分析函数计算计数值。当我们一个月的余额小于或等于前一个月的余额时，**RESET WHEN** 条件的计算结果为 **true**。如果是这样，我们启动一个新分区，**ROW\$1NUMBER()** 从 1 重新开始计数。我们使用 **ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING** 来访问前一行的值。

1. 我们减去 1，以确保计数值以 0 开头。

*Amazon Redshift 等效 SQL*

Amazon Redshift 不支持 SQL 分析窗口函数中的 **RESET WHEN** 短语。 若要生成相同的结果，您必须使用 Amazon Redshift 原生 SQL 语法和嵌套子查询重写 Teradata SQL，如下所示： 

```
SELECT account_id, month_id, balance,
   (ROW_NUMBER() OVER(PARTITION BY account_id, new_dynamic_part ORDER BY month_id) -1) as balance_increase
FROM
( SELECT account_id, month_id, balance, prev_balance,
SUM(dynamic_part) OVER (PARTITION BY account_id ORDER BY month_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) As new_dynamic_part
FROM ( SELECT account_id, month_id, balance,
SUM(balance) over (PARTITION BY account_id ORDER BY month_id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) as prev_balance,
(CASE When balance <= prev_balance Then 1 Else 0 END) as dynamic_part
FROM systest.f_account_balance ) A
) B
ORDER BY 1,2;
```

由于 Amazon Redshift 不支持单个 SQL 语句的 **SELECT** 子句中的嵌套窗口函数，因此您必须使用两个嵌套的子查询。
+ 在内部子查询(别名 A)中，创建并填充动态分区指示器 (**dynamic\$1part**)。如果一个月的余额小于或等于前一个月的余额，则 **dynamic\$1part** 设置为 1；否则，设置为 0。 
+ 在下一层(别名 B)中，将生成 **new\$1dynamic\$1part** 属性作为 **SUM** 窗口函数的结果。 
+ 最后，将 **new\$1dynamic\$1part** 作为新的分区属性（**dynamic partition**）添加到现有分区属性（**account\$1id**）中，并应用与 Teradata 中相同的 **ROW\$1NUMBER() **窗口函数（减一）。 

进行上述更改后，Amazon Redshift SQL 生成的输出与 Teradata 相同。

## 操作说明
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-epics"></a>

### 将 RESET WHEN 转换为 Amazon Redshift SQL
<a name="convert-reset-when-to-amazon-redshift-sql"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Teradata 窗口函数。 | 根据需求使用嵌套聚合与 RESET WHEN 短语。 | SQL Developer | 
| 将代码转换为 Amazon Redshift SQL。 | 若要转换您的代码，请按照此模式的“工具”部分中的指南进行操作。 | SQL Developer | 
| 在 Amazon Redshift 中运行代码。 | 创建您的表，将数据加载至表中，然后在 Amazon Redshift 中运行您的代码。 | SQL Developer | 

## 相关资源
<a name="convert-the-teradata-reset-when-feature-to-amazon-redshift-sql-resources"></a>

**参考**
+ [RESET WHEN 短语](https://docs.teradata.com/reader/1DcoER_KpnGTfgPinRAFUw/b7wL86OoMTPno6hrSPNdDg)（Teradata 文档）
+ [RESET WHEN 解释](https://stackoverflow.com/questions/53344536/teradata-reset-when-partition-by-order-by)（堆栈溢出）
+ [迁移至 Amazon Redshift](https://aws.amazon.com/redshift/data-warehouse-migration/)（AWS 网站）
+ [使用 AWS SCT 数据提取代理，将 Teradata 数据库迁移至 Amazon Redshift](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/migrate-a-teradata-database-to-amazon-redshift-using-aws-sct-data-extraction-agents.html) (AWS Prescriptive Guidance)
+ [将 Teradata RESET WHEN 时态功能转换至 Amazon Redshift SQL](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/convert-the-teradata-normalize-temporal-feature-to-amazon-redshift-sql.html) (AWS Prescriptive Guidance)

**工具**
+ [AWS Schema Conversion Tool (AWS SCT)](https://aws.amazon.com/dms/schema-conversion-tool/)

**合作伙伴**
+ [AWS Migration Competency Partners](https://aws.amazon.com/migration/partner-solutions/#delivery)

# 使用基础设施即代码，在 Amazon Web Services Cloud 上部署和管理无服务器数据湖
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code"></a>

*Kirankumar Chandrashekar 和 Abdel Jaidi，Amazon Web Services*

## Summary
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-summary"></a>

此示例介绍了如何使用[无服务器计算](https://aws.amazon.com/serverless/)和[基础设施即代码](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/infrastructure-as-code.html)（IaC）在 Amazon Web Services (AWS) Cloud 上实施和管理数据湖。这种模式基于 AWS 开发的[无服务器数据湖框架 (SDLF)](https://sdlf.workshop.aws/) 研讨会。

SDLF 是一组可重复使用的资源，可加速企业数据湖在 Amazon Web Services Cloud 上的交付，并有助于更快地部署到生产环境。它用于通过遵循最佳实践来实施数据湖的基础结构。

SDLF 使用 AWS、AWS 和 AWS 等 CodePipeline AWS 服务，在整个代码和基础设施部署过程中实施持续集成/持续部署 (CI/CD) 流程。 CodeBuild CodeCommit

此模式使用多个 AWS 无服务器服务来简化数据湖管理。其中包括用于存储的亚马逊简单存储服务 (Amazon S3) 和亚马逊 DynamoDB、用于计算的 AWS Lambda 和 AWS Glue，以及用于编排的亚马逊活动、亚马逊简单队列服务 (Amazon SQS) Simple Queue Service CloudWatch 和 AWS Step Functions。

AWS CloudFormation 和 AWS 代码服务充当 IaC 层，提供可重现且快速的部署，操作和管理简单。

## 先决条件和限制
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。
+ 已安装并配置 [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)。 
+ Git 客户端，已安装和配置。
+ [SDLF 研讨会](https://sdlf.workshop.aws/)，在 Web 浏览器窗口中打开并随时可以使用。 

## 架构
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-architecture"></a>

![\[在 AWS 云上实施和管理数据湖。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/f4fc3ad2-1c4f-45ea-bc86-2db13105a173/images/e0cfff30-f0f8-4fc1-8e84-a152ef615c58.png)


 该架构图通过以下步骤说明了事件驱动的流程。 

1. 将文件添加到原始数据 S3 存储桶后，Amazon S3 事件通知将放置在 SQS 队列中。每个通知均以 JSON 文件形式传递，其中包含 S3 存储桶名称、对象键或时间戳等元数据。

1. 此通知由 Lambda 函数使用，该函数根据元数据将事件路由到正确的提取、转换和加载 (ETL) 流程。Lambda 函数还可以使用存储在 Amazon DynamoDB 表中的上下文配置。此步骤可以解耦并扩展到数据湖中的多个应用程序。

1. 该事件被路由至 ETL 流程中的第一个 Lambda 函数，该函数将数据从原始数据区域转换并移动到数据湖的暂存区域。第一步是更新综合目录。这是 DynamoDB 表，其中包含数据湖的所有文件元数据。此表中的每一行都包含关于存储在 Amazon S3 中的单个对象的操作元数据。同步调用 Lambda 函数，该函数对 S3 对象执行轻量变换，这是一种计算成本低廉的操作（例如将文件从一种格式转换为另一种格式）。由于新对象已添加到暂存 S3 存储桶中，因此综合目录会更新，并且消息会发送到 SQS 队列，等待 ETL 中的下一阶段。

1.  CloudWatch 事件规则每 5 分钟触发一个 Lambda 函数。此函数检查消息是否从上一个 ETL 阶段传送至 SQS 队列。如果消息已传送，则 Lambda 函数将在 ETL 流程中启动 [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/sample-start-workflow.html) 中的第二个函数。

1. 然后对批量文件进行大量转换。这种繁重的转换是一项计算成本很高的操作，例如同步调用 AWS Glue 作业、AWS Fargate 任务、亚马逊 EMR 步骤或亚马逊笔记本。 SageMaker 使用 AWS Glue 爬网程序从输出文件中提取表元数据，这会更新 AWS Glue 目录。文件元数据也将添加至 DynamoDB 的综合目录表中。最后，还利用 [Deequ](https://github.com/awslabs/deequ) 运行数据质量步骤。

**技术堆栈**
+ 亚马逊 CloudWatch 活动
+ AWS CloudFormation
+ AWS CodePipeline
+ AWS CodeBuild
+ AWS CodeCommit
+ Amazon DynamoDB
+ AWS Glue
+ AWS Lambda
+ Amazon S3
+ Amazon SQS
+ AWS Step Functions

## 工具
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-tools"></a>
+ [Amazon CloudWatch ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) Ev CloudWatch ents — Events 提供近乎实时的系统事件流，这些事件描述了 AWS 资源的变化。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) — CloudFormation 帮助以可预测的方式重复创建和配置 AWS 基础设施部署。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) — CodeBuild 是一项完全托管的构建服务，可编译您的源代码、运行单元测试并生成可供部署的项目。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) — CodeCommit 是一项由 AWS 托管的版本控制服务，您可以使用它来私下存储和管理资产（例如源代码和二进制文件）。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) — CodePipeline 是一项持续交付服务，您可以使用它对持续发布软件变更所需的步骤进行建模、可视化和自动化。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) – DynamoDB 是一种全托管 NoSQL 数据库服务，提供快速而可预测的性能，能够实现扩展。 
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) – AWS Glue 是一项完全托管的 ETL 服务，可让客户轻松准备和加载数据以进行分析。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) – Lambda 支持无需预调配或管理服务器即可运行代码。只有在需要时 Lambda 才运行您的代码，并且能自动扩缩，从每天几个请求扩展到每秒数千个请求。 
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/gsg/GetStartedWithS3.html) – Amazon Simple Storage Service (Amazon S3) 是一种高度可扩展的对象存储服务。Amazon S3 可用于各种存储解决方案，包括网站、移动应用程序、备份和数据湖。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) - AWS Step Functions 是一款无服务器函数编排工具，它可以轻松地将 AWS Lambda 函数和多个 Amazon Web Services 排序到关键业务应用程序中。
+ [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) – Amazon Simple Queue Service (Amazon SQS) 是一种全托管消息队列服务，可帮助您解耦和扩展微服务、分布式系统和无服务器应用程序。
+ [Deequ](https://github.com/awslabs/deequ) – Deequ 是一款工具，可帮助您计算大型数据集的数据质量指标，定义和验证数据质量限制，并随时了解数据分布的变化。

**代码存储库**

SDLF 的源代码和资源可在 [AWS 实验室 GitHub 存储库](https://github.com/awslabs/aws-serverless-data-lake-framework/)中找到。

## 操作说明
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-epics"></a>

### 设置 CI/CD 管道以配置 IaC
<a name="set-up-the-ci-cd-pipeline-to-provision-iac"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 CI/CD 管道以管理数据湖的 IaC。 | 登录 AWS 管理控制台，按照 SDLF 研讨会的[初始设置](https://sdlf.workshop.aws/en/10-deployment/100-setup.html)部分中的步骤进行操作。这将创建初始 CI/CD 资源，例如为数据湖配置和管理 IaC 的 CodeCommit 存储库、 CodeBuild 环境和 CodePipeline 管道。 | DevOps 工程师 | 

### IaC 版本控制
<a name="version-control-the-iac"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在本地计算机上克隆 CodeCommit 存储库。 | 按照 SDLF 研讨会[部署基础](https://sdlf.workshop.aws/en/10-deployment/200-foundations.html)部分中的步骤进行操作。这可以帮助您将托管 IaC 的 Git 存储库克隆至本地环境中。 有关更多信息，请参阅 CodeCommit 文档中的[连接 CodeCommit 存储库](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)。 | DevOps 工程师 | 
| 修改 CloudFormation 模板。 | 使用本地工作站和代码编辑器根据您的用例或要求修改 CloudFormation 模板。将它们提交到本地克隆 Git 存储库。 有关更多信息，请参阅 [AWS CloudFormation 文档中的使用 AWS CloudFormation 模板](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)。 | DevOps 工程师 | 
| 将更改推送到 CodeCommit 存储库。 | 您的基础设施代码现在处于版本控制之下，并且会跟踪对代码库的修改。当您将更改推送到 CodeCommit 存储库时， CodePipeline 会自动将其应用于您的基础架构并将其交付给 CodeBuild。 如果您在中使用 AWS SAM CLI CodeBuild，请运行`sam package`和`sam deploy`命令。如果您使用 AWS CLI，请运行 `aws cloudformation package` 和 `aws cloudformation deploy` 命令。 | DevOps 工程师 | 

## 相关资源
<a name="deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code-resources"></a>

**设置 CI/CD 管道以配置 IaC**
+ [SDLF 研讨会 — 初始设置](https://sdlf.workshop.aws/en/10-deployment/100-setup.html)

**IaC 版本控制**
+ [SDLF 研讨会 — 部署基础](https://sdlf.workshop.aws/en/10-deployment/200-foundations.html)
+ [连接到 CodeCommit 存储库](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)
+ [使用 AWS CloudFormation 模板](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)

**其他资源**
+ [AWS 无服务器数据分析管道参考架构](https://aws.amazon.com/blogs/big-data/aws-serverless-data-analytics-pipeline-reference-architecture/)
+ [SDLF 文档](https://sdlf.readthedocs.io/en/latest/)

# 启动时强制标记 Amazon EMR 集群
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch"></a>

*Priyanka Chaudhary，Amazon Web Services*

## Summary
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-summary"></a>

此模式提供了一种安全控制，可确保 Amazon EMR 集群在创建时被标记。 

Amazon EMR 是一项 Amazon Web Services (AWS) 服务，用于处理和分析大量数据。Amazon EMR 提供可扩展、低配置的服务，作为运行内部集群计算的更简单的替代方案。您可以使用标记以不同的方式对 AWS 资源进行分类，例如按用途、所有者或环境。例如，您可通过将自定义元数据分配给各个 Amazon EMR 集群，为 Amazon EMR 集群添加标签。标签由您定义的键和值组成。我们建议您创建一组一致的标签以满足您的组织要求。当您向 Amazon EMR 集群添加标签时，该标签还会传播到与该集群关联的每个活动亚马逊弹性计算云 (Amazon EC2) 实例。同样，当您从 Amazon EMR 集群中移除标签时，该标签也会从每个关联的活动 EC2 实例中删除。

侦探控件监控 API 调用并启动[RunJobFlow](https://docs.aws.amazon.com/emr/latest/APIReference/API_RunJobFlow.html)、[AddTags](https://docs.aws.amazon.com/emr/latest/APIReference/API_AddTags.html)、和[CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) APIs的 Amazon Event [RemoveTags](https://docs.aws.amazon.com/emr/latest/APIReference/API_RemoveTags.html)s CloudWatch 事件。该事件调用 AWS Lambda，后者运行 Python 脚本。Python 函数从事件的 JSON 输入中获取 Amazon EMR 集群 ID 并执行以下检查：
+ 检查 Amazon EMR 集群是否配置了您指定的标签名称。
+ 如果没有，请向用户发送包含相关信息的 Amazon Simple Notification Service（Amazon SNS）通知：Amazon EMR 集群名称、违规详细信息、AWS 区域、Amazon Web Services account 以及此通知源自 Lambda 的 Amazon 资源名称（ARN）。

## 先决条件和限制
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 用于上传提供的 Lambda 代码的 Amazon Simple Storage Service （Amazon S3）存储桶。或者，您可为此目的创建 S3 存储桶，如*操作说明*部分所述。
+ 您希望接收违规通知的有效电子邮件地址。
+ 您要检查的必填标签列表。

**限制**
+ 这种安全控制为区域性的。您必须将其部署在要监控的每个 AWS 区域。

**产品版本**
+ Amazon EMR 发行版 4.8.0 及更高版本。

## 架构
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-architecture"></a>

**工作流程架构**

![\[集群启动、使用监控 APIs、事件生成、Lambda 函数调用、发送通知。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/1a4fc0f8-b0c9-4391-9c79-9eb3898d6ecb/images/0d95c414-69d1-4f29-a9e7-09f202e27014.png)


**自动化和扩展**
+ 如果您使用的是 [AWS Organ](https://aws.amazon.com/organizations/) izations，则可以使用 [AWS Cloudformation StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) 在要监控的多个账户中部署此模板。

## 工具
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-tools"></a>

**AWS 服务**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) — AWS CloudFormation 可帮助您建模和设置 AWS 资源，快速一致地配置这些资源，并在资源的整个生命周期中对其进行管理。您可以使用模板来描述资源及其依赖关系，然后将它们作为堆栈一起启动和配置，而不必单独管理资源。您可以跨多个 AWS 账户和 AWS 区域管理和预调配堆栈。
+ [Amazon CloudWatch ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) Events-Amazon CloudWatch Events 提供近乎实时的系统事件流，这些事件描述了 AWS 资源的变化。
+ [Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) — Amazon EMR 是一项 Web 服务，可简化大数据框架的运行并高效处理大量数据。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) – AWS Lambda 是一项计算服务，支持无需预置或管理服务器即可运行代码。只有在需要时 Lambda 才运行您的代码，并且能自动扩缩，从每天几个请求扩展到每秒数千个请求。 
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一项对象存储服务。您可以通过 Amazon S3 随时在 Web 上的任何位置存储和检索的任意大小的数据。
+ [Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) — Amazon Simple Notiﬁcation Service (Amazon SNS) 可协调和管理发布者和客户端之间消息的传送或发送，包括 Web 服务器和电子邮件地址。订阅用户接收所有发布至他们所订阅主题的消息，并且一个主题的所有订阅用户收到的消息都相同。

**代码**

此模式包括以下附件：
+ `EMRTagValidation.zip` — 用于安全控制的 Lambda 代码。
+ `EMRTagValidation.yml`— 用于设置事件和 Lambda 函数的 CloudFormation 模板。

## 操作说明
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-epics"></a>

### 设置 S3 存储桶
<a name="set-up-the-s3-bucket"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 定义 S3 存储桶。 | 在 [Amazon S3 控制台](https://console.aws.amazon.com/s3/)，选择或创建 S3 存储桶来托管 Lambda 代码 .zip 文件。此 S3 存储桶必须与您想要监视的 Amazon EMR 集群位于相同的 AWS 区域中。Amazon S3 存储桶名称是全局唯一的，并且命名空间由所有 Amazon Web Services account 共享。S3 存储桶名称不得包含前导斜杠。 | 云架构师 | 
| 上传 Lambda 代码。 | 将*附件*部分中提供的 Lambda 代码 .zip文件上传至 S3 存储桶。                                              | 云架构师 | 

### 部署 AWS CloudFormation 模板
<a name="deploy-the-aws-cloudformation-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动 AWS CloudFormation 模板。 | 在与 S3 存储桶相同的 AWS 区域中打开 AWS [ CloudFormation 控制台](https://console.aws.amazon.com/cloudformation/.)并部署模板。有关部署 AWS CloudFormation 模板的更多信息，请参阅 CloudFormation 文档中的在 [AWS CloudFormation 控制台上创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。 | 云架构师 | 
| 填写模板中的参数。 | 启动模板时，系统将会提示输入以下信息：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/enforce-tagging-of-amazon-emr-clusters-at-launch.html) | 云架构师 | 

### 确认订阅
<a name="confirm-the-subscription"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确认订阅。 |  CloudFormation 模板成功部署后，它会向您提供的电子邮件地址发送一封订阅电子邮件。您必须确认此电子邮件订阅，才能开始接收违规通知。 | 云架构师 | 

## 相关资源
<a name="enforce-tagging-of-amazon-emr-clusters-at-launch-resources"></a>
+ [AWS Lambda 开发人员指南](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
+  [为 Amazon EMR 集群添加标签](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-tags.html)

## 附件
<a name="attachments-1a4fc0f8-b0c9-4391-9c79-9eb3898d6ecb"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/1a4fc0f8-b0c9-4391-9c79-9eb3898d6ecb/attachments/attachment.zip)

# 确保在启动时启用 Amazon EMR 日志记录到 Amazon S3
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch"></a>

*Priyanka Chaudhary，Amazon Web Services*

## Summary
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-summary"></a>

此模式提供了一种安全控制，用于监控在 Amazon Web Services（AWS）上运行的 Amazon EMR 集群的日志记录配置。

Amazon EMR 是用于大数据处理和分析的 AWS 工具。Amazon EMR 提供可扩展的低配置服务，作为运行内部集群计算的替代方法。Amazon EMR 提供两类 EMR 集群。
+ **临时 Amazon EMR 集群**：临时 Amazon EMR 集群在处理完成后自动关闭并停止产生成本。
+ **永久 Amazon EMR 集群**：数据处理任务完成后，永久性 Amazon EMR 集群将继续运行。

Amazon EMR 和 Hadoop 都可以生成日志文件，报告集群上的状态。默认情况下，它们会写入**/mnt/var/log/**目录中的主节点。根据在启动集群时配置集群的方式，您还可将这些日志保存到 Amazon Simple Storage Service (Amazon S3)，并通过图形调试工具进行查看。请注意，只有在启动集群时才可指定 Amazon S3 日志记录。通过此配置，日志每 5 分钟从主节点发送到 Amazon S3 位置。对于瞬态集群，Amazon S3 日志记录非常重要，因为处理完成后集群就会消失，并且这些日志文件可用于调试任何失败的作业。

该模式使用 AWS CloudFormation 模板部署安全控 CloudWatch 件，用于监控 API 调用，并在 “” 上启动 Amazon Events RunJobFlow。” 触发器调用运行 Python 脚本的 AWS Lambda。Lambda 函数从事件 JSON 输入中检索 EMR 集群 ID，并检查 Amazon S3 日志 URI。如果未找到 Amazon S3 URI，Lambda 函数将发送 Amazon Simple Notiﬁcation Service (Amazon SNS) 通知，详细说明 EMR 集群名称、违规详细信息、AWS 区域、Amazon Web Services account 以及通知来源的 Lambda Amazon 资源名称（ARN）。

## 先决条件和限制
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 存放 Lambda 代码 .zip 文件的 S3 存储桶
+ 接收违规通知的电子邮件地址

**限制**
+ 此检测控制是区域性的，必须部署在您要监控的 AWS 区域中。

**产品版本**
+ Amazon EMR 发行版 4.8.0 及以上版本

## 架构
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-architecture"></a>

**目标技术堆栈**
+ 亚马逊 CloudWatch 活动活动
+ Amazon EMR
+ Lambda 函数
+ S3 存储桶
+ Amazon SNS

**目标架构**

![\[确保在启动时启用 Amazon EMR 日志记录到 Amazon S3 的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/079af32e-0418-4bb2-bc20-c67ea5ac3b6e/images/3ba125cb-018a-4ace-838f-8c20992ecc20.png)


**自动化和扩展**
+ 如果您使用的是 AWS Organizations CloudFormation StackSets，则可以使用 [AWS](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) 在要监控的多个账户中部署此模板。

## 工具
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-tools"></a>

**工具**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) — AWS CloudFormation 可帮助您使用基础设施即代码建模和设置 AWS 资源。
+ [AWS Cloudwatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) Ev CloudWatch ents — AWS Events 提供近乎实时的系统事件流，这些事件描述了 AWS 资源的变化。
+ [Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) — Amazon EMR 是托管集群平台，可简化大数据框架的运行。
+ [AWS Lambda](https://aws.amazon.com/lambda/) — AWS Lambda 支持无需预置或管理服务器即可运行代码。只有在需要时 Lambda 才运行您的代码，并且能自动扩缩，从每天几个请求扩展到每秒数千个请求。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/Welcome.html) — Amazon S3 是一个 Web 服务接口，可用于从 Web 上的任何位置存储和检索任意数量的数据。
+ [Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) — Amazon SNS 是一项 Web 服务，可协调和管理发布者和客户端之间消息的传送或发送，包括 Web 服务器和电子邮件地址。

**代码**
+ 该项目的 .zip 文件作为附件提供。

## 操作说明
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-epics"></a>

### 删除 S3 存储桶
<a name="define-the-s3-bucket"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 定义 S3 存储桶。 | 要托管 Lambda 代码 .zip 文件，请选择或创建一个具有不包含前导斜杠的唯一名称的 S3 存储桶。S3 存储桶名称是全局唯一的，并且命名空间由所有 Amazon Web Services account 共享。您的 S3 存储桶需要与正在评估的 Amazon EMR 集群位于同一 AWS 区域。 | 云架构师 | 

### 将 Lambda 代码上传至 S3 存储桶
<a name="upload-the-lambda-code-to-the-s3-bucket"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将 Lambda 代码上传至 S3 存储桶。 | 将“附件”部分中提供的 Lambda 代码.zip 文件上传到 S3 存储桶。S3 存储桶需要与正在评估的 Amazon EMR 集群位于同一区域。 | 云架构师 | 

### 部署 AWS CloudFormation 模板
<a name="deploy-the-aws-cloudformation-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 AWS CloudFormation 模板。 | 在 AWS CloudFormation 控制台上，在与 S3 存储桶相同的区域中，部署作为该模式附件提供的 AWS CloudFormation 模板。在下一个操作说明中，提供参数的值。有关部署 AWS CloudFormation 模板的更多信息，请参阅 “相关资源” 部分。 | 云架构师 | 

### 完成 AWS CloudFormation 模板中的参数
<a name="complete-the-parameters-in-the-aws-cloudformation-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 命名 S3 存储桶。 | 输入您在第一个操作说明中创建的 S3 存储桶的名称。 | 云架构师 | 
| 提供 Amazon S3 密钥。 | 提供 Lambda 代码 .zip 文件在 S3 存储桶中的位置，不带前导斜杠（例如，<directory>/<file-name>.zip）。 | 云架构师 | 
| 提供电子邮箱地址。 | 提供有效的电子邮件地址以接收 Amazon SNS 通知。 | 云架构师 | 
| 定义日志记录级别。 | 定义 Lambda 函数的日志记录级别与频率。“信息”表示有关应用程序进度的详细信息消息。“错误”表示仍可能允许应用程序继续运行的错误事件。“警告”表示潜在的有害情况。 | 云架构师 | 

### 确认订阅
<a name="confirm-the-subscription"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确认订阅。 | 成功部署模板后，它将向提供的电子邮件地址发送订阅电子邮件。您必须确认此电子邮件订阅才能接收违规通知。 | 云架构师 | 

## 相关资源
<a name="ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch-resources"></a>
+ [AWS Lambda](https://aws.amazon.com/lambda/)
+ [Amazon EMR 日志记录](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-debugging.html)
+ [部署 AWS CloudFormation 模板](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)

## 附件
<a name="attachments-079af32e-0418-4bb2-bc20-c67ea5ac3b6e"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/079af32e-0418-4bb2-bc20-c67ea5ac3b6e/attachments/attachment.zip)

# 使用 AWS Glue 作业和 Python 生成测试数据
<a name="generate-test-data-using-an-aws-glue-job-and-python"></a>

*Moinul Al-Mamun，Amazon Web Services*

## Summary
<a name="generate-test-data-using-an-aws-glue-job-and-python-summary"></a>

此模式向您展示如何通过创建用 Python 编写的 AWS Glue 作业，快速轻松地同时生成数百万个示例文件。示例文件存储在 Amazon Simple Storage Service（Amazon S3）存储桶中。能够快速生成大量示例文件对于在 Amazon Web Services Cloud 中测试或评估服务非常重要。例如，您可以通过对数百万个 Amazon S3 前缀的小文件进行数据分析来测试 AWS Glue Studio 或 AWS Glue DataBrew 任务的性能。

尽管您可以使用其他 Amazon Web Services 生成示例数据集，但我们建议您使用 AWS Glue。您无需管理任何基础设施，因为 AWS Glue 是一项无服务器数据处理服务。您只需带上代码并在 AWS Glue 集群中运行即可。此外，AWS Glue 还预调配、配置和扩展运行作业所需资源。您只需为作业运行时使用的资源付费。

## 先决条件和限制
<a name="generate-test-data-using-an-aws-glue-job-and-python-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ AWS 命令行界面（AWS CLI），[已安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)并[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)以使用 Amazon Web Services account 

**产品版本**
+ Python 3.9
+ AWS CLI 版本 2

**限制**

每个触发器的最大 AWS Glue 作业数是 50。有关更多信息，请参阅 [AWS Glue 端点和限额](https://docs.aws.amazon.com/general/latest/gr/glue.html)。

## 架构
<a name="generate-test-data-using-an-aws-glue-job-and-python-architecture"></a>

下图描绘了一个以 AWS Glue 作业为中心的示例架构，该作业将其输出（即示例文件）写入 S3 存储桶。

![\[工作流显示 AWS CLI 启动将输出写入 S3 存储桶的 AWS Glue 任务。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/f35943e8-3b2b-410e-a3f0-05e1ebd357d0/images/452ccbda-71f2-42b8-976d-bcc968bb1dab.png)


下图包含如下工作流：

1. 您可以使用 AWS CLI、AWS 管理控制台 或 API 启动 AWS Glue 作业。AWS CLI 或 API 使您能够自动并行化调用的作业，并缩短生成示例文件的运行时系统。

1. AWS Glue 作业随机生成文件内容，将内容转换为 CSV 格式，然后将内容作为 Amazon S3 对象存储在通用前缀下。每个文件小于 1 千字节。AWS Glue 作业接受两个用户定义的任务参数：`START_RANGE` 和 `END_RANGE`。您可以使用这些参数来设置文件名和每次作业运行在 Amazon S3 中生成的文件数。您可以并行运行此作业的多个实例（例如，100 个实例）。

## 工具
<a name="generate-test-data-using-an-aws-glue-job-and-python-tools"></a>
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一项完全托管的提取、转换、加载（ETL）服务。它可以帮助您在数据存储和数据流之间对数据进行可靠地分类、清理、扩充和移动。
+ [AWS Identity and Access Management (AWS IAM) ](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)通过控制验证和授权使用您 AWS 资源的用户，帮助您安全地管理对您 AWS 资源的访问。

## 最佳实践
<a name="generate-test-data-using-an-aws-glue-job-and-python-best-practices"></a>

在实施此模式时，请考虑以下 AWS Glue 最佳实践：
+ **使用正确的 AWS Glue Worker 类型来降低成本。**我们建议您了解 Worker 类型的不同属性，然后根据 CPU 和内存要求为工作负载选择正确的 Worker 类型。对于这种模式，我们建议您使用 Python Shell 作业作为作业类型，以最大限度地减少 DPU 并降低成本。有关更多信息，请参阅 AWS Glue 开发人员指南中的[在 AWS Glue 中添加作业](https://docs.aws.amazon.com/glue/latest/dg/add-job.html)。
+ **使用正确的并发限制来扩展作业。**我们建议您根据自己的时间要求和所需文件数量来确定 AWS Glue 作业的最大并发度。
+ **首先开始生成少量文件。**为了在构建 AWS Glue 作业时降低成本并节省时间，请从少量文件（例如 1,000 个）开始。这样可以更轻松地进行故障排除。如果成功生成少量文件，则可以扩展到更多数量的文件。
+ **首先在本地运行。**为了在构建 AWS Glue 作业时降低成本并节省时间，请在本地开始开发并测试代码。有关设置 Docker 容器以帮助您在 Shell 和集成式开发环境（IDE）中测试提取、转换、加载（ETL）作业的说明，请参阅 AWS 大数据博客文章[使用容器在本地开发 AWS Glue ETL 作业](https://aws.amazon.com/blogs/big-data/developing-aws-glue-etl-jobs-locally-using-a-container/)。

有关更多 AWS Glue 最佳实践，请参阅 AWS Glue 文档中的[最佳实践](https://docs.aws.amazon.com/prescriptive-guidance/latest/serverless-etl-aws-glue/best-practices.html)。

## 操作说明
<a name="generate-test-data-using-an-aws-glue-job-and-python-epics"></a>

### 创建目标 S3 存储桶和 IAM 角色
<a name="create-a-destination-s3-bucket-and-iam-role"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 S3 存储桶以存储文件。 | 创建 [S3 存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)及其中的[前缀](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-prefixes.html)。此模式使用该 `s3://{your-s3-bucket-name}/small-files/` 位置进行演示。 | 应用程序开发人员 | 
| 创建和配置 IAM 角色。 | 您必须创建 IAM 角色，这样 AWS Glue 作业可以使用该角色写入 S3 存储桶。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 应用程序开发人员 | 

### 创建和配置 AWS Glue 作业以处理并发运行
<a name="create-and-configure-an-aws-glue-job-to-handle-concurrent-runs"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 AWS Glue 作业。 | 您必须创建 AWS Glue 作业来生成内容并将其存储在 S3 存储桶中。创建 [AWS Glue 作业](https://docs.aws.amazon.com/glue/latest/dg/console-jobs.html)，然后通过完成以下步骤来配置作业：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 应用程序开发人员 | 
| 更新作业代码。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 应用程序开发人员 | 

### 从命令行或控制台运行 AWS Glue 作业
<a name="run-the-aws-glue-job-from-the-command-line-or-console"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 从命令行运行 AWS Glue 作业。 | 要从 AWS CLI 运行 AWS Glue 作业，请使用您的值运行以下命令：<pre>cmd:~$ aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"0","--END_RANGE":"1000000"}'<br />cmd:~$ aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1000000","--END_RANGE":"2000000"}'</pre>有关从 AWS 管理控制台运行 AWS Glue 任务的说明，请参阅此模式中的*在 AWS 管理控制台中运行 AWS Glue 任务*部分。如果您想使用不同的参数同时运行多个执行，我们建议您使用 AWS CLI 运行 AWS Glue 任务，如以上示例所示。要生成所有 AWS CLI 命令（在使用特定的并行化系数生成指定数量的文件时所需），请运行以下 bash 代码（使用您的值）：<pre># define parameters<br />NUMBER_OF_FILES=10000000;<br />PARALLELIZATION=50; <br /> <br /># initialize<br />_SB=0;<br />      <br /># generate commands<br />for i in $(seq 1 $PARALLELIZATION); <br />do <br />      echo aws glue start-job-run --job-name create_small_files --arguments "'"'{"--START_RANGE":"'$(((NUMBER_OF_FILES/PARALLELIZATION) * (i-1) + _SB))'","--END_RANGE":"'$(((NUMBER_OF_FILES/PARALLELIZATION) * (i)))'"}'"'";<br />      _SB=1; <br />done</pre>如果使用上述脚本，请考虑以下事项：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) 要查看上述脚本的输出示例，请参阅此模式的*其他信息*部分中的 *Shell 脚本输出*。 | 应用程序开发人员 | 
| 在 AWS 管理控制台 中运行 AWS Glue 作业。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 应用程序开发人员 | 
| 检查 AWS Glue 作业的状态。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-test-data-using-an-aws-glue-job-and-python.html) | 应用程序开发人员 | 

## 相关资源
<a name="generate-test-data-using-an-aws-glue-job-and-python-resources"></a>

**参考**
+ [Registry of Open Data on AWS](https://registry.opendata.aws/)
+ [用于分析的数据集](https://aws.amazon.com/marketplace/solutions/data-analytics/data-sets)
+ [在 AWS 上打开数据](https://aws.amazon.com/opendata/)
+ [在 AWS Glue 中添加作业](https://docs.aws.amazon.com/glue/latest/dg/add-job.html)
+ [AWS Glue 入门](https://aws.amazon.com/glue/getting-started/)

**指南和模式**
+ [AWS Glue 最佳实践](https://docs.aws.amazon.com/prescriptive-guidance/latest/serverless-etl-aws-glue/best-practices.html)
+ [加载测试应用程序](https://docs.aws.amazon.com/prescriptive-guidance/latest/load-testing/welcome.html)

## 附加信息
<a name="generate-test-data-using-an-aws-glue-job-and-python-additional"></a>

**基准测试**

作为基准测试的一部分，该模式用于使用不同的并行化参数生成 1000 万个文件。下表显示测试输出：


| 
| 
| 并行化 | 作业运行生成的文件数 | 作业时长 | Speed | 
| --- |--- |--- |--- |
| 10 | 1000000 | 6 小时 40 分钟 | 很慢 | 
| 50 | 200,000 | 80 分钟 | 中 | 
| 100 | 100000 | 40 minutes | 快速 | 

如果要加快处理速度，可以在作业配置中配置更多的并发运行。您可以根据自己的要求轻松调整作业配置，但请记住，AWS Glue 服务限额存在限制。有关更多信息，请参阅 [AWS Glue 端点和限额](https://docs.aws.amazon.com/general/latest/gr/glue.html)。

**Shell 脚本输出**

以下示例显示了此模式中*从命令行运行 AWS Glue 作业*情节的 Shell 脚本的输出。

```
user@MUC-1234567890 MINGW64 ~
  $ # define parameters
  NUMBER_OF_FILES=10000000;
  PARALLELIZATION=50;
  # initialize
  _SB=0;
   
  # generate commands
  for i in $(seq 1 $PARALLELIZATION);
   do
         echo aws glue start-job-run --job-name create_small_files --arguments "'"'{"--START_RANGE":"'$(((NUMBER_OF_FILES/PARALLELIZATION)  (i-1) + SB))'","--ENDRANGE":"'$(((NUMBER_OF_FILES/PARALLELIZATION)  (i)))'"}'"'";
         _SB=1;
   done
   
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"0","--END_RANGE":"200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"200001","--END_RANGE":"400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"400001","--END_RANGE":"600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"600001","--END_RANGE":"800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"800001","--END_RANGE":"1000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1000001","--END_RANGE":"1200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1200001","--END_RANGE":"1400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1400001","--END_RANGE":"1600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1600001","--END_RANGE":"1800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"1800001","--END_RANGE":"2000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2000001","--END_RANGE":"2200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2200001","--END_RANGE":"2400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2400001","--END_RANGE":"2600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2600001","--END_RANGE":"2800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"2800001","--END_RANGE":"3000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3000001","--END_RANGE":"3200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3200001","--END_RANGE":"3400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3400001","--END_RANGE":"3600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3600001","--END_RANGE":"3800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"3800001","--END_RANGE":"4000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4000001","--END_RANGE":"4200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4200001","--END_RANGE":"4400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4400001","--END_RANGE":"4600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4600001","--END_RANGE":"4800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"4800001","--END_RANGE":"5000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5000001","--END_RANGE":"5200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5200001","--END_RANGE":"5400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5400001","--END_RANGE":"5600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5600001","--END_RANGE":"5800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"5800001","--END_RANGE":"6000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6000001","--END_RANGE":"6200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6200001","--END_RANGE":"6400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6400001","--END_RANGE":"6600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6600001","--END_RANGE":"6800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"6800001","--END_RANGE":"7000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7000001","--END_RANGE":"7200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7200001","--END_RANGE":"7400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7400001","--END_RANGE":"7600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7600001","--END_RANGE":"7800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"7800001","--END_RANGE":"8000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8000001","--END_RANGE":"8200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8200001","--END_RANGE":"8400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8400001","--END_RANGE":"8600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8600001","--END_RANGE":"8800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"8800001","--END_RANGE":"9000000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9000001","--END_RANGE":"9200000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9200001","--END_RANGE":"9400000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9400001","--END_RANGE":"9600000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9600001","--END_RANGE":"9800000"}'
  aws glue start-job-run --job-name create_small_files --arguments '{"--START_RANGE":"9800001","--END_RANGE":"10000000"}'
  
  user@MUC-1234567890 MINGW64 ~
```

**常见问题解答**

*我应该使用多少个并发运行或并行作业？*

并发运行和并行作业的数量取决于您的时间要求和所需测试文件数量。我们建议您检查正在创建的文件的大小。首先，检查 AWS Glue 作业生成所需数量的文件需要多长时间。然后，使用正确的并发运行次数来实现您的目标。例如，如果您假设 100,000 个文件需要 40 分钟才能完成运行，但目标时间为 30 分钟，则必须增加 AWS Glue 作业的并发设置。

*我可以使用这种模式创建什么类型的内容？*

您可以创建任何类型的内容，例如具有不同分隔符的文本文件（例如 PIPE、JSON 或 CSV）。此模式使用 Boto3 写入文件，然后将文件保存到 S3 存储桶中。

*我需要在 S3 存储桶中获得什么级别的 IAM 权限？*

您必须具有基于身份的策略，该策略允许对 S3 存储桶中的对象进行 `Write` 访问。有关更多信息，请参阅 Amazon S3 文档中的 [Amazon S3：允许对 S3 存储桶中的对象进行读写访问](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_s3_rw-bucket.html)。

# 使用 Amazon IoT Greengrass 将物联网数据直接摄取至 Amazon S3，经济实惠
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass"></a>

*Sebastian Viviani 和 Rizwan Syed，Amazon Web Services*

## Summary
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-summary"></a>

本文向您介绍了如何使用 Amazon IoT Greengrass Version 2 设备经济高效地将物联网 (IoT) 数据直接摄取至 Amazon Simple Storage Service (Amazon S3) 存储桶中。设备运行自定义组件，用于读取物联网数据，并将数据保存在永久存储（即本地磁盘或卷）中。然后，设备将物联网数据压缩为 Apache Parquet 文件，并定期将数据上传至 S3 存储桶。

您采集的物联网数据的数量和速度仅受边缘硬件功能以及网络带宽的限制。您可使用 Amazon Athena 经济高效地分析您摄取的数据。Athena 支持使用 [Amazon Managed Grafana](https://docs.aws.amazon.com/grafana/latest/userguide/what-is-Amazon-Managed-Service-Grafana.html) 进行压缩 Apache Parquet 文件和数据可视化。

## 先决条件和限制
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 在 [Amazon IoT Greengrass Version 2](https://docs.aws.amazon.com/greengrass/v2/developerguide/greengrass-v2-whats-new.html) 上运行的[边缘网关](https://docs.aws.amazon.com/greengrass/v1/developerguide/quick-start.html)手机传感器数据。（数据来源和数据收集过程超出了此模式的范围，但您几乎可以使用任何类型的传感器数据。本示例采用本地 [MQTT](https://mqtt.org/) 代理，其带传感器或网关，可在本地发布数据）。
+ Amazon IoT Greengrass [组件](https://docs.aws.amazon.com/greengrass/v2/developerguide/develop-greengrass-components.html)、[角色](https://docs.aws.amazon.com/greengrass/v1/developerguide/service-role.html)和 [SDK 依赖项](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#installation)
+ 用于将数据上传至 S3 存储桶的[流管理器组件](https://docs.aws.amazon.com/greengrass/v2/developerguide/stream-manager-component.html)
+ [适用于 Java 的](https://aws.amazon.com/sdk-for-java/) AW [S 开发工具包、适用于 JavaScript](https://aws.amazon.com/sdk-for-javascript/) Java 的 A [WS 开发工具包或适用于 Python 的 AWS 开发工具包 (Boto3](https://docs.aws.amazon.com/pythonsdk/)) 来运行 APIs

**限制**
+ 这种模式中的数据不会实时上传至 S3 存储桶。有延迟期，您可配置延迟时间。数据在边缘设备中临时缓冲，然后在到期后上传。
+ SDK 仅可采用 Java、Node.js 和 Python 语言。

## 架构
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-architecture"></a>

**目标技术堆栈**
+ Amazon S3
+ Amazon IoT Greengrass
+ MQTT 代理
+ 流管理器组件

**目标架构**

下图显示了一种架构，该架构旨在摄取物联网传感器数据，并将该数据存储至 S3 存储桶。

![\[架构图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/b9032ae2-fffb-4750-b161-09810e19d878/images/8c28e639-5dcf-4950-b4a6-8015ec1a2894.png)


图表显示了以下工作流：

1. 多个传感器（例如温度和阀门）更新会发布到本地 MQTT 代理。

1. 订阅这些传感器的 Parquet 文件压缩器会更新主题并接收这些更新。

1. Parquet 文件压缩器将更新项存储在本地。

1. 期限过后，存储的文件被压缩为 Parquet 文件，然后传递至流管理器，以上传到指定的 S3 存储桶。

1. 流管理器会将 Parquet 文件上传至 S3 存储桶。

**注意**  
流管理器（`StreamManager`）是托管式组件。有关如何将数据导出至 Amazon S3 的示例，请参阅 Amazon IoT Greengrass 文档中的[流管理器](https://docs.aws.amazon.com/greengrass/v2/developerguide/stream-manager-component.html)。你可以使用本地 MQTT 代理作为组件，也可以使用其他代理，比如 [Eclipse Mosquitto](https://mosquitto.org/)。

## 工具
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-tools"></a>

**AWS 工具**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一种交互式查询服务，可帮助您使用标准 SQL 直接在 Amazon S3 中分析数据。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [Amazon IoT Greengrass](https://docs.aws.amazon.com/greengrass/v2/developerguide/what-is-iot-greengrass.html) 是一项开源 IoT 边缘运行时和云服务，可帮助您在设备上构建、部署和管理 IoT 应用程序。

**其他工具**
+ [Apache Parquet](https://parquet.apache.org/) 是一种专为存储和检索而设计的开源列式数据文件格式。
+ [MQTT](https://docs.aws.amazon.com/iot/latest/developerguide/mqtt.html)（消息队列遥测传输）是一种轻量级消息协议，专为受限的设备而设计。

## 最佳实践
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-best-practices"></a>

**对上传的数据使用正确分区格式**

对 S3 存储桶中的根前缀名称没有具体要求（例如 `"myAwesomeDataSet/"` 或 `"dataFromSource"`），但我们建议您使用有意义的分区和前缀，以便于理解数据集的用途。

我们还建议您在 Amazon S3 中使用正确分区，以便查询在数据集上以最佳方式运行。在以下示例中，数据以 HIVE 格式分区，以便优化每个 Athena 查询扫描的数据量。这可以提高性能并降低成本。

`s3://<ingestionBucket>/<rootPrefix>/year=YY/month=MM/day=DD/HHMM_<suffix>.parquet`

## 操作说明
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-epics"></a>

### 设置您的环境
<a name="set-up-your-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 S3 存储桶。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 应用程序开发人员 | 
| 添加 IAM 权限至 S3 存储桶。 | 要向用户授予您之前创建的 S3 存储桶和前缀写入权限，请将以下 IAM policy 添加至您的 Amazon IoT Greengrass 角色：<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Sid": "S3DataUpload",<br />            "Effect": "Allow",<br />            "Action": [<br />                "s3:List*",<br />                "s3:Put*"<br />            ],<br />            "Resource": [<br />                "arn:aws:s3:::<ingestionBucket>",<br />                "arn:aws:s3:::<ingestionBucket>/<prefix>/*"<br />            ]<br />        }<br />    ]<br />}</pre>有关更多信息，请参阅 Aurora 文档中的[创建 Amazon S3 资源 IAM policy](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.Authorizing.IAM.S3CreatePolicy.html)。接下来，更新 S3 存储桶的资源策略（如果需要），以允许使用正确的 AWS [主体](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-bucket-user-policy-specifying-principal-intro.html)写入。 | 应用程序开发人员 | 

### 构建和部署 Amazon IoT Greengrass 组件
<a name="build-and-deploy-the-aws-iot-greengrass-component"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新组件的配方。 | 当您根据以下示例[创建部署](https://docs.aws.amazon.com/greengrass/v2/developerguide/create-deployments.html)时[更新组件配置](https://docs.aws.amazon.com/greengrass/v2/developerguide/update-component-configurations.html)：<pre>{<br />  "region": "<region>",<br />  "parquet_period": <period>,<br />  "s3_bucket": "<s3Bucket>",<br />  "s3_key_prefix": "<s3prefix>"<br />}</pre>将 `<region>` 替换为您的 AWS 区域、将 `<period>` 替换为定期间隔、将 `<s3Bucket>` 替换为 S3 存储桶，将 `<s3prefix>` 替换为前缀。 | 应用程序开发人员 | 
| 创建组件。 | 请执行以下操作之一：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 应用程序开发人员 | 
| 更新 MQTT 客户端。 | 示例代码不使用身份验证，因为该组件在本地连接至代理。如果您的场景不同，请按需要更新 MQTT 客户端部分。此外，执行下列操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 应用程序开发人员 | 

### 将该组件添加至 Amazon IoT Greengrass Version 2 核心设备中
<a name="add-the-component-to-the-aws-iot-greengrass-version-2-core-device"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新核心设备部署。 | 如果 Amazon IoT Greengrass Version 2 核心设备的部署已经存在，[请修改部署](https://docs.aws.amazon.com/greengrass/v2/developerguide/revise-deployments.html)。如果部署不存在，请[创建新部署](https://docs.aws.amazon.com/greengrass/v2/developerguide/create-deployments.html)。要为组件指定正确的名称，请根据以下内容[更新新组件的日志管理器配置](https://docs.aws.amazon.com/greengrass/v2/developerguide/log-manager-component.html)（如果需要）：<pre>{<br />  "logsUploaderConfiguration": {<br />    "systemLogsConfiguration": {<br />    ...<br />    },<br />    "componentLogsConfigurationMap": {<br />      "<com.iot.ingest.parquet>": {<br />        "minimumLogLevel": "INFO",<br />        "diskSpaceLimit": "20",<br />        "diskSpaceLimitUnit": "MB",<br />        "deleteLogFileAfterCloudUpload": "false"<br />      }<br />      ...<br />    }<br />  },<br />  "periodicUploadIntervalSec": "300"<br />}</pre>最后，完成对 Amazon IoT Greengrass 核心设备部署的修订。 | 应用程序开发人员 | 

### 验证是否将数据摄取至 S3 存储桶
<a name="verify-data-ingestion-into-the-s3-bucket"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看 Amazon IoT Greengrass 卷日志。 | 检查以下各项：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 应用程序开发人员 | 
| 检查 S3 存储桶。 | 验证数据是否正在上传至 S3 存储桶。您可以看到每个时间段在上传的文件。您还可以通过查询下一部分中的数据，验证数据是否已上传至 S3 存储桶。 | 应用程序开发人员 | 

### 设置来自 Athena 的查询
<a name="set-up-querying-from-athena"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建数据库和表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 应用程序开发人员 | 
| 授予 Athena 数据访问权限。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 应用程序开发人员 | 

## 问题排查
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| MQTT 客户端无法连接 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 
| MQTT 客户端订阅失败 | 验证 MQTT 代理权限。如果你有来自 AWS 的 MQTT 代理，请参阅 [MQTT 3.1.1 代理 (Moquette)](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-broker-moquette-component.html) 和 [MQTT 5 代理 (EMQX)](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-broker-emqx-component.html)。 | 
| 无法创建 Parquet 文件 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 
| 对象未上传至 S3 存储桶 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.html) | 

## 相关资源
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-resources"></a>
+ [DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html)（Pandas 文档）
+ [Apache Parquet 文档](https://parquet.apache.org/docs/)（Parquet 文档）
+ [开发 Amazon IoT Greengrass 组件](https://docs.aws.amazon.com/greengrass/v2/developerguide/develop-greengrass-components.html)（Amazon IoT Greengrass 开发人员指南，第 2 版）
+ [将 Amazon IoT Greengrass 组件部署至设备](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-deployments.html)（Amazon IoT Greengrass 开发人员指南，第 2 版）
+ [与本地物联网设备互动](https://docs.aws.amazon.com/greengrass/v2/developerguide/interact-with-local-iot-devices.html)（Amazon IoT Greengrass 开发人员指南，第 2 版）
+ [MQTT 3.1.1 代理 (Moquette)](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-broker-moquette-component.html)（Amazon IoT Greengrass 开发人员指南，第 2 版）
+ [MQTT 5 代理 (EMQX)](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-broker-emqx-component.html)（Amazon IoT Greengrass 开发人员指南，第 2 版）

## 附加信息
<a name="cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass-additional"></a>

**成本分析**

以下成本分析场景演示了此模式中涵盖的数据摄取方法如何影响 Amazon Web Services Cloud 中的数据摄取成本。此场景中的定价示例基于发布价格。价格可能会发生变化。此外，您的费用可能会有所不同，具体取决于您的 AWS 区域、AWS 服务限额以及与云环境相关的其他因素。

*输入信号集*

该分析使用以下一组输入信号为基础，将物联网摄取成本与其他可用替代方案进行比较。


| 
| 
| 信号数量 | 频率 | 每个信号的数据 | 
| --- |--- |--- |
| 125 | 25 Hz | 8 字节 | 

在此情况下，系统接收 125 个信号。每个信号为 8 字节，每 40 毫秒 (25 Hz) 会出现一次。这些信号可单独发出，也可以分组至公共有效载荷中。您可根据需要选择拆分和打包这些信号。您还可确定延迟。延迟由接收、累积和摄取数据时间段组成。

为了便于比较，此场景的摄取操作基于 `us-east-1` AWS 区域。成本比较仅适用 Amazon Web Services。硬件或连接等其他成本未计入分析。

*成本比较*

下表显示了每种摄取方法的每月费用（以美元为单位）。


| 
| 
| 方法 | 月度成本 | 
| --- |--- |
| AWS 物联网 SiteWise *\$1* | 331.77 美元 | 
| 带有数据处理包的 AWS IoT SiteWise Edge（将所有数据保存在边缘） | 200 美元 | 
| AWS IoT Core 和 Amazon S3 访问原始数据规则 | 84.54 美元 | 
| 边缘 Parquet 文件压缩并上传至 Amazon S3 | 0.5 美元 | 

\$1必须对数据进行缩减采样，才能符合服务限额。这意味着使用此方法会丢失数据。

*替代方法*

本节显示了以下替代方法等效成本：
+ **AWS IoT SiteWise** — 每个信号都必须以单独的消息形式上传。因此，每月的消息总数为 125×25×3600×24×30，相当于每月 81 亿条消息。但是，AWS IoT 每个属性每秒 SiteWise 只能处理 10 个数据点。假设将数据缩减到 10 Hz，则每月的消息数量将减少到125×10×3600×24×30，即 32.4 亿条。如果您使用发布者组件，该组件以 10 个为一组（每百万封邮件 1 美元）打包，则每月的费用为每月 324 美元。假设每条消息为 8 字节 (1 Kb/125)，则为 25.92 Gb 的数据存储空间。这增加了每月 7.77 美元的费用。第一个月的总费用为 331.77 美元，每月增加 7.77 美元。
+ **带有数据处理包的 AWS IoT SiteWise Edge，包括在边缘完全处理的所有模型和信号（即无需云端接入）**— 您可以使用数据处理包作为替代方案，以降低成本并配置在边缘计算的所有模型。即使没有进行实际计算，也可以仅用于存储和可视化。在这种情况下，必须为边缘网关使用强大硬件。每月的固定费用为 200 美元。
+ **MQTT 直接接入 AWS IoT Core by MQTT 以及物联网规则，以将原数据存储至 Amazon S3** — 假设所有信号都发布在公共负载中，则发布到 AWS IoT Core 的消息总数为 25×3600×24×30，即每月 6,480 万条。按每百万条消息 1 美元算，每月费用为 64.8 美元。按每百万条规则激活 0.15 美元，每条消息一条规则，每月增加 19.44 美元的费用。按照 Amazon S3 中每 Gb 存储空间 0.023 美元成本，每月再增加 1.5 美元（每月增加以反映新数据）。第一个月的总费用为 84.54 美元，每月增加 1.5 美元。
+ **在边缘压缩 Parquet 文件中的数据并上传至 Amazon S3（建议的方法**）— 压缩率取决于数据的类型。使用针对 MQTT 测试的相同工业数据，整个月的总产出数据为 1.2 Gb。每月的费用为 0.03 美元。其他基准测试中描述的压缩率（使用随机数据）约为 66％（更接近最坏的情况）。总数据量为 21 Gb，每月花费 0.5 美元。

**Parquet 文件生成器**

以下代码示例显示了用 Python 编写的 Parquet 文件生成器结构。该代码示例仅用于说明，如果粘贴到您的环境中则不起作用。

```
import queue
import paho.mqtt.client as mqtt
import pandas as pd

#queue for decoupling the MQTT thread
messageQueue = queue.Queue()
client = mqtt.Client()
streammanager = StreamManagerClient()

def feederListener(topic, message):
    payload = {
        "topic" : topic,
        "payload" : message,
    }
    messageQueue.put_nowait(payload)

def on_connect(client_instance, userdata, flags, rc):
    client.subscribe("#",qos=0)

def on_message(client, userdata, message):
    feederListener(topic=str(message.topic), message=str(message.payload.decode("utf-8")))


filename = "tempfile.parquet"
streamname = "mystream"
destination_bucket= "amzn-s3-demo-bucket"
keyname="mykey"
period= 60

client.on_connect = on_connect
client.on_message = on_message
streammanager.create_message_stream(
            MessageStreamDefinition(name=streamname, strategy_on_full=StrategyOnFull.OverwriteOldestData)
        )


while True:
   try:
       message = messageQueue.get(timeout=myArgs.mqtt_timeout)
   except (queue.Empty):
       logger.warning("MQTT message reception timed out")

   currentTimestamp = getCurrentTime()
   if currentTimestamp >= nextUploadTimestamp:
       df = pd.DataFrame.from_dict(accumulator)
       df.to_parquet(filename)
       s3_export_task_definition = S3ExportTaskDefinition(input_url=filename, bucket=destination_bucket, key=key_name)
       streammanager.append_message(streamname, Util.validate_and_serialize_to_json_bytes(s3_export_task_definition))
       accumulator = {}
       nextUploadTimestamp += period
   else:
        accumulator.append(message)
```

# 使用 Lambda 函数在瞬态 EMR 集群中启动 Spark 作业
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function"></a>

*Dhrubajyoti Mukherjee，Amazon Web Services*

## Summary
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-summary"></a>

此模式使用 Amazon EMR RunJobFlow API 操作启动临时集群，以便通过 Lambda 函数运行 Spark 作业。瞬态 EMR 集群设计为在作业完成或发生任何错误时立即终止。临时集群可以节省成本，因为它只在计算期间运行，而且它在云环境中提供了可扩展性和灵活性。

瞬态 EMR 集群是在 Lambda 函数中使用 Boto3 API 和 Python 编程语言启动的。用 Python 编写的 Lambda 函数提供了更大的灵活性，可在需要时启动集群。

为了演示批处理计算和输出示例，此模式将在 EMR 集群中通过 Lambda 函数启动 Spark 作业，并针对一家虚构公司的示例销售数据运行批处理计算。Spark 作业的输出将是 Amazon Simple Storage Service (Amazon S3)中的逗号分隔值 (CSV) 文件。输入数据文件、Spark.jar 文件、代码片段以及用于运行计算的虚拟私有云 (VPC) 和 AWS Identity and Access Management (IAM) 角色的 AWS CloudFormation 模板作为附件提供。

## 先决条件和限制
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account

**限制**
+ 每次只能从代码中启动一个 Spark 作业。 

**产品版本**
+ 已在 Amazon EMR 6.0.0 上进行了测试

## 架构
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-architecture"></a>

**目标技术堆栈 **
+ Amazon EMR 
+ AWS Lambda
+ Amazon S3
+ Apache Spark

**目标架构 **

![\[Lambda 到 Amazon EMR 和 Spark 到 Amazon S3\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/6c999fa7-9550-4929-a5c1-60394142175d/images/eb4fbb3f-2114-44d2-b9da-3fdcb9ca456e.png)


**自动化和扩缩**

要实现 Spark-EMR 批处理计算的自动化，您可以使用以下任一选项。
+ 实施可在 cron 计划中启动 Lambda 函数的亚马逊 EventBridge 规则。有关更多信息，请参阅[教程：使用安排 AWS Lambda 函数](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-run-lambda-schedule.html)。 EventBridge
+ 配置[Amazon S3 事件通知](https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html)以在文件到达时启动 Lambda 函数。
+ 通过事件主体和 Lambda 环境变量将输入参数传递给 AWS Lambda 函数。

## 工具
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-tools"></a>

**Amazon Web Services**
+ [Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) 是一个托管集群平台，可简化在 AWS 上运行大数据框架以处理和分析海量数据的操作。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，而无需预置或管理服务器。它仅在需要时运行您的代码，并且能自动扩缩，因此您只需为使用的计算时间付费。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**其他工具**
+ [Apache Spark](https://spark.apache.org/docs/latest/) 是用于大规模数据处理的多语言分析引擎。

## 操作说明
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-epics"></a>

### 创建 Amazon EMR 和 Lambda IAM 角色以及 VPC
<a name="create-the-amazon-emr-and-lambda-iam-roles-and-the-vpc"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 IAM 角色和 VPC。 | 如果您已经拥有 AWS Lambda 和 Amazon EMR IAM 角色以及 VPC，则可以跳过此步骤。要运行代码，EMR 集群和 Lambda 函数都需要 IAM 角色。EMR 集群还需要一个具有公有子网的 VPC 或带有 NAT 网关的私有子网。要自动创建所有 IAM 角色和 VPC，请按原样部署附加的 AWS CloudFormation 模板，或者您可以按照*其他信息*部分中的指定手动创建角色和 VPC。 | 云架构师 | 
| 注意 AWS CloudFormation 模板的输出密钥。 | 成功部署 CloudFormation 模板后，在 AWS CloudFormation 控制台中导航至 “**输出**” 选项卡。请注意五个输出键：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function.html)在创建 Lambda 函数时，您将使用这些键中的值。 | 云架构师 | 

### 上传 Spark .jar 文件
<a name="upload-the-spark-jar-file"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 上传 Spark .jar 文件。 | 将 Spark .jar 文件上传到 AWS CloudFormation 堆栈创建的 S3 存储桶。存储桶名称与输出键 `S3Bucket` 相同。 | 常规 AWS | 

### 创建 Lambda 函数来启动 EMR 集群
<a name="create-the-lambda-function-to-launch-the-emr-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 Lambda 函数。 | 在 Lambda 控制台上，创建一个具有执行角色的 Python 3.9\$1 Lambda 函数。执行角色策略必须允许 Lambda 启动 EMR 集群。（参见随附的 AWS CloudFormation 模板。） | 数据工程师、云工程师 | 
| 复制并粘贴代码。 | 用此模式*其他信息*部分中的代码替换 `lambda_function.py` 文件中的代码。 | 数据工程师、云工程师 | 
| 更改代码中的参数。 | 请根据代码中的注释更改参数值，以匹配您的 Amazon Web Services account。 | 数据工程师、云工程师 | 
| 启动函数以启动集群。 | 启动函数以使用提供的 Spark .jar 文件启动瞬态 EMR 集群的创建。它将运行 Spark 作业，并在作业完成后自动终止。 | 数据工程师、云工程师 | 
| 检查 EMR 集群状态。 | EMR 集群启动后，它会显示在 Amazon EMR 控制台的**集群**选项卡下。可以相应地检查启动集群或运行作业时出现的任何错误。 | 数据工程师、云工程师 | 

### 设置并运行示例演示
<a name="set-up-and-run-the-sample-demo"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 上传 Spark .jar 文件。 | 从*附件*部分下载 Spark .jar 文件并将其上传到 S3 存储桶。 | 数据工程师、云工程师 | 
| 上传输入数据集。 | 将附件 `fake_sales_data.csv` 文件上传到 S3 存储桶。 | 数据工程师、云工程师 | 
| 粘贴 Lambda 代码并更改参数。 | 复制**工具**部分中的代码，然后将代码粘贴到 Lambda 函数中，替换代码 `lambda_function.py` 文件。更改参数值以匹配您的账户。 | 数据工程师、云工程师 | 
| 启动函数并验证输出。 | 在 Lambda 函数使用提供的 Spark 作业启动集群后，它会在 S3 存储桶中生成一个 .csv 文件。 | 数据工程师、云工程师 | 

## 相关资源
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-resources"></a>
+ [Building Spark](https://spark.apache.org/docs/latest/building-spark.html)
+ [Apache Spark 和 Amazon EMR](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark.html)
+ [Boto3 Docs run\$1job\$1flow 文档](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/emr.html#EMR.Client.run_job_flow)
+ [Apache Spark 信息和文档](https://spark.apache.org/)

## 附加信息
<a name="launch-a-spark-job-in-a-transient-emr-cluster-using-a-lambda-function-additional"></a>

**代码**

```
"""
Copy paste the following code in your Lambda function. Make sure to change the following key parameters for the API as per your account

-Name (Name of Spark cluster)
-LogUri (S3 bucket to store EMR logs)
-Ec2SubnetId (The subnet to launch the cluster into)
-JobFlowRole (Service role for EC2)
-ServiceRole (Service role for Amazon EMR)

The following parameters are additional parameters for the Spark job itself. Change the bucket name and prefix for the Spark job (located at the bottom).

-s3://your-bucket-name/prefix/lambda-emr/SparkProfitCalc.jar (Spark jar file)
-s3://your-bucket-name/prefix/fake_sales_data.csv (Input data file in S3)
-s3://your-bucket-name/prefix/outputs/report_1/ (Output location in S3)
"""
import boto3

client = boto3.client('emr')


def lambda_handler(event, context):
    response = client.run_job_flow(
        Name='spark_job_cluster',
        LogUri='s3://your-bucket-name/prefix/logs',
        ReleaseLabel='emr-6.0.0',
        Instances={
            'MasterInstanceType': 'm5.xlarge',
            'SlaveInstanceType': 'm5.large',
            'InstanceCount': 1,
            'KeepJobFlowAliveWhenNoSteps': False,
            'TerminationProtected': False,
            'Ec2SubnetId': 'subnet-XXXXXXXXXXXXXX'
        },
        Applications=[{'Name': 'Spark'}],
        Configurations=[
            {'Classification': 'spark-hive-site',
             'Properties': {
                 'hive.metastore.client.factory.class': 'com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory'}
             }
        ],
        VisibleToAllUsers=True,
        JobFlowRole='EMRLambda-EMREC2InstanceProfile-XXXXXXXXX',
        ServiceRole='EMRLambda-EMRRole-XXXXXXXXX',
        Steps=[
            {
                'Name': 'flow-log-analysis',
                'ActionOnFailure': 'TERMINATE_CLUSTER',
                'HadoopJarStep': {
                    'Jar': 'command-runner.jar',
                    'Args': [
                        'spark-submit',
                        '--deploy-mode', 'cluster',
                        '--executor-memory', '6G',
                        '--num-executors', '1',
                        '--executor-cores', '2',
                        '--class', 'com.aws.emr.ProfitCalc',
                        's3://your-bucket-name/prefix/lambda-emr/SparkProfitCalc.jar',
                        's3://your-bucket-name/prefix/fake_sales_data.csv',
                        's3://your-bucket-name/prefix/outputs/report_1/'
                    ]
                }
            }
        ]
    )
```

**IAM 角色和 VPC 创建**

要在 Lambda 函数中启动 EMR 集群，需要一个 VPC 和 IAM 角色。您可以使用此模式的 “附件” 部分中的 AWS CloudFormation 模板设置 VPC 和 IAM 角色，也可以使用以下链接手动创建它们。 

运行 Lambda 和 Amazon EMR 需要以下 IAM 角色。 

*Lambda 执行角色*

AWS Lambda 函数的[执行角色](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html)授予该函数访问 Amazon Web Services 和资源的权限。

*Amazon EMR 的服务角色*

[Amazon EMR 角色](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role.html)定义了 Amazon EMR 在配置资源和执行非在集群内运行的亚马逊弹性计算云 (Amazon EC2) 实例环境中执行的服务级别任务时允许执行的操作。例如，服务角色用于在集群启动时配置 EC2 实例。

* EC2 实例的服务角色*

[集群 EC2 实例的服务角色](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role-for-ec2.html)（也称为 Amazon EMR 的 EC2 实例配置文件）是一种特殊类型的服务角色，该角色在 EC2 实例启动时分配给 Amazon EMR 集群中的每个实例。在 Apache Hadoop 上运行的应用程序进程代入该角色来获得与其它 Amazon Web Services 交互的权限。

*VPC 和子网创建*

您可以从 VPC 控制台[创建 VPC](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#create-vpc-and-other-resources)。 

## 附件
<a name="attachments-6c999fa7-9550-4929-a5c1-60394142175d"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/6c999fa7-9550-4929-a5c1-60394142175d/attachments/attachment.zip)

# 使用 AWS Glue 将 Apache Cassandra 工作负载迁移到 Amazon Keyspaces
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue"></a>

*Nikolai Kolesnikov、Karthiga Priya Chandran 和 Samir Patel，Amazon Web Services*

## Summary
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-summary"></a>

此模式向您展示了如何在 AWS Glue 上使用将现有 Apache Cassandra 工作负载迁移到亚马逊密钥空间（适用于 Apache Cassandra）。 CQLReplicator 您可以 CQLReplicator 在 AWS Glue 上使用来最大限度地减少将工作负载迁移的复制延迟缩至几分钟。您还将学习如何使用 Amazon Simple Storage Service (Amazon S3)存 储桶来存储迁移所需数据，包括 [Apache Parquet](https://parquet.apache.org/) 文件、配置文件和脚本。此模式假设您的 Cassandra 工作负载托管在虚拟私有云 (VPC EC2) 中的亚马逊弹性计算云 (Amazon) 实例上。

## 先决条件和限制
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-prereqs"></a>

**先决条件**
+ 带源表的 Cassandra 集群
+ Amazon Keyspaces 中的目标表，用于复制工作负载
+ 用于存储包含增量数据更改的中间 Parquet 文件的 S3 存储桶
+ 用于存储作业配置文件和脚本的 S3 存储桶

**限制**
+ CQLReplicator 在 AWS Glue 上，需要一些时间来为 Cassandra 工作负载配置数据处理单元 (DPUs)。Cassandra 集群与 Amazon Keyspaces 中的目标键空间和表之间的复制延迟可能只会持续几分钟。

## 架构
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-architecture"></a>

**源技术堆栈**
+ Apache Cassandra
+ DataStax 服务器
+ scyllaDB

**目标技术堆栈**
+ Amazon Keyspaces

**迁移架构**

下图显示了一个示例架构，其中 Cassandra 集群托管在 EC2 实例上并分布在三个可用区。Cassandra 节点托管在私有子网。

![\[自定义服务角色、Amazon Keyspaces 和 Amazon S3，AWS Glue 连接到节点 VPC。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e08048da-8996-4f2c-b8ed-da49fe9e693b/images/76256ab3-a1e6-4c9e-9c40-dc78f51edf0f.png)


下图显示了如下工作流：

1. 自定义服务角色提供对 Amazon Keyspaces 和 S3 存储桶的访问权限。

1. AWS Glue 作业读取 S3 存储桶中的作业配置和脚本。

1. AWS Glue 作业通过端口 9042 连接以从 Cassandra 集群读取数据。

1. AWS Glue 作业通过端口 9142 连接，将数据写入至 Amazon Keyspaces。

## 工具
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-tools"></a>

**Amazon Web Services 和工具**
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [AWS CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/welcome.html) 是一个基于浏览器的外壳，您可以使用 AWS 命令行界面 (AWS CLI) Line CLI 和一系列预装的开发工具来管理 AWS 服务。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一项完全托管的 ETL 服务，它可帮助您在各种数据存储和数据流之间可靠地对数据进行分类、清理、扩充和移动。
+ [Amazon Keyspaces（Apache Cassandra 兼容）](https://docs.aws.amazon.com/keyspaces/latest/devguide/what-is-keyspaces.html)是一项托管数据库服务，可帮助您在 Amazon Web Services Cloud 中迁移、运行和扩展 Cassandra 工作负载。

**代码**

此模式的代码可在 GitHub [CQLReplicator](https://github.com/aws-samples/cql-replicator/tree/main/glue)存储库中找到。

## 最佳实践
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-best-practices"></a>
+ 要确定迁移所需的 AWS Glue 资源，请预估源 Cassandra 表中的行数。例如，使用 84 GB 的磁盘，每 0.25 DPU（2 vCPUs，4 GB 内存）有 250 K 行。
+ 在运行之前预热 Amazon Keyspaces 表。 CQLReplicator例如，八个 CQLReplicator 图块（AWS Glue 作业） WCUs 每秒最多可以写入 22 K，因此应将目标预热到每秒 25-30 K WCUs 。
+ 要使 AWS Glue 组件之间能够通信，请在安全组中为所有 TCP 端口配置自引用入站规则。
+ 采用增量流量策略，将迁移工作负载分散到不同时间段。

## 操作说明
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-epics"></a>

### 部署 CQLReplicator
<a name="deploy-cqlreplicator"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建目标键空间和表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.html) | 应用程序所有者，AWS 管理员，数据库管理员，应用程序开发人员 | 
| 将 Cassandra 驱动程序配置为连接至 Cassandra。 | 使用以下配置脚本：<pre>Datastax-java-driver {<br />  basic.request.consistency = "LOCAL_QUORUM"<br />  basic.contact-points = ["127.0.0.1:9042"]<br />   advanced.reconnect-on-init = true<br />   basic.load-balancing-policy {<br />        local-datacenter = "datacenter1"<br />}<br />advanced.auth-provider = {<br />       class = PlainTextAuthProvider<br />       username = "user-at-sample"<br />       password = "S@MPLE=PASSWORD="<br />}<br />}</pre>前述脚本使用 Spark Cassandra Connector。有关更多信息，请参阅 [Cassandra](https://docs.datastax.com/en/developer/java-driver/4.17/manual/core/configuration/reference/) 的参考配置。 | 数据库管理员 | 
| 将 Cassandra 驱动程序配置为连接至 Amazon Keyspaces。 | 使用以下配置脚本：<pre>datastax-java-driver {<br />basic {<br />  load-balancing-policy {<br />    local-datacenter = us-west-2<br />        }<br />  contact-points = [<br />            "cassandra.us-west-2.amazonaws.com:9142"<br />        ]<br />  request {<br />  page-size = 2500<br />  timeout = 360 seconds<br />  consistency = LOCAL_QUORUM<br />        }<br />    }<br />advanced {<br /> control-connection {<br />  timeout = 360 seconds<br />        }<br /> session-leak.threshold = 6<br /> connection {<br /> connect-timeout = 360 seconds<br /> init-query-timeout = 360 seconds<br /> warn-on-init-error = false<br />        }<br /> auth-provider = {<br />  class = software.aws.mcs.auth.SigV4AuthProvider<br />  aws-region = us-west-2<br /> }<br /><br /> ssl-engine-factory {<br />  class = DefaultSslEngineFactory<br />        }<br />    }<br />}</pre>前述脚本使用 Spark Cassandra Connector。有关更多信息，请参阅 [Cassandra](https://docs.datastax.com/en/developer/java-driver/4.17/manual/core/configuration/reference/) 的参考配置。 | 数据库管理员 | 
| 为 AWS Glue 作业创建 IAM 角色。 | 用 AWS Glue 创建名为 `glue-cassandra-migration` 的新 AWS 服务角色作为受信任实体。`glue-cassandra-migration` 应提供对 S3 存储桶和 Amazon Keyspaces 的读写访问权限。S3 存储桶包含.jar 文件、Amazon Keyspaces 与 Cassandra 的配置文件，以及中间的 Parquet 文件。例如，其中包含 `AWSGlueServiceRole`、`AmazonS3FullAccess` 和 `AmazonKeyspacesFullAccess` 托管策略。 | AWS DevOps | 
|  CQLReplicator 在 AWS 中下载 CloudShell。 | 运行以下命令，将项目下载到您的主文件夹：<pre>git clone https://github.com/aws-samples/cql-replicator.git<br />cd cql-replicator/glue<br /># Only for AWS CloudShell, the bc package includes bc and dc. Bc is an arbitrary precision numeric processing arithmetic language<br />sudo yum install bc -y</pre> |  | 
| 修改参考配置文件。 | 将 `CassandraConnector.conf` 和 `KeyspacesConnector.conf` 复制到项目文件夹中的 `../glue/conf` 目录。 | AWS DevOps | 
| 启动迁移过程。 | 以下命令初始化 CQLReplicator 环境。初始化包括复制 .jar 构件以及创建 AWS Glue 连接器、S3 存储桶、AWS Glue 作业、`migration` 密钥空间和 `ledger` 表：<pre>cd cql-replicator/glue/bin<br />./cqlreplicator --state init --sg '"sg-1","sg-2"' \ <br />                --subnet "subnet-XXXXXXXXXXXX" \ <br />                --az us-west-2a --region us-west-2 \ <br />                --glue-iam-role glue-cassandra-migration \ <br />                --landing-zone s3://cql-replicator-1234567890-us-west-2<br /></pre>此脚本包含以下参数：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.html) | AWS DevOps | 
| 验证部署。 | 运行上一个命令后，AWS 账户应包含如下内容：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.html) | AWS DevOps | 

### 跑 CQLReplicator
<a name="run-cqlreplicator"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 开始迁移过程。 | 要 CQLReplicator 在 AWS Glue 上操作，您需要使用`--state run`命令和一系列参数。这些参数的具体配置主要取决于您的独特迁移需求。例如，如果您选择复制生存时间（TTL）值和更新，或者将超过 1 MB 的对象卸载到 Amazon S3，则这些设置可能会有所不同。要将工作负载从 Cassandra 集群复制到 Amazon Keyspaces，请运行以下命令：<pre>./cqlreplicator --state run --tiles 8  \<br />                --landing-zone s3://cql-replicator-1234567890-us-west-2 \ <br />                --region us-west-2 \                              <br />                --src-keyspace source_keyspace \ <br />                --src-table source_table \  <br />                --trg-keyspace taget_keyspace \<br />                --writetime-column column_name \<br />                --trg-table target_table --inc-traffic</pre>在 Cassandra 集群中，您的源键空间和表为 `source_keyspace.source_table`。在 Amazon Keyspaces 中，目标键空间和表为 `target_keyspace.target_table`。参数 `--inc-traffic` 有助于防止增量流量因请求量过高而导致 Cassandra 集群和 Amazon Keyspaces 过载。要复制更新，请将 `--writetime-column regular_column_name` 添加到命令行。常规列将用作写入时间戳的来源。 | AWS DevOps | 

### 监控迁移过程
<a name="monitor-the-migration-process"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在历史迁移阶段验证迁移的 Cassandra 行。 | 要获取回填阶段复制的行数，请运行以下命令：<pre>./cqlreplicator --state stats \<br />                --landing-zone s3://cql-replicator-1234567890-us-west-2 \  <br />                --src-keyspace source_keyspace --src-table source_table --region us-west-2</pre> | AWS DevOps | 

### 停止迁移过程
<a name="stop-the-migration-process"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 `cqlreplicator` 命令或 AWS Glue 控制台。 | 要正常停止迁移过程，请运行以下命令：<pre>./cqlreplicator --state request-stop --tiles 8 \                         <br />                --landing-zone s3://cql-replicator-1234567890-us-west-2 \     <br />                --region us-west-2 \                     <br />                --src-keyspace source_keyspace --src-table source_table</pre>要立即停止迁移过程，请使用 AWS Glue 控制台。 | AWS DevOps | 

### 清理
<a name="clean-up"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除已部署的资源。 | 以下命令将删除 AWS Glue 作业、连接器、S3 存储桶和键空间表 `ledger`：<pre>./cqlreplicator --state cleanup --landing-zone s3://cql-replicator-1234567890-us-west-2</pre> | AWS DevOps | 

## 问题排查
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| AWS Glue 作业失败并返回内存不足（OOM）错误。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.html) | 

## 相关资源
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-resources"></a>
+ [CQLReplicator 使用 AWS Glue README.MD](https://github.com/aws-samples/cql-replicator/blob/main/glue/README.MD)
+ [AWS Glue 文档](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html)
+ [Amazon Keyspaces 文档](https://docs.aws.amazon.com/keyspaces/latest/devguide/what-is-keyspaces.html)
+ [阿帕奇·卡桑德拉](https://cassandra.apache.org/_/index.html)

## 附加信息
<a name="migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue-additional"></a>

**迁移注意事项**

您可使用 AWS Glue 将 Cassandra 工作负载迁移到 Amazon Keyspaces，同时在迁移过程中保持您的 Cassandra 源数据库完全正常运行。复制完成后，您可选择将应用程序割接到 Amazon Keyspaces，同时将 Cassandra 集群和 Amazon Keyspaces 之间的复制延迟降至最低（少于几分钟）。为了保持数据一致性，您还可以使用类似的管线将数据从 Amazon Keyspaces 复制回至 Cassandra 集群。

**编写单位计算**

举个例子，假定您打算在一小时内写入 500,000,000，行大小为 1 KiB。您需要的 Amazon Keyspaces 写入单元总数 (WCUs) 是基于以下计算得出的：

`(number of rows/60 mins 60s) 1 WCU per row = (500,000,000/(60*60s) * 1 WCU) = 69,444 WCUs required`

 WCUs 每秒 69,444 是 1 小时的速度，但你可以为开销增加一些缓冲。 例如，`69,444 * 1.10 = 76,388 WCUs` 有 10% 的开销。

**使用 CQL 创建键空间**

要通过使用 CQL 创建键空间，请运行以下命令：

```
CREATE KEYSPACE target_keyspace WITH replication = {'class': 'SingleRegionStrategy'}
CREATE TABLE target_keyspace.target_table ( userid uuid, level text, gameid int, description text, nickname text, zip text, email text, updatetime text, PRIMARY KEY (userid, level, gameid) ) WITH default_time_to_live = 0 AND CUSTOM_PROPERTIES = {'capacity_mode':{ 'throughput_mode':'PROVISIONED', 'write_capacity_units':76388, 'read_capacity_units':3612 }} AND CLUSTERING ORDER BY (level ASC, gameid ASC)
```

# 将 Oracle 商业智能 12c 从本地服务器迁移到 Amazon Web Services Cloud
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers"></a>

*Lanre（Lan-Ray）showunmi 和 Patrick Huang，Amazon Web Services*

## Summary
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-summary"></a>

此模式展示了如何使用 AWS 将 [Oracle 商业智能企业版 12c](https://www.oracle.com/business-analytics/business-intelligence/technologies/bi-enterprise-edition.html) 从本地服务器迁移到 AWS CloudFormation 云。它还介绍了如何使用其他 Amazon Web Services 来实施 Oracle BI 12c 组件，这些组件可提供高可用性、安全性、灵活性和动态扩展能力。

有关将 Oracle BI 12c 迁移到 Amazon Web Services Cloud 相关的最佳实践列表，请参阅此模式的**其他信息**部分。

**注意**  
最佳做法是在将现有 Oracle BI 12c 数据传输到云端之前运行多次测试迁移。这些测试可帮助您微调迁移方法，识别和修复潜在问题，并更准确地估计停机时间需求。

## 先决条件和限制
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 通过 [AWS 虚拟专用网络 (AWS VPN)](https://aws.amazon.com/vpn/) 服务或 [AWS Direct Connect](https://docs.aws.amazon.com/directconnect/latest/UserGuide/Welcome.html) 的本地服务器和 AWS 之间的安全网络连接
+ 适用于您的 Oracle 操作系统、Oracle BI 12c、甲骨文数据库、甲骨文服务器和 Oracle HTTP WebLogic 服务器的软件许可证

**限制**

有关存储大小限制的信息，请参阅 [Amazon Relational Database Service（Amazon RDS）for Oracle](https://aws.amazon.com/rds/oracle/features/) 文档。

**产品版本**
+ Oracle 商业智能企业版 12c
+ 甲骨文 WebLogic 服务器 12c
+ Oracle HTTP 服务器 12c
+ Oracle 数据库 12c（或更高版本）
+ Oracle Java SE 8

## 架构
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-architecture"></a>

下图显示了在 Amazon Web Services Cloud 中运行 Oracle BI 12c 组件的示例架构：

![\[在 AWS 云中运行 Oracle BI 12c 组件的示例架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/8bb72df1-7546-4208-bc70-5789767e3600/images/aae8f8f3-8125-4868-a8e5-eac1cc42812f.png)


 

此图显示以下架构：

1. Amazon Route 53 提供域名服务 (DNS) 配置。

1. 弹性负载均衡（ELB）可分发网络流量，以提高 Oracle BI 12c 组件在多个可用区中的可扩展性和可用性。

1. 亚马逊弹性计算云 (亚马逊 EC2) Auto Scaling 组在多个可用区托管 Oracle HTTP 服务器、Weblogic 管理服务器和托管 BI 服务器。

1. 适用于 Oracle 数据库的 Amazon Relational Database Service（Amazon RDS）跨多个可用区存储 BI 服务器元数据。

1. Amazon Elastic File System（Amazon EFS）安装在每个 Oracle BI 12c 组件上，用于共享文件存储。

**技术堆栈**
+ Amazon Elastic Block Store（Amazon EBS）
+ 亚马逊弹性计算云（亚马逊 EC2）
+ Amazon Elastic File System (Amazon EFS)
+ Amazon RDS for Oracle
+ AWS Certificate Manager (ACM)
+ 弹性负载均衡（ELB）
+ Oracle BI 12c
+ 甲骨文 WebLogic 服务器 12c
+ Oracle HTTP Server (OHS)

## 工具
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-tools"></a>
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可帮助您设置 AWS 资源，快速一致地配置这些资源，并在 AWS 账户和区域的整个生命周期中对其进行管理。
+ [AWS Certifice Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) 可帮助您创建、存储和续订 X.509 公有和私有 SSL/TLS X.509 证书和密钥，以保护您的 AWS 网站和应用程序。
+ [AWS Database Migration Service (AWS DMS)](https://docs.aws.amazon.com/dms/latest/userguide/Welcome.html) 可帮助您将数据存储迁移到 Amazon Web Services Cloud，或者在云和本地设置的组合之间迁移。
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/ec2/?id=docs_gateway) 在 AWS 云中提供可扩展的计算容量。您可以根据需要启动任意数量的虚拟服务器，并快速扩展或缩减它们。
+ [Amazon A EC2 uto Scaling](https://aws.amazon.com/ec2/autoscaling/) 可帮助您保持应用程序的可用性，并允许您根据自己定义的条件自动添加或删除亚马逊 EC2 实例。 
+ [Amazon Elastic File System（Amazon EFS）](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html)可帮助您在 Amazon Web Services Cloud 中创建和配置共享文件系统。
+ [弹性负载均衡](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)将传入的应用程序或网络流量分发到多个目标。例如，您可以跨亚马逊弹性计算云 (Amazon EC2) 实例、容器以及一个或多个可用区中的 IP 地址分配流量。
+ [Amazon Relational Database Service（Amazon RDS）](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html)可帮助您在 AWS 云端设置、操作和扩展关系数据库。
+ [Amazon Simple Storage Service(Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [Amazon Virtual Private Cloud (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) 可帮助您将 AWS 资源启动到您定义的虚拟网络中。此虚拟网络类似于您在自己的数据中心内运行的传统网络，具有使用 AWS 可扩展基础设施的优势。
+ [Oracle 数据泵](https://docs.oracle.com/cd/B19306_01/server.102/b14215/dp_overview.htm)可帮助您将数据和元数据从一个数据库高速移动至另一个数据库。
+ [Oracle 融合中间件](https://www.oracle.com/middleware/technologies/business-intelligence-v12214-downloads.html)是一套用于身份管理、协作和商业智能报告的应用程序开发工具和集成解决方案。
+ [Oracle GoldenGate](https://www.oracle.com/integration/goldengate/#:~:text=OCI%20GoldenGate%20is%20a%20real,in%20the%20Oracle%20Cloud%20Infrastructure.) 可帮助您在 Oracle 云基础设施中设计、运行、编排和监控数据复制和流数据处理解决方案。
+ [Oracle WebLogic 脚本工具 (WLST)](https://docs.oracle.com/middleware/12213/cross/wlsttasks.htm) 提供了一个命令行界面，可帮助您水平扩展集群。 WebLogic 

## 操作说明
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-epics"></a>

### 评测源环境
<a name="assess-the-source-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 收集软件库存信息。 | 识别源技术堆栈中每个软件组件的版本和补丁级别，包括以下内容：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 迁移架构师、解决方案架构师、应用程序所有者、Oracle BI 管理员 | 
| 收集计算和存储库存信息。 | 在源环境中，查看以下各项的当前和历史使用率指标：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html)请务必考虑使用量的历史峰值。 | 迁移架构师、解决方案架构师、应用程序所有者、Oracle BI 管理员、系统管理员 | 
| 收集有关源环境架构及其要求的信息。 | 全面了解源环境的架构及其要求，包括以下方面的知识：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 迁移架构师、解决方案架构师、应用程序所有者、Oracle BI 管理员 | 
| 识别 Java 数据库连接 (JDBC) 数据来源。 | 收集有关源环境的 JDBC 数据来源及其使用的每个数据库引擎的驱动程序的信息。 | 迁移架构师、应用程序所有者、Oracle BI 管理员、数据库工程师或管理员 | 
| 收集有关特定环境设置的信息。 | 收集有关特定于源环境的设置和配置的信息，包括：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 迁移架构师、解决方案架构师、应用程序所有者、Oracle BI 管理员 | 
| 确定对其他应用程序的任何依赖项。 | 收集有关源环境中各项集成的信息，这些集成使用其他应用程序创建依赖项。请务必确定任何轻型目录访问协议（LDAP）集成和其他联网要求。 | 迁移架构师、解决方案架构师、应用程序所有者、Oracle BI 管理员 | 

### 设计目标环境
<a name="design-your-target-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建高级设计文档。 | 创建目标架构设计文档。请务必使用在评测源环境时收集的信息来为设计文档提供信息。 | 解决方案架构师、应用程序架构师、数据库工程师、迁移架构师 | 
| 获得设计文档的批准。 | 与利益相关者一起审查设计文件并获得所需批准。 | 应用程序或服务所有者、解决方案架构师、应用程序架构师 | 

### 部署基础设施
<a name="deploy-the-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在中准备基础架构代码 CloudFormation。 | 创建 CloudFormation 模板以在 AWS 云中配置您的 Oracle BI 12c 基础设施。有关更多信息，请参阅 [AWS * CloudFormation 用户指南中的使用 AWS CloudFormation * 模板](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)。最佳做法是为每个 Oracle BI 12c 层创建模块化 CloudFormation 模板，而不是为所有资源创建一个大型模板。有关 CloudFormation 最佳实践的更多信息，请参阅 AWS 博客 CloudFormation上的 [AWS 自动部署时的 8 个最佳实践](https://aws.amazon.com/blogs/infrastructure-and-automation/best-practices-automating-deployments-with-aws-cloudformation/)。 | 云基础设施架构师、解决方案架构师、应用程序架构师 | 
| 下载所需软件。 | DDownload 以下软件以及来自 [Oracle 网站](https://www.oracle.com/)的所需版本和补丁：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 迁移架构师、数据库工程师、应用程序架构师 | 
| 准备安装脚本。 | 创建运行静默安装的软件安装脚本。这些脚本简化了部署自动化。有关更多信息，请参阅 Oracle Support 网站上的 [OBIEE 12c：如何执行静默安装？](https://support.oracle.com/knowledge/Enterprise%20Performance%20Management%20and%20Business%20Intelligence/2267490_1.html)。您需要 Oracle Support 账户才能查看文档。 | 迁移架构师、数据库工程师、应用程序架构师 | 
| 为 Web 和应用程序层创建由 Amazon EBS 提供支持的 Linux AMI。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 迁移架构师、数据库工程师、应用程序架构师 | 
| 使用启动您的 AWS 基础设施 CloudFormation。 | 使用您创建的 CloudFormation 模板，在模块中部署 Oracle BI 12c Web 和应用程序层。有关说明，请参阅 [AWS * CloudFormation 用户指南 CloudFormation中的 AWS* 入门](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/GettingStarted.html)。 | 云基础设施架构师、解决方案架构师、应用程序架构师 | 

### 使用全新安装将 Oracle BI 12c 迁移到 AWS
<a name="migrate-oracle-bi-12c-to-aws-by-using-a-fresh-installation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 准备所需软件。 | 将所需的软件暂存到可供 Amazon EC2 实例访问的位置。例如，您可以将软件暂存到 Amazon S3 或其他可供您的 Web 和应用程序服务器访问的 Amazon EC2 实例中。 | 迁移架构师、Oracle BI 架构师、云基础设施架构师、解决方案架构师、应用程序架构师 | 
| 为安装 Oracle BI 12c 准备存储库数据库。 | 通过对新的 [Amazon RDS for Oracle](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Oracle.html) 数据库实例运行 [Oracle 存储库创建实用程序 (RCU)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Oracle.Resources.RCU.html#Oracle.Resources.RCU.Installing) 来创建 Oracle BI 12c 架构。 | 云基础设施架构师、解决方案架构师、应用程序架构师、迁移架构师、Oracle BI 架构师 | 
| 安装 Oracle 融合中间件 12c 和 Oracle BI 12c。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 迁移架构师、Oracle BI 架构师 | 
| 为 Oracle BI 12c 配置你的 Oracle WebLogic 服务器域。 | 将 Oracle BI 12c 域配置为非集群部署。有关更多信息，请参阅*适用于 Oracle 商业智能的 Oracle 融合中间件企业部署指南*中的[配置 BI 域](https://docs.oracle.com/middleware/bi12214/lcm/BIEDG/GUID-FD80C4C4-A2E9-4190-8B6A-7AD659D8FBE2.htm#BIEDG-GUID-D4FC2F0A-88B0-453C-BF14-17D365018252)。 | 迁移架构师、Oracle BI 架构师 | 
| 对 Oracle BI 12c 进行水平横向扩展。 | 将单个节点水平横向扩展到所需节点数。有关更多信息，请参阅*适用于 Oracle 商业智能的 Oracle 融合中间件企业部署指南*中的[横向扩展 Oracle 商业智能](https://docs.oracle.com/middleware/bi12214/lcm/BIEDG/GUID-B7BEA45C-A8C0-4591-B748-FC35C587DAE0.htm#BIEDG-GUID-B7BEA45C-A8C0-4591-B748-FC35C587DAE0)。 | 迁移架构师、Oracle BI 架构师 | 
| 安装 Oracle HTTP 服务器 12c。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 迁移架构师、Oracle BI 架构师 | 
| 为 SSL 终止配置负载均衡器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 云基础设施架构师、迁移架构师 | 
| 将商业智能元数据构件迁移到 AWS。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 迁移架构师、Oracle BI 架构师 | 
| 执行迁移后的任务。 | 导入 BAR 文件后，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | 迁移架构师、Oracle BI 架构师 | 

### 测试新环境
<a name="test-the-new-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试新的 Oracle BI 12c 环境。 | 在新的 Oracle BI 12c 环境上进行 end-to-end测试。尽可能多地使用自动化。测试活动示例包括以下内容：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html)根据需要进行其他测试和验证。 | 迁移架构师、解决方案架构师、应用程序所有者、Oracle BI 管理员 | 

### 割接至新环境
<a name="cut-over-to-the-new-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 断开流向本地 Oracle BI 12c 环境的流量。 | 在指定的割接窗口中，停止所有流向本地 Oracle BI 12c 环境的流量。 | 迁移架构师、解决方案架构师、应用程序所有者、Oracle BI 管理员 | 
| 将新的 Oracle BI 12c 存储库数据库与源数据库重新同步。 | 将 Amazon RDS Oracle Oracle BI 12c 存储库数据库与本地数据库重新同步。要同步数据库，您可以使用 [Oracle 数据泵刷新](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Oracle.Procedural.Importing.DataPump.html)或 [AWS DMS 更改数据捕获（CDC）](https://aws.amazon.com/blogs/database/migrating-oracle-databases-with-near-zero-downtime-using-aws-dms/)。 | Oracle BI 管理员、数据库工程师/管理员 | 
| 将您的 Oracle BI 12c 切换 URLs 为指向新的 AWS 环境。 | 更新内部 DNS 服务器 URLs 上的 Oracle BI 12c，使其指向新安装的 AWS。 | 迁移架构师、解决方案架构师、应用程序所有者、Oracle BI 管理员 | 
| 监控新环境。 | 使用以下任一工具监控新的 Oracle BI 12c 环境：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers.html) | Oracle BI 管理员、数据库工程师/管理员、应用程序管理员 | 
| 获得项目签核。 | 与利益相关者一起审查测试结果，并获得完成迁移所需批准。 | 应用程序所有者、服务所有者、云基础设施架构师、迁移架构师、Oracle BI 架构师 | 

## 相关资源
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-resources"></a>
+ [在 RDS for Oracle 上使用 Oracle 存储库创建实用程序](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Oracle.Resources.RCU.html)（*Amazon RDS 用户指南*）
+ [Amazon RDS 上的 Oracle](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Oracle.html)（*Amazon RDS 用户指南*）
+ [AWS 上 WebLogic 的 Oracle Server 12c（A](https://d1.awsstatic.com/whitepapers/Oracle-WebLogic-12c-on-AWS.pdf) WS 白皮书）
+ [部署 Oracle 商业智能以实现高可用性](https://docs.oracle.com/middleware/1221/biee/BIESG/highavail.htm#BIESG1584)（Oracle 帮助中心）
+ [Oracle 商业智能应用程序档案（BAR）文件](https://docs.oracle.com/middleware/bi12214/biee/BIESG/GUID-7FCD90A3-E005-49BF-902F-30FBF9B41B07.htm#BIESG2889)（Oracle 帮助中心）
+ [如何在环境之间迁移 OBI 12c](https://support.oracle.com/knowledge/Enterprise%20Performance%20Management%20and%20Business%20Intelligence/2203360_1.html)（Oracle Support） 

## 附加信息
<a name="migrate-oracle-business-intelligence-12c-to-the-aws-cloud-from-on-premises-servers-additional"></a>

以下是与将 Oracle BI 12c 迁移到 Amazon Web Services Cloud 相关的最佳实践列表。

**存储库数据库**

在 Amazon RDS for Oracle 实例上托管 Oracle BI 12c 数据库架构是一种最佳实践。此实例类型提供经济实惠、且可调整的容量，同时自动执行管理任务，例如硬件预调配、数据库设置、修补和备份。

有关更多信息，请参阅 *Amazon RDS 用户指南*中的[在 RDS for Oracle 上使用 Oracle 存储库创建实用程序](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Oracle.Resources.RCU.html)。

**Web 和应用程序层**

[内存优化的 Amazon EC2 实例](https://aws.amazon.com/ec2/instance-types/)通常非常适合 Oracle BI 12c 服务器。无论您选择哪种实例类型，务必确保您预调配的实例满足系统的内存使用要求。此外，请确保根据您的 Amazon EC2 实例的可用内存[配置足够的 J WebLogic ava 虚拟机 (JVM) 堆大小](https://docs.oracle.com/cd/E49933_01/server.770/es_install/src/tins_postinstall_jvm_heap.html#:~:text=The%20default%20JVM%20heap%20size%20for%20WebLogic%20is%203GB.,file%20for%20Linux%20or%20setDomainEnv.)。

**本地存储**

I/O 在 Oracle BI 12c 应用程序的整体性能中起着重要作用。Amazon Elastic Block Store（Amazon EBS）提供针对不同工作负载模式进行优化的不同存储类别。请务必选择适合用例的 Amazon EBS 卷类型。

有关 EBS 卷类型的更多信息，请参阅 Amazon EBS 文档中的 [Amazon EBS 功能](https://aws.amazon.com/ebs/features/)。

**共享存储**

集群化的 Oracle BI 12c 域需要共享存储空间来存储以下资源：
+ 配置文件
+ Oracle BI 12c 单例数据目录 (SDD)
+ Oracle 全局缓存
+ Oracle BI 计划程序脚本
+ 甲骨文 WebLogic 服务器二进制文件

您可以使用 [Amazon EFS](https://aws.amazon.com/efs/) 来满足这一共享存储需求，它提供了可扩展、完全托管的弹性网络文件系统 (NFS) 文件系统。

*微调共享存储性能*

Amazon EFS 有两种[吞吐量模式](https://docs.aws.amazon.com/efs/latest/ug/performance.html#throughput-modes)：**预调配**和**突增**。该服务还有两种[性能模式](https://docs.aws.amazon.com/efs/latest/ug/performance.html#performancemodes)：**通用模式**和**最大 I/O 模式**。

要微调性能，请首先在**通用**性能模式和**预调配**吞吐量模式下测试工作负载。进行这些测试将帮助您确定这些基准模式是否足以满足所需服务级别。

有关更多信息，请参阅 [Amazon EFS 用户指南](https://docs.aws.amazon.com/efs/latest/ug/performance.html)中的 *Amazon EFS 性能*。

**可用性和灾难恢复**

最佳做法是跨多个可用区部署 Oracle BI 12c 组件，以便在可用区出现故障时保护这些资源。以下是 Amazon Web Services Cloud 中托管的特定 Oracle BI 12c 资源的可用性和灾难恢复最佳实践列表：
+ **Oracle BI 12c 存储库数据库**：将多可用区 Amazon RDS 数据库实例部署到Oracle BI 12c 存储库数据库。在多可用区部署中，Amazon RDS 会自动在不同可用区中预调配和维护一个同步备用副本。在计划内的系统维护期间，跨可用区运行 Oracle BI 12c 存储库数据库实例可以提高可用性，并帮助保护数据库以防数据库实例发生故障和可用区中断。
+ **Oracle BI 12c 托管服务器**：为了实现容错能力，最佳做法是在配置为跨多个可用区域的 Amazon A EC2 uto Scaling 组中的托管服务器上部署 Oracle BI 12c 系统组件。Auto Scaling 会根据[亚马逊运行 EC2 状况检查](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-health-checks.html)替换故障实例。如果可用区出现故障，Oracle HTTP 服务器会继续将流量引导到正常运行的可用区内的托管服务器。然后，自动扩缩会启动实例以满足主机数量要求。建议激活 HTTP 会话状态复制，以帮助确保现有会话顺畅地失效转移到正常运行的托管服务器。
+ **Oracle BI 12c 管理服务器：**为确保您的管理服务器具有高可用性，请将其托管在配置为跨多个可用区域的 Amazon A EC2 uto Scaling 组中。然后，将组的最小和最大大小设置为 **1**。如果可用区出现故障，Amazon A EC2 uto Scaling 会在备用可用区中启动一台替换的管理服务器。要恢复同一可用区内任何出现故障的底层主机，您可以激活 [Amazon A EC2 uto Recovery](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-recover.html)。
+ **Oracle Web 层服务器：**最佳做法是将您的 Oracle HTTP 服务器与 Oracle WebLogic 服务器域关联起来。为了获得高可用性，请在配置为跨越多个可用区域的 Amazon A EC2 uto Scaling 组中部署 Oracle HTTP 服务器。然后，将服务器放在 ELB 弹性负载均衡器后面。要提供针对主机故障的额外保护，您可以激活 Amazon A EC2 uto Recovery。

**可扩展性**

Amazon Web Services Cloud 的弹性可帮助您根据工作负载要求水平或垂直扩展应用程序。

*垂直扩展*

要垂直扩展您的应用程序，您可以更改运行 Oracle BI 12c 组件的 Amazon EC2 实例的大小和类型。您无需在部署开始时过度配置实例，也无需产生不必要的成本。 

*横向扩展*

Amazon A EC2 uto Scaling 可根据工作负载要求自动添加或删除托管服务器，从而帮助您水平扩展应用程序。

**注意**  
使用 Amazon A EC2 uto Scaling 进行横向扩展需要脚本编写技能和全面的测试才能实施。

**备份和恢复**

以下是 Amazon Web Services Cloud 中托管的特定 Oracle BI 12c 资源的备用和恢复最佳实践列表：
+ **Oracle 商业智能元数据存储库：**Amazon RDS 会自动创建并保存数据库实例的备份。这些备份会保留您指定的时间。请务必根据数据保护要求配置 Amazon RDS 备份持续时间和保留期设置。有关更多信息，请参阅 [Amazon RDS 备份和恢复](https://aws.amazon.com/rds/features/backup/)。
+ **托管服务器、管理服务器和 Web 层服务器：**确保根据数据保护和保留要求配置 [Amazon EBS 快照](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html)。
+ **共享存储：**您可以使用 [AWS Backup](https://docs.aws.amazon.com/efs/latest/ug/awsbackup.html) 管理存储在 Amazon EFS 中的文件的备份和恢复。还可以部署 AWS Backup 服务来集中管理其他服务的备份和恢复，包括亚马逊 EC2、亚马逊 EBS 和 Amazon RDS。有关更多信息，请参阅[什么是 AWS Backup？](https://docs.aws.amazon.com/aws-backup/latest/devguide/whatisbackup.html) 在 *AWS Backup 开发人员指南*中。

**安全与合规**

以下是可以帮助您保护 Amazon Web Services Cloud 中的 Oracle BI 12c 应用程序的安全最佳实践和 Amazon Web Services 列表：
+ **静态加密：**Amazon RDS、Amazon EFS 和 Amazon EBS 都支持行业标准加密算法。您可以使用 [AWS Key Management Service（AWS KMS）](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html)来创建和管理加密密钥，并控制其在 Amazon Web Services 和应用程序中的使用。您还可以在托管 Oracle BI 12c 存储库数据库的 Amazon RDS for Oracle 数据库实例上配置 [Oracle 透明数据加密 (TDE)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.Oracle.Options.AdvSecurity.html)。
+ **传输中的加密：**最佳做法是激活 SSL 或 TLS 协议，以保护在 Oracle BI 12c 安装的各个层之间的传输中数据。您可以使用 [AWS Certificate Manager（ACM）](https://aws.amazon.com/certificate-manager/)为 Oracle BI 12c 资源预调配、管理和部署公有和私有 SSL 和 TLS 证书。
+ **网络安全**：确保将 Oracle BI 12c 资源部署在针对用例配置了相应访问控制的 Amazon VPC 中。配置您的安全组，以筛选来自正在运行您的安装的 Amazon EC2 实例的入站和出站流量。此外，请确保配置[网络访问控制列表 (NACLs)](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html)，以根据定义的规则允许或拒绝流量。
+ **监控和记录**：您可以使用 [AWS CloudTrail](https://aws.amazon.com/cloudtrail/) 来跟踪对您的 AWS 基础设施（包括 Oracle BI 12c 资源）的 API 调用。在跟踪基础设施变更或进行安全分析时，此功能非常有用。您还可以使用 [Amazon CloudWatch](https://aws.amazon.com/cloudwatch/) 查看操作数据，这些数据可以让您深入了解 Oracle BI 12c 应用程序的性能和运行状况。您也可以配置警报并根据这些警报采取自动操作。Amazon RDS 提供了其他监控工具，包括[增强型监控](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Monitoring.OS.html)和[性能详情](https://aws.amazon.com/rds/performance-insights/)。

# 将 ELK 堆栈迁移至 Elastic Cloud on AWS
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws"></a>

*Battulga Purevragchaa 和 Antony Prasad Thevaraj，Amazon Web Services*

*uday reddy，无*

## Summary
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-summary"></a>

[Elastic](https://www.elastic.co/) 多年来一直提供服务，其用户和客户通常在本地自行管理 Elastic。[Elastic Cloud](https://www.elastic.co/cloud) 是一种托管的 [Elasticsearch 服务](https://www.elastic.co/elasticsearch/service)，提供了一种使用 Elastic Stack (ELK Stack) 的方式，以及[企业搜索](https://www.elastic.co/enterprise-search)、[可观测性](https://www.elastic.co/observability)和[安全](https://www.elastic.co/security)的解决方案。您可以使用日志、指标、APM（应用程序性能监控）和 SIEM（安全信息和事件管理）等应用程序访问 Elastic 解决方案。您可以使用机器学习、索引生命周期管理、Kibana Lens（用于拖放可视化）等集成功能。

当你从自我管理的 Elasticsearch 迁移至 Elasticsearch 时，Elasticsearch 服务会处理以下几点：
+ 配置和管理基础架构
+ 创建和管理 Elasticsearch 集群
+ 向上和向下扩展集群
+ 升级、修补以及拍摄快照

这使您有更多时间专注解决其他挑战。

此模式定义了如何在 Amazon Web Services (AWS) 上将本地 Elasticsearch 7.13 迁移至 Elastic Cloud on Amazon Web Services (AWS)。其他版本可能需要对此模式中描述的过程稍作修改。有关更多信息，请您联系 Elastic 代表。

## 先决条件和限制
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-prereqs"></a>

**先决条件**
+ 具有访问[Amazon Simple Storage Service](https://aws.amazon.com/s3/) (Amazon S3)以获取快照的有效的 [Amazon Web Services account](https://aws.amazon.com/account/)
+ 一个安全、带宽足够高的[私有链接](https://docs.aws.amazon.com/vpc/latest/userguide/vpn-connections.html)，用于将快照数据文件复制至 Amazon S3
+ [Amazon S3 Transfer Acceleration](https://aws.amazon.com/s3/transfer-acceleration/)
+ [Elastic Snapshot 策略](https://www.elastic.co/guide/en/elasticsearch/reference/7.10/getting-started-snapshot-lifecycle-management.html)，确保定期将数据摄取存档到足够大的本地数据存储或远程存储 (Amazon S3)

开始迁移之前，您必须了解本地快照的大小以及随附索引的[生命周期策略](https://www.elastic.co/guide/en/elasticsearch/reference/current/index-lifecycle-management.html)。有关更多信息，[请联系 Elastic](https://www.elastic.co/contact)。

**角色与技能**

迁移过程还需要下表中描述的角色和专长。


| 
| 
|  角色 | 专业知识 | 责任 | 
| --- |--- |--- |
| App support | 熟悉本地部署的 Elastic Cloud 和 Elastic | 所有 Elastic 相关任务 | 
| 系统管理员或 数据库管理员 | 深入了解本地 Elastic 环境及配置 | 能够预配置存储空间、安装和使用 AWS 命令行界面（AWS CLI），并识别在本地提供 Elastic 的所有数据来源 | 
| 网络管理员 | 了解本地与 AWS 的网络连接、安全以及性能 | 在了解连接带宽的前提下，建立从本地至 Amazon S3 的网络链接 | 

**限制**
+ Elastic Cloud 上的 Elasticsearch 仅在[支持的 AWS 区域](https://www.elastic.co/guide/en/cloud/current/ec-regions-templates-instances.html#ec-aws_regions) 可用。

**产品版本**
+ Elasticsearch 7.13

## 架构
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-architecture"></a>

**源技术堆栈**

本地 Elasticsearch 7.13 或更高版本：
+ 集群快照
+ 索引快照
+ [Beats](https://www.elastic.co/beats/) 配置

**源技术架构**

下图显示了具有不同摄取方法、节点类型以及 Kibana 的典型本地架构。不同的节点类型反映了 Elasticsearch 集群、身份验证以及可视化角色。

![\[包括 Beats、Logstash、Elasticsearch 和 Kibana 的八步流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/23d1b437-22ff-420e-80ac-834f1116d234/images/937c4d22-429f-4673-86df-ae491d68389c.png)


1. 从 Beats 摄取至 Logstash

1. 从 Beats 摄取至 Apache Kafka 消息队列

1. 从 Filebeat 摄取至 Logstash

1. 从 Apache Kafka 消息队列摄取至 Logstash

1. 从 Logstash 摄取至 Elasticsearch 集群

1. Elasticsearch 集群

1. 身份验证以及通知节点

1. Kibana 和 blob 节点

**目标技术堆栈**

Elastic Cloud 通过跨集群复制功能部署到您在多个 AWS 区域的软件即服务（SaaS）账户。
+ 集群快照
+ 索引快照
+ Beats 配置
+ Elastic Cloud
+ Network Load Balancer
+ Amazon Route 53
+ Amazon S3

**目标架构**

![\[Route 53 端点将流量路由到两个不同区域的多可用区环境。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/23d1b437-22ff-420e-80ac-834f1116d234/images/16cbac49-0adb-4469-b546-ae4b1ca35357.png)


 

托管 Elastic Cloud 基础架构是：
+ 高度可用，存在于多个[可用区](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/)和多个 AWS 区域。
+ 由于数据（索引和快照）是使用 Elastic Cloud [跨集群复制 (CCR) ](https://www.elastic.co/guide/en/elasticsearch/reference/7.14/xpack-ccr.html)，因此可以容忍区域故障
+ 存档，因为快照存档至 [Amazon S3](https://aws.amazon.com/s3/?p=pm&c=s3&z=4)
+ 通过[网络负载均衡器](https://aws.amazon.com/elasticloadbalancing/network-load-balancer/)和 [Route 53](https://aws.amazon.com/route53/) 的组合实现分区容错性
+ 源自（但不限于）[Elastic APM](https://www.elastic.co/apm/)、[Beats](https://www.elastic.co/beats/)、[Logstash](https://www.elastic.co/guide/en/logstash/current/index.html) 的数据摄取

**高级迁移步骤**

Elastic 开发了自己的规范性方法，用于将本地 Elastic Cluster 迁移至 Elastic Cloud。Elastic 方法与 AWS 迁移指南和最佳实践（[架构完善的框架](https://aws.amazon.com/architecture/well-architected/?wa-lens-whitepapers.sort-by=item.additionalFields.sortDate&wa-lens-whitepapers.sort-order=desc)和 [AWS 迁移加速计划](https://aws.amazon.com/migration-acceleration-program/) (MAP)）直接一致并互为补充。通常，三个 AWS 迁移阶段如下：
+ 评测
+ 动员
+ 迁移与现代化

Elastic 遵循类似迁移阶段，术语互补：
+ 启动
+ 规划
+ 实施
+ 交付
+ Close

Elastic 使用 Elastic 实施方法促进项目成果交付。这在设计上具有包容性，可确保 Elastic、咨询团队和客户团队能清晰地协同工作，共同实现预期成果。

Elastic 方法在实施阶段将传统瀑布项目分阶段与 Scrum 相结合。技术需求的配置以协作方式迭代交付，同时最大限度降低风险。

![\[该图介绍了 Elastic 实施方法的五个阶段。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/23d1b437-22ff-420e-80ac-834f1116d234/images/b041c61d-980e-49a0-a721-791c20edde64.png)


 

## 工具
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-tools"></a>

**Amazon Web Services**
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一项高度可用且可扩展的域名系统（DNS）Web 服务。您可以使用 Route 53 以任意组合执行三个主要功能：域注册、DNS 路由和运行状况检查。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一项对象存储服务。您可以通过 Amazon S3 随时在 Web 上的任何位置存储和检索的任意大小的数据。此模式使用 S3 存储桶和 [Amazon S3 Transfer Acceleration](https://docs.aws.amazon.com/AmazonS3/latest/userguide/transfer-acceleration-examples.html)。
+ [Elastic L](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) oad Balancing — Elastic Load Balancing 会自动将您的传入流量分配到一个或多个可用区的多个目标，例如 EC2 实例、容器和 IP 地址。

**其他工具**
+ [Beats](https://www.elastic.co/beats/) – Beats 发布来自 Logstash 或 Elasticsear
+ [Elastic Cloud](https://www.elastic.co/cloud/) – Elastic Cloud 是一项用于托管 Elasticsearch 的托管服务。
+ [Elasticsearch](https://www.elastic.co/elasticsearch/) – Elasticsearch 是一个搜索和分析引擎，它使用 Elastic Stack 集中存储您的数据，以便进行大规模的搜索和分析。此模式还使用快照创建与跨集群复制。
+ [Logstash](https://www.elastic.co/logstash/) — Logstash 是一项服务器端数据处理管道，它从多个来源摄取数据，对其进行转换，然后将其发送到您的数据存储。

## 操作说明
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-epics"></a>

### 准备迁移
<a name="prepare-the-migration"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 识别可运行本地 Elastic 解决方案的服务器。 | 确认可支持弹性迁移。 | 应用程序所有者 | 
| 了解本地的服务器配置。 | 要了解成功驱动本地工作负载所需服务器配置，请查找当前使用的服务器硬件占用空间、网络配置和存储特性 | App Support | 
| 收集用户和应用程序的账户信息。 | 识别本地 Elastic 环境使用的用户名以及应用程序名称。 | 系统管理员，App support | 
| 记录 Beats 以及数据采集器配置。 | 若要记录配置，请查看现有的数据来源和接收器。有关更多信息，请参阅 [Elastic 文档](https://www.elastic.co/guide/en/elasticsearch/reference/current/ingest.html)。 | App support | 
| 确定数据的速度与数量。 | 为集群处理数据量设定基准。 | 系统管理员，App support | 
| 记录 RPO 与 RTO 方案。 | 记录中断和服务级别协议方面的恢复点目标 (RPO) 和恢复时间目标 (RTO) 情景 (SLAs)。 | 应用程序所有者、系统管理员、应用程序支持 | 
| 确定最佳快照生命周期设置。 | 定义在迁移*期间和之后*，需要使用 Elastic 快照保护数据的频率。 | 应用程序所有者、系统管理员、应用程序支持 | 
| 定义迁移后的性能预计。 | 生成有关当前和预期屏幕刷新、查询运行时以及用户界面行为的指标。 | 系统管理员，App support | 
| 记录互联网接入传输、带宽以及可用性要求。 | 确定将快照复制到 Amazon S3 的互联网连接的速度、延迟以及弹性。 | 网络管理员 | 
| 记录 Elastic 本地运行时系统的当前成本。 | 确保 AWS 目标环境的规模设计高性能且具有成本效益。 | 数据库管理员、系统管理员、App support | 
| 确定身份验证以及授权需求。 | Elastic Stack 安全功能提供了内置领域，例如 Lightweight Directory Access Protocol (LDAP)、Security Assertion Markup Language (SAML) 和 OpenID Connect (OIDC). | 数据库管理员、系统管理员、App support | 
| 根据地理位置了解具体监管要求。 | 确保根据您的要求和任何相关的国家要求，对数据进行导出和加密。 | 数据库管理员、系统管理员、App support | 

### 实施迁移
<a name="implement-the-migration"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 Amazon S3 准备暂存区。 | 若要在 Amazon S3 上接收快照，[请创建一个 S3 存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)和一个具有对新创建存储桶具有完全访问权限的临时 AWS Identity and Access Management (IAM) 角色。有关更多信息，请参阅[创建向 IAM 用户委派权限的角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html)。使用 AWS Security Token Service [请求临时安全凭证](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html)。确保访问密钥 ID、秘密访问密钥和会话令牌安全。在存储桶上启用 [Amazon S3 Transfer Acceleration](https://docs.aws.amazon.com/AmazonS3/latest/userguide/transfer-acceleration-examples.html)。 | AWS 管理员 | 
| 在本地安装 AWS CLI 和Amazon S3 插件。 | 在每个 Elasticsearch 节点上运行以下命令。<pre>sudo bin/elasticsearch-plugin install repository-s3</pre>然后重新启动该节点。 | AWS 管理员 | 
| 配置 Amazon S3 客户端的访问权限。 | 通过运行以下命令，添加之前创建的密钥。<pre>elasticsearch-keystore add s3.client.default.access_key</pre><pre>elasticsearch-keystore add s3.client.default.secret_key</pre><pre>elasticsearch-keystore add s3.client.default.session_token</pre> | AWS 管理员 | 
| 为 Elastic 数据注册快照存储库 | 使用 [Kibana Dev Tools](https://www.elastic.co/guide/en/kibana/current/console-kibana.html) 告诉本地集群要写入哪个远程 S3 存储桶。 | AWS 管理员 | 
| 配置快照策略。 | 要配置快照生命周期管理，请在 Kibana **策略**选项卡选择 **SLM 策略**，然后定义应包含哪些时间、数据流或索引以及要使用的名称。配置频繁拍摄快照策略。快照是增量，可有效利用存储空间。与准备情况评测决定相匹配。策略还可指定[保留策略](https://www.elastic.co/guide/en/elasticsearch/reference/current/slm-retention.html)，并在不再需要快照时自动删除它们。 | App support | 
| 验证快照是否有效。 | 在 Kibana 开发人员工具，运行以下命令。<pre>GET _snapshot/<your_repo_name>/_all</pre> | AWS 管理员，App support  | 
| 在 Elastic Cloud 上部署新集群。 | [登录 Elastic](https://cloud.elastic.co/login?redirectTo=%2Fhome)，根据准备情况评测中的业务调查发现，选择“可观测性、搜索性或安全性”集群。 | AWS 管理员，App support | 
| 设置集群密钥存储访问权限。 | 新集群需访问用于存储快照的 S3 存储桶。在 Elasticsearch Service Console 上，选择**安全**，然后输入您之前创建的访问和私有 IAM 密钥。 | AWS 管理员 | 
| 将 Elastic Cloud 托管集群配置为访问 Amazon S3。 | 设置对先前在 Amazon S3 中创建的快照存储库新集群的访问权限。使用 Kibana 执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-an-elk-stack-to-elastic-cloud-on-aws.html) | AWS 管理员，App support | 
| 验证新 Amazon S3 存储库。 | 确保您可访问托管在 Elastic Cloud 集群中的新存储库。 | AWS 管理员 | 
| 初始化 Elasticsearch 服务集群。 | 在 Elasticsearch Service Console，从 S3 快照初始化 Elasticsearch 服务集群。运行以下“发布”命令。<pre>*/_close?expand_wildcards=all</pre><pre>/_snapshot/<your-repo-name>/  <your-snapshot-name>/_restore</pre><pre>*/_open?expand_wildcards=all</pre> | App Support | 

### 完成迁移
<a name="complete-the-migration"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证快照恢复是否成功。 | 使用 Kibana 开发人员工具运行以下命令。<pre>GET _cat/indices</pre> | App support | 
| 重新部署摄取服务。 | 将 Beats 和 Logstash 的端点连接至新的 Elasticsearch 服务端点。 | App support | 

### 测试集群环境并清理
<a name="test-the-cluster-environment-and-clean-up"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证集群环境。 | 将本地 Elastic 集群环境迁移至 AWS 后，您可以连接到该环境并使用自己的用户验收测试 (UAT) 工具验证新环境。 | App support | 
| 清除资源。 | 验证集群成功迁移后，移除用于迁移的 S3 存储桶以及 IAM 角色。 | AWS 管理员 | 

## 相关资源
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-resources"></a>

**Elastic references**
+ [Elastic Cloud](https://www.elastic.co/cloud/)
+ [在 AWS 上托管 Elasticsearch 和 Kibana](https://www.elastic.co/elasticsearch/service)
+ [弹性企业搜索](https://www.elastic.co/enterprise-search)
+ [弹性集成](https://www.elastic.co/integrations?search=amazon)
+ [弹性可观测性](https://www.elastic.co/observability)
+ [弹性安全](https://www.elastic.co/security)
+ [Beats](https://www.elastic.co/beats/)
+ [Elastic APM](https://www.elastic.co/apm/)
+ [迁移至索引生命周期管理](https://www.elastic.co/guide/en/cloud-enterprise/current/ece-migrate-index-management.html)
+ [弹性订阅](https://www.elastic.co/subscriptions)
+ [接触弹性](https://www.elastic.co/contact)

*弹性博文*
+ [如何在 AWS 上从自我管理的 Elasticsearch 迁移至 Elastic Cloud](https://www.elastic.co/blog/how-to-migrate-from-self-managed-elasticsearch-to-elastic-cloud-on-aws)（博客文章）
+ [迁移至 Elastic Cloud](https://www.elastic.co/blog/migrating-to-elastic-cloud)（博客文章）

*Elastic 文档*
+ [教程：使用 SLM 自动备份](https://www.elastic.co/guide/en/elasticsearch/reference/7.10/getting-started-snapshot-lifecycle-management.html)
+ [ILM：管理索引生命周期](https://www.elastic.co/guide/en/elasticsearch/reference/current/index-lifecycle-management.html)
+ [Logstash](https://www.elastic.co/guide/en/logstash/current/index.html)
+ [跨集群复制 (CCR)](https://www.elastic.co/guide/en/elasticsearch/reference/7.14/xpack-ccr.html)
+ [采集管道](https://www.elastic.co/guide/en/elasticsearch/reference/current/ingest.html)
+ [运行 Elasticsearch API 请求](https://www.elastic.co/guide/en/kibana/current/console-kibana.html)
+ [快照保留](https://www.elastic.co/guide/en/elasticsearch/reference/current/slm-retention.html)

*Elastic 视频和网络研讨会*
+ [Elastic 云迁移](https://www.youtube.com/watch?v=WbPJi-APZ_Q)
+ [Elastic Cloud：客户为什么要迁移](https://www.elastic.co/webinars/elastic-cloud-why-customers-are-migrating-now)（网络研讨会）

**AWS 参考**
+ [Amazon Web Services Marketplace 上的弹性云](https://aws.amazon.com/marketplace/seller-profile?id=d8f59038-c24c-4a9d-a66d-6711d35d7305)
+ [AWS Command Line Interface](https://docs.aws.amazon.com/AmazonS3/latest/userguide/setup-aws-cli.html)
+ [AWS Direct Connect](https://aws.amazon.com/directconnect/)
+ [AWS 迁移加速计划](https://aws.amazon.com/migration-acceleration-program/)
+ [网络负载均衡器](https://aws.amazon.com/elasticloadbalancing/network-load-balancer/)
+ [区域和可用区](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/)
+ [Amazon Route 53](https://aws.amazon.com/route53/)
+ [Amazon Simple Storage Service](https://aws.amazon.com/s3/)
+ [Amazon S3 Transfer Acceleration](https://aws.amazon.com/s3/transfer-acceleration/)
+ [VPN 连接](https://docs.aws.amazon.com/vpc/latest/userguide/vpn-connections.html)
+ [架构完善的框架](https://aws.amazon.com/architecture/well-architected/?wa-lens-whitepapers.sort-by=item.additionalFields.sortDate&wa-lens-whitepapers.sort-order=desc)

## 附加信息
<a name="migrate-an-elk-stack-to-elastic-cloud-on-aws-additional"></a>

如果您计划迁移复杂的工作负载，请使用 [Elastic Consulting Services](https://www.elastic.co/consulting/engage)。如果您有与配置和服务相关的基本问题，请联系 [Elastic Support](mailto:support@elastic.co) 团队。

# 使用 Starburs AWS 云 t 将数据迁移到
<a name="migrate-data-to-the-aws-cloud-by-using-starburst"></a>

*Antony Prasad Thevaraj 和 Suresh Veeragoni，Amazon Web Services*

*Shaun Van Staden，无*

## Summary
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-summary"></a>

Starburst 通过提供企业查询引擎，将现有数据来源整合到一个接入点中，从而帮助您加快向 Amazon Web Services（AWS）的数据迁移之旅。在最终确定任何迁移计划之前，您可对多个数据来源进行分析，以获得有价值的见解。在不中断 business-as-usual分析的情况下，您可以使用 Starburst 引擎或专用的提取、转换和加载 (ETL) 应用程序迁移数据。

## 先决条件和限制
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 虚拟私有云（VPC）
+ Amazon Elastic Kubernetes Service (Amazon EKS) 集群
+ 亚马逊弹性计算云 (亚马逊 EC2) Auto Scaling 小组
+ 需要迁移的当前系统工作负载列表
+ 从您的本地环境 AWS 到您的本地环境的网络连接

## 架构
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-architecture"></a>

**参考架构**

以下高级架构图显示了 Starburst Enterprise 在 AWS 云中的典型部署：

1. Starburst Enterprise 集群在您的 AWS 账户中运行。

1. 用户使用轻型目录访问协议 (LDAP) 或开放授权 (OAuth) 进行身份验证，并直接与 Starburst 集群进行交互。

1. Starburst 可以连接到多个 AWS 数据源，例如亚马逊简单存储服务 (Amazon S3) AWS Glue、亚马逊关系数据库服务 (Amazon RDS) 和亚马逊 Redshift。Starburst 提供跨云环境 AWS 云、本地或其他云环境中的数据源的联合查询功能。

1. 您可使用 Helm 图表在 Amazon EKS 集群中启动 Starburst Enterprise。

1. Starburst Enterprise 使用 Amazon A EC2 uto Scaling 组和 Amazon EC2 Spot 实例来优化基础设施。

1. Starburst Enterprise 直接连接到至您现有的本地数据来源以实时读取数据。此外，如果您在此环境中部署了现有的 Starburst Enterprise，则可以将中的新 Starburst 集群直接 AWS 云 连接到该现有集群。

![\[在 Amazon Web Services Cloud 中部署 Starburst Enterprise 的高级架构图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/12ae0463-9029-4a32-9d7b-70cdb5406fb0/images/e9975d3a-f75b-41a2-8c08-5b82539adf8c.png)


请注意以下几点：
+ Starburst 不是数据虚拟化平台。它是基于 SQL 的大规模并行处理 (MPP) 查询引擎，构成了整体数据网格分析策略的基础。
+ 在迁移过程中部署 Starburst 时，它可以直接连接至现有的本地基础设施。
+ Starburst 提供了多种内置的企业和开源连接器，便于连接到各种遗留系统。有关连接器及其功能的完整列表，请参阅 *Starburst Enterprise 用户指南*中的[连接器](https://docs.starburst.io/latest/connector.html)。
+ Starburst 可从本地数据来源实时查询数据。这样可防止在迁移数据时中断常规业务运营。
+ 如果您要从现有的本地 Starburst Enterprise 部署迁移，则可以使用特殊连接器 Starburst *Stargate 将您的 Starbur* st Enterprise 集群 AWS 直接连接到本地集群。当业务用户和数据分析师将查询从联合 AWS 云 到您的本地环境时，这会带来额外的性能优势。

**高级流程概述**

您可使用 Starburst 加速数据迁移项目，因为 Starburst 可以在迁移数据之前对所有数据进行深入分析。下图显示了使用 Starburst 迁移数据的典型进程。

![\[使用 Starburst 将数据迁移到 Amazon Web Services Cloud 的流程流程\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/12ae0463-9029-4a32-9d7b-70cdb5406fb0/images/e79b0084-7275-4824-8854-646236ec23dc.png)


**角色**

使用 Starburst 完成迁移通常需要使用以下角色：
+ **云管理员** – 负责提供云资源以运行 Starburst Enterprise 应用程序
+ **Starburst 管理员** – 负责安装、配置、管理和支持 Starburst 应用程序
+ **数据工程师** – 负责：
  + 将遗留数据迁移到云
  + 构建语义视图以支持分析
+ **解决方案或系统所有者** – 负责整体解决方案的实施

## 工具
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-tools"></a>

**AWS 服务**
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 在中提供可扩展的计算容量 AWS 云。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [亚马逊 Elastic Kubernetes Service（亚马逊](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。

**其他工具**
+ [Helm](https://helm.sh/docs/) – Helm 是 Kubernetes 的软件包管理器，可帮助您在 Kubernetes 集群上安装和管理应用程序。
+ [Starburst Enterprise](https://docs.starburst.io/latest/index.html) – Starburst Enterprise 是一款基于 SQL 的大规模并行处理 (MPP) 查询引擎，构成了总体数据网格分析策略的基础。
+ [Starburst Stargate](https://docs.starburst.io/latest/connector/starburst-stargate.html) – Starburst Stargate 将一个 Starburst Enterprise 环境（例如本地数据中心中的集群）中的目录和数据来源链接到另一个 Starburst Enterprise 环境（例如 AWS 云中的集群）中的目录和数据来源。

## 操作说明
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-epics"></a>

### 评测数据
<a name="assess-the-data"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 识别您的数据并确定优先级。 | 确定您要移动的数据。大型本地遗留系统可能包含您想要迁移的核心数据，以及您不想移动或由于合规性原因而无法移动的数据。从数据清单开始，帮助您优先考虑应首先定位的数据。有关更多信息，请参阅[自动产品组合发现入门](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/get-started-with-automated-portfolio-discovery.html)。 | 数据工程师、数据库管理员 | 
| 浏览、清点和备份数据。 | 验证数据与您的用例的质量、数量和相关性。根据需要备份或创建数据快照，并最终确定数据的目标环境。 | 数据工程师、数据库管理员 | 

### 设置 Starburst Enterprise 环境
<a name="set-up-the-starburst-enterprise-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 AWS 云内配置 Starburst Enterprise。 | 在对数据进行编目时，在托管 Amazon EKS 集群中设置 Starburst Enterprise。有关更多信息，请参阅 *Starburst Enterprise 参考文档*中的[使用 Kubernetes 部署](https://docs.starburst.io/latest/k8s.html)。这允许在数据迁移过程中进行 business-as-usual分析。 | AWS 管理员、应用程序开发人员 | 
| 将 Starburst 连接至数据来源。 | 识别数据并设置 Starburst Enterprise 后，将 Starburst 连接到数据来源。Starburst 以 SQL 查询的形式直接从数据来源读取数据。有关更多信息，请参阅 [Starburst Enprise 参考文档](https://docs.starburst.io/latest/overview.html)。 | AWS 管理员、应用程序开发人员 | 

### 迁移数据
<a name="migrate-the-data"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 构建并运行 ETL 管线。 | 开始数据迁移进程。此活动可以与 business-as-usual分析同时发生。要进行迁移，您可使用第三方产品或 Starburst。Starburst 能跨不同来源读取和写入数据。有关更多信息，请参阅 [Starburst Enprise 参考文档](https://docs.starburst.io/latest/overview.html)。 | 数据工程师 | 
| 验证数据。 | 迁移数据后，验证数据以，确保所有必需的数据均已移动且完好无损。 | 数据工程师、 DevOps 工程师 | 

### 割接
<a name="cut-over"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 割接数据。 | 数据迁移和验证完成后，您可割接数据。这涉及更改 Starburst 中的数据链接。与其指向本地资源，不如指向新云源并更新语义视图。有关更多信息，请参阅 *Starburst Enterprise 参考文档*中的[连接器](https://docs.starburst.io/latest/connector.html)。 | 数据工程师，割接负责人 | 
| 向用户推出。 | 数据使用者开始处理迁移数据来源。此过程对于分析最终用户来说是不可见的。 | 割接负责人，数据工程师 | 

## 相关资源
<a name="migrate-data-to-the-aws-cloud-by-using-starburst-resources"></a>

**AWS Marketplace**
+ [Starburst Galaxy](https://aws.amazon.com/marketplace/pp/prodview-yugyv4gbgn5ss?ref_=srh_res_product_title)
+ [Starburst Enterprise](https://aws.amazon.com/marketplace/pp/prodview-pwnl3c6p2jycg?ref_=srh_res_product_title)
+ [Starburst 数据 JumpStart](https://aws.amazon.com/marketplace/pp/prodview-ou6drb23gch2u?ref_=srh_res_product_title)
+ [Starburst Enterprise with Graviton](https://aws.amazon.com/marketplace/pp/prodview-2bpppdqlesn6w?ref_=srh_res_product_title)

**Starburst 文档**
+ [Starburst Enterprise 用户指南](https://docs.starburst.io/index.html)
+ [Starburst Enterprise 参考文档](https://docs.starburst.io/latest/index.html)

**其他 AWS 文档**
+ [开始自动发现投资组合](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/get-started-with-automated-portfolio-discovery.html)（AWS 规范性指导）
+ 开启 [Starburst，优化云基础设施的成本和性能 AWS](https://aws.amazon.com/blogs/architecture/optimizing-cloud-infrastructure-cost-and-performance-with-starburst-on-aws/)（AWS 博客文章）

# 优化 AWS 输入文件大小的 ETL 摄取
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws"></a>

*Apoorva Patrikar，Amazon Web Services*

## Summary
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-summary"></a>

本指南向您展示如何通过在处理数据之前优化文件大小，以优化 AWS Glue 上的大数据和 Apache Spark 工作负载的提取、转换、加载（ETL）过程的摄取步骤。使用此模式可防止或解决*小文件问题*。也就是说，当大量小文件由于文件总大小而减慢数据处理速度时。例如，数百个只有几百 KB 的文件可能会显着降低 AWS Glue 作业的数据处理速度。这是因为 AWS Glue 必须在 Amazon Simple Storage Service (Amazon S3) 上执行内部列表功能，并且 YARN (Yet Another Resource Negotiator) 必须存储大量元数据。为了提高数据处理速度，您可以使用分组，以使 ETL 任务将一组输入文件读取至单个内存分区。该分区会自动将较小文件组合在一起。或者，您可以使用自定义代码将批处理逻辑添加至现有文件。

## 先决条件和限制
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 一个或多个 AWS glue [作业](https://docs.aws.amazon.com/glue/latest/dg/author-job.html)
+ 一个或多个大数据或 [Apache Spark](https://spark.apache.org/) 工作负载
+ 一个 [S3 存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html)

## 架构
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-architecture"></a>

以下指南展示了 AWS Glue 作业如何处理不同格式的数据，然后将其存储在 S3 存储桶中以了解性能。

![\[不同格式的数据由 AWS Glue 作业处理，然后存储在 S3 存储桶中。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/88ee332f-2f12-4d88-b491-e78bbb173850/images/9a97b54a-3f67-4a48-94d2-5807373ace25.png)


图表显示了以下工作流：

1. 
**注意**  
AWS Glue 任务将 CSV、JSON 和 Parquet 格式的小文件转换至动态框架。：输入文件的大小对 AWS Glue 任务性能影响最大。

1. AWS Glue 任务在 S3 存储桶执行内部列表功能。

## 工具
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-tools"></a>
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一项完全托管的 ETL 服务。它可以帮助您在数据存储和数据流之间对数据进行可靠地分类、清理、扩充和移动。
+ [Amazon Simple Storage Service(Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

## 操作说明
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-epics"></a>

### 读取期间通过分组优化 ETL 摄取
<a name="use-grouping-to-optimize-etl-ingestion-during-reading"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 指定群组大小。 | 如果您的文件数量超过 50,000 个，预设情况下将进行分组。但是，您也可以通过在 `connectionOptions` 参数中指定组大小来对少于 50,000 个文件使用分组。`connectionOptions` 参数使用 `create_dynamic_frame.from_options` 方法。 | 数据工程师 | 
| 编写分组代码。 | 使用 `create_dynamic_frame` 方法创建动态框架。例如：<pre>S3bucket_node1 = glueContext.create_dynamic_frame.from_options(<br />    format_options={"multiline": False},<br />    connection_type="s3",<br />    format="json",<br />    connection_options={<br />        "paths": ["s3://bucket/prefix/file.json"],<br />        "recurse": True,<br />        "groupFiles": 'inPartition', <br />        "groupSize": 1048576<br />    },<br />    transformation_ctx="S3bucket_node1",<br />)</pre>使用 `groupFiles` 对 Amazon S3 分区组中的文件进行分组。使用 `groupSize` 设置要在内存中读取的组的目标大小。以字节为指定 `groupSize` (1048576 = 1 MB)。 | 数据工程师 | 
| 将代码添加到工作流。 | 在 AWS Glue 中将分组代码添加至您的任务[工作流](https://docs.aws.amazon.com/glue/latest/dg/workflows_overview.html)。 | 数据工程师 | 

### 通过自定义逻辑优化 ETL 摄取
<a name="use-custom-logic-to-optimize-etl-ingestion"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 选择语言与处理平台。 | 选择针对您的用例量身定制的脚本语言与处理平台。 | 云架构师 | 
| 编写代码。 | 编写自定义逻辑，将文件一起批处理。 | 云架构师 | 
| 将代码添加到工作流。 | 在 AWS Glue 中添加代码到您的[工作流](https://docs.aws.amazon.com/glue/latest/dg/workflows_overview.html)。这样，您就可在每次运行作业时应用自定义逻辑。 | 数据工程师 | 

### 转换后写入数据时重新分区
<a name="repartition-when-writing-data-after-transformation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 分析使用模式。 | 了解下游应用程序将如何使用您写入的数据。例如，如果他们每天查询数据，而您只按区域对数据进行分区，或者输出文件非常小（例如每个文件 2.5 KB），那么这并非最佳的使用方式。 | 数据库管理员 | 
| 写入之前对数据重新分区。 | 在处理过程中（基于处理逻辑）和处理后（基于使用量），根据联接或查询进行重新分区。例如，根据字节大小进行重新分区（如 `.repartition(100000)`），或者根据列重新分区（如 `.repartition("column_name")`）。 | 数据工程师 | 

## 相关资源
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-resources"></a>
+ [读取较大群组中的输入文件](https://docs.aws.amazon.com/glue/latest/dg/grouping-input-files.html)
+ [监控 AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/monitor-glue.html)
+ [使用亚马逊 CloudWatch 指标监控 AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/monitoring-awsglue-with-cloudwatch-metrics.html)
+ [作业监控和调试](https://docs.aws.amazon.com/glue/latest/dg/monitor-profile-glue-job-cloudwatch-metrics.html)
+ [在 AWS Glue 上开启无服务器 ETL 入门](https://docs.aws.amazon.com/prescriptive-guidance/latest/serverless-etl-aws-glue/welcome.html)

## 附加信息
<a name="optimize-the-etl-ingestion-of-input-file-size-on-aws-additional"></a>

**确定文件大小**

没有直接的方法可确定文件大小。文件大小对处理性能的影响，取决于集群的配置。在核心 Hadoop，我们建议您使用 128 MB 或 256 MB 文件，以充分利用数据块。

对于 AWS Glue 上的大多数文本文件工作负载，我们建议 5-10 DPU 个集群的文件大小在 100 MB 到 1 GB 之间。要找出输入文件的最佳大小，请监控 AWS Glue 任务预处理部分，然后检查该作业的 CPU 利用率和内存利用率。

**其它注意事项**

如果早期 ETL 阶段的性能存在瓶颈，请考虑在处理之前对数据文件进行分组或合并。如果您可完全控制文件生成过程，则在将原始数据发送至 AWS 之前，在源系统本身上聚合数据点会更加高效。

# 使用验证、转换和分区编排 ETL 管道 AWS Step Functions
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions"></a>

*Sandip Gangapadhyay，Amazon Web Services*

## Summary
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-summary"></a>

此示例介绍了如何构建无服务器提取、转换、加载（ETL）管道，以验证、转换、压缩和分区大型 CSV 数据集，从而实现性能和成本优化。该管道由编排 AWS Step Functions 并包括错误处理、自动重试和用户通知功能。

将 CSV 文件上传至 Amazon Simple Storage Service (Amazon S3) 存储桶文件夹，ETL 管道开始运行。该管道验证源 CSV 文件的内容和架构，将 CSV 文件转换为压缩 Apache Parquet 格式，按年、月和日对数据集进行分区，并将其存储在单独的文件夹中供分析工具处理。

自动执行此模式的代码可在[带有 AWS Step Functions存储库的 ETL Pipelin](https://github.com/aws-samples/aws-step-functions-etl-pipeline-pattern) e 中找到。 GitHub

## 先决条件和限制
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ AWS Command Line Interface (AWS CLI) 已安装并配置为你的 AWS 账户，这样你就可以通过部署 AWS CloudFormation 堆栈来创建 AWS 资源。我们建议使用 AWS CLI 版本 2。有关说明，请参阅 AWS CLI 文档 AWS CLI中的[安装或更新到最新版本](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)的。有关配置说明，请参阅 AWS CLI 文档中的[配置和凭据文件设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)。
+ Amazon S3 存储桶。
+ 具有正确架构的 CSV 数据集。(此模式中包含的[代码存储库](https://github.com/aws-samples/aws-step-functions-etl-pipeline-pattern/)提供了示例 CSV 文件，其中包含您可以使用的正确架构和数据类型。)
+ 支持 AWS 管理控制台. 的网络浏览器 （请参阅[支持的浏览器列表](https://aws.amazon.com/premiumsupport/knowledge-center/browsers-management-console/)。）
+ AWS Glue 控制台访问权限。
+ AWS Step Functions 控制台访问权限。

**限制**
+ 在中 AWS Step Functions，保存历史记录日志的最大限制为 90 天。有关更多信息，请参阅 AWS Step Functions 文档中的 Ste [p Functions 服务配额](https://docs.aws.amazon.com/step-functions/latest/dg/service-quotas.html)。

**产品版本**
+ Python 3.13 适用于 AWS Lambda
+ AWS Glue 版本 4.0

## 架构
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-architecture"></a>

![\[从 S3 源存储桶开始，通过 Step Functions、AWS Glue 和 Amazon SNS 进行数据提取、转换和加载（ETL）的 10 步流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/8eb792b0-d35b-4a63-ba2d-71eb8d2c1203/images/054c8e9d-76a2-4334-b21a-cbe76af45923.png)


 

图中所示的工作流包括以下高级步骤：

1. 用户将 CSV 文件上传至 Amazon S3 中的源文件夹。

1. Amazon S3 通知事件启动启动 AWS Step Functions 状态机的 AWS Lambda 函数。

1. Lambda 函数验证原始 CSV 文件架构和数据类型。

1. 根据验证结果：

   1. 如源文件验证成功，则文件将移至舞台文件夹进行进一步处理。

   1. 如果验证失败，文件将移至错误文件夹，并由 Amazon Simple Notiﬁcation Service (Amazon SNS) 发送错误通知。

1.  AWS Glue 爬虫从 Amazon S3 的舞台文件夹中创建原始文件的架构。

1.  AWS Glue 作业将原始文件转换、压缩和分区为 Parquet 格式。

1. 该 AWS Glue 任务还会将文件移动到 Amazon S3 中的转换文件夹。

1. C AWS Glue rawler 根据转换后的文件创建架构。生成的架构用于任何分析作业。您还可以使用 Amazon Athena 中运行临时查询。

1. 如果管道在无错误的情况下完成，则架构文件将移至存档文件夹。如遇到任何错误，则会将文件移至错误文件夹。

1. Amazon SNS 会根据管道完成状态发送通知，指示成功或者失败。

此模式中使用的所有 AWS 资源都是无服务器的。没有需要管理的服务器。

## 工具
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-tools"></a>

**AWS 服务**
+ [AWS Glue](https://aws.amazon.com/glue/)— AWS Glue 是一项完全托管的 ETL 服务，可让客户轻松准备和加载数据进行分析。
+ [AWS Step Functions](https://aws.amazon.com/step-functions/)— AWS Step Functions 是一项无服务器编排服务，可让您组合 AWS Lambda 功能和其他功能 AWS 服务 来构建关键业务应用程序。通过 AWS Step Functions 图形控制台，您可以将应用程序的工作流程视为一系列事件驱动的步骤。
+ [Amazon S3](https://aws.amazon.com/s3/) – Amazon Simple Storage Service（Amazon S3）是一种对象存储服务，提供行业领先的可扩展性、数据可用性、安全性和性能。
+ [Amazon SNS](https://aws.amazon.com/sns/) — 亚马逊简单通知服务 (Amazon SNS) Simple Notification 是一项高度可用、耐用、安全、完全 pub/sub 托管的消息服务，可让您分离微服务、分布式系统和无服务器应用程序。
+ [AWS Lambda](https://aws.amazon.com/lambda/)— AWS Lambda 是一项计算服务，允许您在不预配置或管理服务器的情况下运行代码。 AWS Lambda 仅在需要时运行您的代码，并自动缩放，从每天几个请求到每秒数千个请求。

**代码**

此模式的代码可在[带有 AWS Step Functions存储库的 ETL Pipelin](https://github.com/aws-samples/aws-step-functions-etl-pipeline-pattern) e 中找到。 GitHub此代码存储库包含以下文件和文件夹：
+ `template.yml`— 用于创建 ETL 管道的 AWS CloudFormation AWS Step Functions模板。
+ `parameter.json` — 包含所有参数和参数值。您可更新此文件以更改参数值，如*操作说明*部分所述。
+ `myLayer/python`文件夹-包含为此项目创建所需 AWS Lambda 图层所需的 Python 包。
+ `lambda` 文件夹 - 包含以下 Lambda 函数：
  + `move_file.py` — 将源数据集移动到存档、转换或错误文件夹。
  + `check_crawler.py`— 在 AWS Glue 爬网程序发送失败消息之前，根据`RETRYLIMIT `环境变量的配置多次检查其状态。
  + `start_crawler.py`— 启动 AWS Glue 爬行器。
  + `start_step_function.py`— 开始 AWS Step Functions。
  + `start_codebuild.py`— 启动 AWS CodeBuild 项目。
  + `validation.py` — 验证输入的原始数据集。
  + `s3object.py` – 在 Amazon S3 存储桶内创建所需目录结构。
  + `notification.py` — 在管道结束时发送成功或错误通知。

若要使用示例代码，请按照*操作*部分的说明执行。

## 操作说明
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-epics"></a>

### 准备源文件
<a name="prepare-the-source-files"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆示例代码存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 开发者版 | 
| 更新参数值。 | 在存储库本地副本中，编辑 `parameter.json` 文件并更新默认参数值，如下所示：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 开发者版 | 
| 上传源代码到 Amazon S3 存储桶。 | 在部署自动执行 ETL 管道的 AWS CloudFormation 模板之前，必须打包模板的源文件并将其上传到 Amazon S3 存储桶。为此，请使用预先配置的配置文件运行以下 AWS CLI 命令：<pre>aws cloudformation package --template-file template.yml --s3-bucket <bucket_name> --output-template-file packaged.template --profile <profile_name></pre>其中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 开发者版 | 

### 创建堆栈
<a name="create-the-stack"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 CloudFormation 模板。 | 要部署 AWS CloudFormation 模板，请运行以下 AWS CLI 命令：<pre>aws cloudformation deploy --stack-name <stack_name> --template-file packaged.template --parameter-overrides file://parameter.json --capabilities CAPABILITY_IAM --profile <profile_name></pre>其中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 开发者版 | 
| 查看进度。 | 在 [AWS CloudFormation 控制台](https://console.aws.amazon.com/cloudformation/)上，查看堆栈开发进度。当状态为时 `CREATE_COMPLETE`，表示堆栈已成功部署。 | 开发者版 | 
| 记下 AWS Glue 数据库名称。 | 堆栈的 “**输出**” 选项卡显示 AWS Glue 数据库的名称。键名称为 `GlueDBOutput`。 | 开发者版 | 

### 测试管道
<a name="test-the-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动 ETL 管道。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 开发者版 | 
| 查看分区数据集。 | ETL 管道完成后，确认分区数据集在 Amazon S3 转换文件夹（`transform` 或您在 `parameter.json` 文件中设置的文件夹名称）中可用。 | 开发者版 | 
| 检查分区 AWS Glue 数据库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.html) | 开发者版 | 
| 运行查询。 | （可选）使用 Amazon Athena 对已分区和转换的数据库运行临时查询。有关说明，请参阅文档中的在 [Amazon Athena 中运行 SQL 查询](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)。 AWS  | 数据库分析师 | 

## 问题排查
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| AWS Identity and Access Management AWS Glue 任务和爬虫的 (IAM) 权限 | 如果您进一步自定义 AWS Glue 任务或抓取工具，请务必在 AWS Glue 任务使用的 IAM 角色中授予相应的 IAM 权限，或者向提供数据权限。 AWS Lake Formation有关详情，请参阅 [AWS 文档](https://docs.aws.amazon.com/lake-formation/latest/dg/upgrade-glue-lake-formation.html)。 | 

## 相关资源
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-resources"></a>

**AWS 服务 文档**
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/)
+ [AWS Glue](https://docs.aws.amazon.com/glue/)
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/)
+ [Amazon S3](https://docs.aws.amazon.com/s3/)
+ [Amazon SNS](https://docs.aws.amazon.com/sns/)

## 附加信息
<a name="orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions-additional"></a>

下图显示了 Insp AWS Step Functions **ector** 面板中成功建立 ETL 管道 AWS Step Functions 的工作流程。 ****

![\[Step Functions 工作流，用于验证输入的 .csv、爬取数据和运行 AWS Glue 作业。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/8eb792b0-d35b-4a63-ba2d-71eb8d2c1203/images/bd77de7b-4d04-44bb-95d2-3ec4599b3770.png)


下图显示了 Step Functions Insp **ec** tor 面板中因输入验证错误而失败的 ETL 管道 AWS Step Functions 的工作流程。

![\[Step Functions 工作流发生故障，因此文件被移至错误文件夹。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/8eb792b0-d35b-4a63-ba2d-71eb8d2c1203/images/5fd7dd79-ba4c-4c20-b1f0-ad4b5f22bdfc.png)


 

# 使用 Amazon Redshift ML 执行高级分析
<a name="perform-advanced-analytics-using-amazon-redshift-ml"></a>

*Po Hong 和 Chyanna Antonio，Amazon Web Services*

## Summary
<a name="perform-advanced-analytics-using-amazon-redshift-ml-summary"></a>

在 Amazon Web Services (AWS) Cloud，您可使用 Amazon Redshift machine learning (Amazon Redshift ML) 对存储在 Amazon Redshift cluster 或 Amazon Simple Storage Service (Amazon S3) 的数据执行机器学习分析。Amazon Redshift ML 支持有监督学习，这种学习常用于高级分析。Amazon Redshift ML 用例包括收入预测、信用卡欺诈检测以及客户生命周期价值 (CLV) 或客户流失预测。

Amazon Redshift ML 使数据库用户可以轻松地使用标准的 SQL 命令创建、训练和部署 ML 模型。Amazon Redshift ML 使用 Amazon A SageMaker utopilot 自动训练和调整最佳机器学习模型，以便根据您的数据进行分类或回归，同时保持控制和可见性。

亚马逊 Redshift、Amazon S3 和亚马逊之间的所有交互 SageMaker 都被抽象出来并实现了自动化。ML 模型经过训练和部署后，它将作为[用户定义函数](https://docs.aws.amazon.com/redshift/latest/dg/user-defined-functions.html) (UDF) 在 Amazon Redshift 中使用，并可用于 SQL 查询。 

此模式补充了 AWS 博客中的 “[使用 SQL 在 Amazon Redshift 中创建、训练和部署机器学习模型](https://aws.amazon.com/blogs/big-data/create-train-and-deploy-machine-learning-models-in-amazon-redshift-using-sql-with-amazon-redshift-ml/)” 和 [“入门资源中心” 中的 “使用 SageMaker亚马逊构建、训练和部署机器学习模型](https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/)[”](https://aws.amazon.com/getting-started/) 教程。

## 先决条件和限制
<a name="perform-advanced-analytics-using-amazon-redshift-ml-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ Amazon Redshift 表内现有数据

**技能**
+ 熟悉 Amazon Redshift ML 使用的术语和概念，包括*机器学习*、*培训*和*预测*。有关这方面的更多信息，请参阅 Amazon Machine Learning (Amazon ML) 文档中的[ML 模型培训](https://docs.aws.amazon.com/machine-learning/latest/dg/training-ml-models.html)。
+ 体验 Amazon Redshift 用户设置、访问管理以及标准 SQL 语法。有关的更多信息，请参阅 Amazon Redshift 文档中的 [Amazon Redshift 入门](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html)。
+ Amazon S3 和 AWS Identity and Acess Management (IAM) 方面的专长和经验。 
+ 在 AWS 命令行界面（AWS CLI）中运行命令也是有益的，但不是必需的。

**限制**
+ Amazon Redshift 集群与 S3 存储桶必须位于同一 AWS 区域。
+ 此模式方法仅支持有监督学习模型，例如回归、二进制分类以及多类分类。 

## 架构
<a name="perform-advanced-analytics-using-amazon-redshift-ml-architecture"></a>

![\[工作流程展示了 Amazon Redshift 机器学习 SageMaker 如何使用来构建、训练和部署机器学习模型。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/3b6a5f49-c647-45f4-940e-b623f989326a/images/36cc39fe-c1f3-4d68-b89e-e636156001a6.png)


以下步骤说明了 Amazon Redshift 机器学习如何使用 SageMaker 来构建、训练和部署机器学习模型： 

1. Amazon Redshift 将训练数据导出到 S3 存储桶中。

1. SageMaker Autopilot 会自动预处理训练数据。

1. 调用该`CREATE MODEL`语句后，Amazon Redshift ML 将 SageMaker 用于训练。

1. SageMaker Autopilot 搜索并推荐用于优化评估指标的机器学习算法和最佳超参数。

1. Amazon Redshift ML 会在 Amazon Redshift 集群中将输出 ML 模型注册为 SQL 函数。

1. ML 模型的函数可用于 SQL 语句。 

**技术堆栈**
+ Amazon Redshift
+ SageMaker
+ Amazon S3

## 工具
<a name="perform-advanced-analytics-using-amazon-redshift-ml-tools"></a>
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/latest/dg/welcome.html) – Amazon Redshift 是一种完全托管的企业 PB 级数据仓库服务。
+ [Amazon Redshift ML](https://docs.aws.amazon.com/redshift/latest/dg/machine_learning.html) – Amazon Redshift 机器学习 (Amazon Redshift ML) 是一种基于云的稳健服务，能够让所有技能水平的分析人员和数据科学家都能轻松使用 ML 技术。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一项面向互联网的存储服务。 
+ [Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) — SageMaker 是一项完全托管的机器学习服务。 
+ [Amazon A SageMaker uto SageMaker pil](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-automate-model-development.html) ot — Autopilot 是一款功能集，可自动执行自动机器学习 (AutoML) 过程中的关键任务。

 

**代码**

您可使用以下代码，在 Amazon Redshift 中创建受监管的 ML 模型：

```
"CREATE MODEL customer_churn_auto_model
FROM (SELECT state,
             account_length,
             area_code,
             total_charge/account_length AS average_daily_spend, 
             cust_serv_calls/account_length AS average_daily_cases,
             churn 
      FROM customer_activity
      WHERE  record_date < '2020-01-01' 
     )
TARGET churn
FUNCTION ml_fn_customer_churn_auto
IAM_ROLE 'arn:aws:iam::XXXXXXXXXXXX:role/Redshift-ML'
SETTINGS (
  S3_BUCKET 'your-bucket'
);")
```

**注意**  
`SELECT` 状态可以指 Amazon Redshift 常规表或 Amazon Redshift Spectrum 外部表，或者同时参考两者。

## 操作说明
<a name="perform-advanced-analytics-using-amazon-redshift-ml-epics"></a>

### 准备训练与测试数据集
<a name="prepare-a-training-and-test-dataset"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 准备训练与测试数据集。 | 登录 AWS 管理控制台并打开亚马逊 SageMaker 控制台。按照[构建、训练和部署机器学习模型](https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/)教程创建包含标签列（*监督训练*）且没有标题的 .csv 或 Apache Parquet 文件。 我们建议您将原始数据集进行打乱，并拆分为用于模型训练的训练集（70%）和用于模型性能评估的测试集（30%）。 | 数据科学家 | 

### 准备与配置技术堆栈
<a name="prepare-and-configure-the-technology-stack"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建和配置 Amazon Redshift 集群。 | 在 Amazon Redshift 控制台，根据您的要求创建集群。有关更多信息，请参阅 Amazon Redshift 文档中的[创建集群](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-data-launch-cluster.html)。 Amazon Redshift 集群必须使用 `SQL_PREVIEW` 维护轨道创建。有关预览轨道的更多信息，请参阅 Amazon Redshift 文档中的[选择集群维护轨道](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-mgmt-maintenance-tracks)。 | 数据库管理员、云架构师 | 
| 创建 S3 存储桶以存储训练数据和模型构件。 | 在 Amazon S3 控制台，创建 S3 存储桶以训练和测试数据。有关创建 S3 存储桶的更多信息，请参阅 AWS 快速入门中的[创建 S3 存储桶](https://docs.aws.amazon.com/quickstarts/latest/s3backup/step-1-create-bucket.html)。 请确保您的 Amazon Redshift 集群与 S3 存储桶位于同一区域。  | 数据库管理员、云架构师 | 
| 创建 IAM policy，并将其附加至 Amazon Redshift 集群。 | 创建 IAM 策略以允许 Amazon Redshift 集群访问 SageMaker 和亚马逊 S3。有关说明和步骤，请参阅 Amazon Redshift 文档中的[使用 Amazon Redshift ML 的集群设置](https://docs.aws.amazon.com/redshift/latest/dg/cluster-setup.html)。 | 数据库管理员、云架构师 | 
| 允许 Amazon Redshift 用户和群组访问架构和表格。 | 授予权限，允许 Amazon Redshift 中的用户和群组访问内部和外部架构和表格。有关步骤和说明，请参阅 Amazon Redshift 文档的[管理权限和所有权](https://docs.aws.amazon.com/redshift/latest/dg/permissions-ownership.html)。 | 数据库管理员 | 

### 在 Amazon Redshift 中创建和训练 ML 模型
<a name="create-and-train-the-ml-model-in-amazon-redshift"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 Amazon Redshift 中创建和训练 ML 模型。 | 在 Amazon Redshift ML 中创建和训练您的 ML 模型。有关更多信息，请参阅 Amazon Redshift 文档中的 `CREATE MODEL` 语句。 | 开发人员、数据科学家 | 

### 在 Amazon Redshift 中执行批量推理与预测
<a name="perform-batch-inference-and-prediction-in-amazon-redshift"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用生成的 ML 模型函数执行推理。 | 有关使用生成 ML 模型函数执行推理的更多信息，请参阅 Amazon Redshift 文档中的[预测](https://docs.aws.amazon.com/redshift/latest/dg/prediction.html)。 | 数据科学家、商业智能用户 | 

## 相关资源
<a name="perform-advanced-analytics-using-amazon-redshift-ml-resources"></a>

**准备训练与测试数据集**
+ [使用 Amazon 构建、训练和部署机器学习模型 SageMaker](https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/)

 

**准备与配置技术堆栈**
+ [创建 Amazon Redshift 集群。](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-data-launch-cluster.html)
+ [选择 Amazon Redshift 集群维护轨道](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-mgmt-maintenance-tracks)
+ [创建 S3 存储桶](https://docs.aws.amazon.com/quickstarts/latest/s3backup/step-1-create-bucket.html)
+ [为使用 Amazon Redshift ML 设置 Amazon Redshift 集群](https://docs.aws.amazon.com/redshift/latest/dg/cluster-setup.html)
+ [在 Amazon Redshift 中管理权限与所有权](https://docs.aws.amazon.com/redshift/latest/dg/permissions-ownership.html)

 

**在 Amazon Redshift 中创建和训练 ML 模型**
+ [在 Amazon Redshift 中创建模型语句](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_MODEL.html#r_simple_create_model) 

 

**在 Amazon Redshift 中执行批量推理与预测**
+ [Amazon Redshift 中的预测](https://docs.aws.amazon.com/redshift/latest/dg/prediction.html) 

 

**其他资源**
+ [Amazon Redshift ML 入门](https://docs.aws.amazon.com/redshift/latest/dg/geting-started-machine-learning.html)
+ [使用 SQL 和 Amazon Redshift ML 在 Amazon Redshift 中构建、训练和部署 ML 模型](https://aws.amazon.com/blogs/big-data/create-train-and-deploy-machine-learning-models-in-amazon-redshift-using-sql-with-amazon-redshift-ml/)
+ [Amazon Redshift 合作伙伴](https://aws.amazon.com/redshift/partners/?partner-solutions-cards.sort-by=item.additionalFields.partnerNameLower&partner-solutions-cards.sort-order=aschttps://aws.amazon.com/redshift/partners/?partner-solutions-cards.sort-by=item.additionalFields.partnerNameLower&partner-solutions-cards.sort-order=asc)
+ [AWS 机器学习能力合作伙伴](https://aws.amazon.com/machine-learning/partner-solutions/?partner-solutions-cards.sort-by=item.additionalFields.partnerNameLower&partner-solutions-cards.sort-order=asc)

# 使用 Amazon Athena 通过 SQL 查询 Amazon DynamoDB 表
<a name="query-amazon-dynamodb-tables-sql-amazon-athena"></a>

*Gavin Perrie、Ajit Ambike 和 Brad Yates，Amazon Web Services*

## Summary
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-summary"></a>

如果您的数据包含除 Amazon Simple Storage Service（Amazon S3）之外的其他数据来源，可以使用联合查询来访问这些关系型、非关系型、对象型或自定义数据来源。此模式展示了如何使用 SQL 数据来源连接器，通过 Amazon Athena 配置对 Amazon DynamoDB 的联合查询访问。

您可以使用此模式执行以下操作：
+ 使用 SQL 查询 DynamoDB 表。
+ 在 Athena 中运行联合 SQL 查询，并将 DynamoDB 表与其他受支持的数据来源联接。

## 先决条件和限制
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-prereqs"></a>

**先决条件**
+ 一个 DynamoDB 表。
+ 有一个 Athena 工作组设置为使用 Athena 引擎版本 2。有关说明，请参阅 [Athena 文档](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-changing.html)。
+ 一个 S3 存储桶，`AthenaDynamoDBConnector` AWS Lambda 函数可以在其中泄露数据。Lambda 函数必须与 S3 存储桶位于同一 AWS 区域。

如果是首次访问 Athena，则需要一个额外的 S3 存储桶用作查询结果的存储位置。有关说明，请参阅 [Athena 文档](https://docs.aws.amazon.com/athena/latest/ug/querying.html#query-results-specify-location-console)。

**限制**
+ 不支持诸如 [INSERT INTO](https://docs.aws.amazon.com/athena/latest/ug/insert-into.html) 之类的写入操作。****

**产品版本**
+ [Athena Query Federation 发布于 GitHub](https://github.com/awslabs/aws-athena-query-federation/releases)

## 架构
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-architecture"></a>

**目标架构**

下图显示了模式建立后的连接流程。用户将连接到 Amazon Athena 以提供查询。Athena 会将查询和目标传递给 DynamoDB 数据来源连接器 Lambda 函数，然后函数会检索数据并将其返回给 Athena。如果返回大量数据，Athena 会在打包并返回完整数据集之前，将临时结果存储在溢出存储桶中。

![\[从用户到 Athena 再到 Lambda 的工作流，Lambda 连接到 S3 存储桶和 DynamoDB 表。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/9d1ee529-36f3-4c7e-a2e7-05b76e09a3d8/images/e50a00cf-a55a-4def-81d5-4d2755dc9a97.png)


## 工具
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-tools"></a>

**AWS 服务**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一种交互式查询服务，可帮助您通过使用标准 SQL 直接分析 Amazon Simple Storage Service（Amazon S3）中的数据。此模式使用 [Amazon Athena DynamoDB 连接器，该工具使用亚马逊](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb) Athena Query Federation SDK 构建，并通过作为应用程序安装。 AWS Lambda AWS Serverless Application Repository
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一项完全托管式 NoSQL 数据库服务，可提供快速、可预测、可扩展的性能。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**代码存储库 **

此模式的代码可在 GitHub [Athena Query Federation 存储库中找到。](https://github.com/awslabs/aws-athena-query-federation/releases)

## 操作说明
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-epics"></a>

### 设置和测试 DynamoDB 数据来源连接器
<a name="set-up-and-test-the-ddb-data-source-connector"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 AthenaDynamoDBConnector 应用程序。 | 要部署 AthenaDynamoDBConnecter，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/query-amazon-dynamodb-tables-sql-amazon-athena.html) | AWS DevOps | 
| 为 Athena 创建数据来源。 | 要创建数据来源，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/query-amazon-dynamodb-tables-sql-amazon-athena.html) | AWS DevOps | 
| 使用 Athena 查询 DynamoDB 表。 | 要查询 DynamoDB 表，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/query-amazon-dynamodb-tables-sql-amazon-athena.html) | 应用程序开发人员 | 

## 问题排查
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 查询失败：`GENERIC_INTERNAL_ERROR: The bucket is in this region: <region>`*。* | 确保 Athena 溢出存储桶和 Lambda 函数是在同一个 AWS 区域中创建的。 | 
| 新创建的数据来源未显示在 Athena 控制台上。 | Athena 数据目录是区域性的。确保已在尝试使用 Athena 的区域部署 `AthenaDynamoDBConnector`。 | 
| 不能对新创建的数据来源运行查询。 | 检查是否已设定**查询结果位置**。 | 

## 相关资源
<a name="query-amazon-dynamodb-tables-sql-amazon-athena-resources"></a>
+ [亚马逊 Athena DynamoDB 连接器](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb)
+ [Amazon Athena 联合查询](https://docs.aws.amazon.com/athena/latest/ug/connect-to-a-data-source.html)

# 使用 Athena 访问、查询和联接 Amazon DynamoDB 表
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena"></a>

*Moinul Al-Mamun，Amazon Web Services*

## Summary
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-summary"></a>

此模式说明如何使用 Amazon Athena DynamoDB 连接器在 Amazon Athena 和 Amazon DynamoDB 之间建立连接。连接器使用 AWS Lambda 函数查询 DynamoDB 中的数据。您无需编写任何代码即可设置连接。建立连接后，您可以[使用 Athena 联合查询](https://docs.aws.amazon.com/athena/latest/ug/connect-to-a-data-source.html)从 Athena 运行 SQL 命令，从而快速访问和分析 DynamoDB 表。您还可以将一个或多个 DynamoDB 表相互联接，或联接到其他数据来源，例如 Amazon Redshift 或 Amazon Aurora。

## 先决条件和限制
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户，拥有管理 DynamoDB 表、Athena 数据来源、Lambda 和 AWS Identity and Access Management（IAM）角色的权限
+ 一个 Amazon Simple Storage Service（Amazon S3）存储桶，Athena 可以在其中存储查询结果
+ 一个 S3 存储桶，Athena DynamoDB 连接器可以在其中保存数据
+ 支持 [Athena 引擎版本 2](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference-0002.html) 的 AWS 区域
+ 访问 Athena 和所需 S3 存储桶的 IAM 权限
+ [Amazon Athena DynamoDB 连接器](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb)，已安装

**限制**

查询 DynamoDB 表需要付费。表大小超过几千兆字节 (GBs) 可能会产生高昂的成本。我们建议您在执行任何全表 SCAN 操作之前考虑成本。有关更多信息，请参阅 [Amazon DynamoDB 定价](https://aws.amazon.com/dynamodb/pricing/)。为了降低成本并实现高性能，我们建议您始终在查询中使用 LIMIT（例如，`SELECT * FROM table1 LIMIT 10`）。此外，在生产环境中执行 JOIN 或 GROUP BY 查询之前，请考虑表的大小。如果您的表太大，请考虑其他选项，例如[将表迁移到 Amazon S3](https://aws.amazon.com/blogs/database/simplify-amazon-dynamodb-data-extraction-and-analysis-by-using-aws-glue-and-amazon-athena/)。

## 架构
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-architecture"></a>

下图显示了用户如何从 Athena 对 DynamoDB 表运行 SQL 查询。

![\[连接 Athena 和 DynamoDB 以运行 SQL 查询的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e6ff94af-d208-40c7-94e4-af257755a603/images/bc8e0132-b578-463b-bf55-3c39ce359c17.png)


下图显示了如下工作流：

1. 要查询 DynamoDB 表，用户需要从 Athena 运行 SQL 查询。

1. Athena 启动 Lambda 函数。

1. Lambda 函数查询 DynamoDB 表中请求的数据。

1. DynamoDB 将请求的数据返回给 Lambda 函数。然后，该函数通过 Athena 将查询结果传输给用户。

1. Lambda 函数将数据存储在 S3 存储桶中。

**技术堆栈**
+ Amazon Athena
+ Amazon DynamoDB
+ Amazon S3
+ AWS Lambda

## 工具
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-tools"></a>
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一种交互式查询服务，可帮助您使用标准 SQL 直接在 Amazon S3 中分析数据。
+ [Amazon Athena DynamoDB Connector](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb) 是一种 AWS 工具，它使 Athena 能够与 DynamoDB 连接并使用 SQL 查询访问您的表。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一项完全托管式 NoSQL 数据库服务，可提供快速、可预测、可扩展的性能。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，而无需预置或管理服务器。它仅在需要时运行您的代码，并且能自动扩缩，因此您只需为使用的计算时间付费。

## 操作说明
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-epics"></a>

### 创建示例 DynamoDB 表
<a name="create-sample-dynamodb-tables"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建第一个示例表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html) | 开发者版 | 
| 将示例数据插入到第一个表中。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html)<pre>{<br />  "PK1": "1234",<br />  "SK1": "info",<br />  "Salary": "5000"<br /> }</pre><pre>{<br />  "PK1": "1235",<br />  "SK1": "info",<br />  "Salary": "5200"<br /> }</pre> | 开发者版 | 
| 创建第二个示例表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html) | 开发者版 | 
| 将示例数据插入到第二个表中。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html)<pre>{<br />  "PK2": "1234",<br /> "SK2": "bonus",<br /> "Bonus": "500"<br />}</pre><pre>{<br />  "PK2": "1235",<br /> "SK2": "bonus",<br /> "Bonus": "1000"<br />}</pre> | 开发者版 | 

### 在 Athena 中为 DynamoDB 创建数据来源
<a name="create-a-data-source-in-athena-for-dynamodb"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置数据来源连接器。 | 为 DynamoDB 创建数据来源，然后创建 Lambda 函数以连接到该数据来源。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html) | 开发者版 | 
| 验证 Lambda 函数是否可以访问 S3 溢出存储桶。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html)如果遇到错误，请参阅此模式中的*其他信息*部分以获取指导。 | 开发者版 | 

### 从 Athena 访问 DynamoDB 表
<a name="access-dynamodb-tables-from-athena"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查询 DynamoDB 表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html) | 开发者版 | 
| 连接两个 DynamoDB 表。 | DynamoDB 是 NoSQL 数据存储，不支持 SQL 联接操作。因此，您必须对两个 DynamoDB 表执行联接操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-query-and-join-amazon-dynamodb-tables-using-athena.html)<pre>SELECT pk1, salary, bonus FROM dydbtable1 t1<br /> JOIN dydbtable2 t2 ON t1.pk1 = t2.pk2;</pre> | 开发者版 | 

## 相关资源
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-resources"></a>
+ [Amazon Athena DynamoDB 连接器](https://github.com/awslabs/aws-athena-query-federation/tree/master/athena-dynamodb)（AWS Labs）
+ [使用 Amazon Athena 的新联合查询查询任何数据来源](https://aws.amazon.com/blogs/big-data/query-any-data-source-with-amazon-athenas-new-federated-query/)（AWS 大数据博客）
+ [Athena 引擎版本参考](https://docs.aws.amazon.com/athena/latest/ug/engine-versions-reference.html)（Athena 用户指南）
+ [使用 AWS Glue 和 Amazon Athena 简化 Amazon DynamoDB 数据提取和分析](https://aws.amazon.com/blogs/database/simplify-amazon-dynamodb-data-extraction-and-analysis-by-using-aws-glue-and-amazon-athena/)（AWS 数据库博客）

## 附加信息
<a name="access-query-and-join-amazon-dynamodb-tables-using-athena-additional"></a>

如果您在 Athena 中使用 `spill_bucket` 的 `{bucket_name}/folder_name/` 格式运行查询，则可能会收到以下错误消息：

```
"GENERIC_USER_ERROR: Encountered an exception[java.lang.RuntimeException] from your LambdaFunction[arn:aws:lambda:us-east-1:xxxxxx:function:testdynamodb] executed in context[retrieving meta-data] with message[You do NOT own the spill bucket with the name: s3://amzn-s3-demo-bucket/athena_dynamodb_spill_data/]
This query ran against the "default" database, unless qualified by the query. Please post the error message on our forum  or contact customer support with Query Id: [query-id]"
```

要解决此错误，请将 Lambda 函数的环境变量 `spill_bucket` 更新为 `{bucket_name_only}`，然后更新存储桶写入访问权限的以下 Lambda IAM policy：

```
{
             "Action": [
                 "s3:GetObject",
                 "s3:ListBucket",
                 "s3:GetBucketLocation",
                 "s3:GetObjectVersion",
                 "s3:PutObject",
                 "s3:PutObjectAcl",
                 "s3:GetLifecycleConfiguration",
                 "s3:PutLifecycleConfiguration",
                 "s3:DeleteObject"
            ],
             "Resource": [
                 "arn:aws:s3:::spill_bucket",
                 "arn:aws:s3:::spill_bucket/*"
            ],
             "Effect": "Allow"
        }
```

或者，您可以删除之前创建的 Athena 数据来源连接器，然后仅对 `spill_bucket` 使用 `{bucket_name}` 重新创建它。

# 使用标量 Python UDF 为 Amazon Redshift 查询结果设置特定于语言的排序
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf"></a>

*Ethan Stark，Amazon Web Services*

## Summary
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-summary"></a>

此模式提供了使用标量 Python UDF（用户定义的函数）为 Amazon Redshift 查询结果设置不区分大小写的语言排序的步骤和示例代码。有必要使用标量 Python UDF，因为 Amazon Redshift 返回基于二进制 UTF-8 排序的结果，并且不支持特定于语言的排序。Python UDF 是基于 Python 程序并在数据仓库运行的非 SQL 处理代码。您可在单个查询中使用 SQL 语句运行 Python UDF 代码。有关更多信息，请参阅[亚马逊 Redshift AWS 大数据 UDFs 中的 Python 简介](https://aws.amazon.com/blogs/big-data/introduction-to-python-udfs-in-amazon-redshift/)博客文章。

此模式中的示例数据基于土耳其字母表，用于演示目的。此模式中的标量 Python UDF 旨在使 Amazon Redshift 的默认查询结果符合土耳其语字符的语言顺序。有关更多信息，请参阅此模式的*其他信息*部分中的*土耳其语示例*。您可以用这种模式修改其他语言标量 Python UDF。

## 先决条件和限制
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-prereqs"></a>

**先决条件**
+ 带有数据库、架构和表的 [Amazon Redshift 集群](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html)
+ 具有 `CREATE TABLE` 和 `CREATE FUNCTION` 权限的 [Amazon Redshift 用户](https://docs.aws.amazon.com/redshift/latest/dg/r_Users.html)
+ [Python 2.7](https://www.python.org/download/releases/2.7/) 或更高版本

**限制**

此模式中的查询使用的语言排序不区分大小写。

## 工具
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-tools"></a>

**AWS 服务**
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html) 是一项在 AWS 云中托管的 PB 级数据仓库服务。Amazon Redshift 与数据湖集成，让您可以使用数据获得对您的业务和客户的新见解。

**其他工具**
+ [Python (UDFs) 用户定义的函数](https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-introduction.html)是可以用 Python 编写然后在 SQL 语句中调用的函数。

## 操作说明
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-epics"></a>

### 开发代码以按语言顺序对查询结果进行排序
<a name="develop-code-to-sort-query-results-in-linguistic-order"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为您的示例数据创建一个表。 | 要在 Amazon Redshift 中创建表并将示例数据插入到该表中，请使用以下 SQL 语句：<pre>CREATE TABLE my_table (first_name varchar(30));<br /><br />INSERT INTO my_table (first_name)<br />VALUES<br />    ('ali'),<br />    ('Ali'),<br />    ('ırmak'),<br />    ('IRMAK'),<br />    ('irem'),<br />    ('İREM'),<br />    ('oğuz'),<br />    ('OĞUZ'),<br />    ('ömer'),<br />    ('ÖMER'),<br />    ('sedat'),<br />    ('SEDAT'),<br />    ('şule'),</pre>示例数据中的名字包含土耳其字母表中的特殊字符。有关此示例中土耳其语注意事项的更多信息，请参阅此模式的*其他信息*部分中的*土耳其语示例*。 | 数据工程师 | 
| 检查样本数据默认排序。 | 若要在 Amazon Redshift 中查看示例数据的默认排序，请运行以下查询：<pre>SELECT first_name FROM my_table ORDER BY first_name;</pre>该查询返回您之前创建表中的名字列表：<pre>first_name<br />---------------<br />Ali<br />IRMAK<br />OĞUZ<br />SEDAT<br />ali<br />irem<br />oğuz<br />sedat<br />ÖMER<br />ömer<br />İREM<br />ırmak<br />ŞULE<br />şule</pre>查询结果的顺序不正确，因为默认二进制 UTF-8 排序不适应土耳其语特殊字符的语言顺序。 | 数据工程师 | 
| 创建标量 Python UDF。 | 若要创建标量 Python UDF，请使用以下 SQL 代码： <pre>CREATE OR REPLACE FUNCTION collate_sort (value varchar) <br />RETURNS varchar <br />IMMUTABLE <br />AS <br />$$    <br />    def sort_str(val):<br />        import string<br />        <br />        dictionary = {<br />            'I': 'ı', <br />            'ı': 'h~', <br />            'İ': 'i', <br />            'Ş': 's~', <br />            'ş': 's~', <br />            'Ğ': 'g~', <br />            'ğ': 'g~', <br />            'Ü': 'u~', <br />            'ü': 'u~', <br />            'Ö': 'o~', <br />            'ö': 'o~', <br />            'Ç': 'c~', <br />            'ç': 'c~'<br />        }<br />        <br />        for key, value in dictionary.items():<br />            val = val.replace(key, value)<br />        <br />        return val.lower()<br /> <br />    return sort_str(value)<br />    <br />$$ LANGUAGE plpythonu;</pre> | 数据工程师 | 
| 查询示例数据。 | 若要使用 Python UDF 查询示例数据，请运行以下 SQL 查询：<pre>SELECT first_name FROM my_table ORDER BY collate_sort(first_name);</pre>现在，查询以土耳其语顺序返回示例数据：<pre>first_name<br />---------------<br />ali<br />Ali<br />ırmak<br />IRMAK<br />irem<br />İREM<br />oğuz<br />OĞUZ<br />ömer<br />Ömer<br />sedat<br />SEDAT<br />şule<br />ŞULE</pre> | 数据工程师 | 

## 相关资源
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-resources"></a>
+ [ORDER BY 子句](https://docs.aws.amazon.com/redshift/latest/dg/r_ORDER_BY_clause.html)（Amazon Redshift 文档）
+ [创建标量 Python UDF](https://docs.aws.amazon.com/redshift/latest/dg/udf-creating-a-scalar-udf.html)（Amazon Redshift 文档）

## 附加信息
<a name="set-up-language-specific-sorting-for-amazon-redshift-query-results-using-a-scalar-python-udf-additional"></a>

**土耳其语示例**

Amazon Redshift 根据二进制 UTF-8 排序顺序（而不是特定于语言的排序顺序）返回查询结果。这意味着，如果您查询包含土耳其语字符的 Amazon Redshift 表，则查询结果不会根据土耳其语的语言顺序进行排序。土耳其语包含六个不出现在拉丁字母表中的特殊字符 (ç、ı、ğ、 ö、ş, 以及 ü)。这些特殊字符放置在基于二进制 UTF-8 排序的排序结果集的末尾，如下表所示。


| 
| 
| 二进制 UTF-8 排序 | 土耳其语语言排序 | 
| --- |--- |
| a | a | 
| b | b | 
| c | c | 
| d | **ç (\$1)** | 
| e | d | 
| f | e | 
| g | f | 
| h | g | 
| i | **ğ (\$1)** | 
| j | h | 
| k | **ı (\$1)** | 
| l | i | 
| m | j | 
| n | k | 
| o | l | 
| p | m | 
| r | n | 
| s | o | 
| t | **ö (\$1)** | 
| u | p | 
| v | r | 
| y | s | 
| z | **ş (\$1)** | 
| **ç (\$1)** | t | 
| **ğ (\$1)** | u | 
| **ı (\$1)** | **ü (\$1)** | 
| **ö (\$1)** | v | 
| **ş (\$1)** | y | 
| **ü (\$1)** | z | 

**注意**  
星号（\$1）表示土耳其语的特殊字符。

如上表所示，特殊字符 **ç** 在土耳其语语言排序中介于 **c** 和 **d** 之间，但在二进制 UTF-8 排序中在 **z** 之后。此模式中的标量 Python UDF 使用以下字符替换目录将土耳其语特殊字符替换为相应的拉丁语等效字符。


| 
| 
| 土耳其语特殊字符 | 拉丁语等效字符 | 
| --- |--- |
| ç | c\$1 | 
| ı | h\$1 | 
| ğ | g\$1 | 
| ö | o\$1 | 
| ş | s\$1 | 
| ü | u\$1 | 

**注意**  
波形符（\$1）字符附加到拉丁字符的末尾，以替换相应的土耳其语特殊字符。

**修改标量 Python UDF 函数**

要从此模式修改标量 Python UDF 函数，以便该函数接受定位参数并支持多事务字典，请使用以下 SQL 代码：

```
CREATE OR REPLACE FUNCTION collate_sort (value varchar, locale varchar) 
RETURNS varchar 
IMMUTABLE 
AS 
$$    
    def sort_str(val):
       import string
       # Turkish Dictionary
       if locale == 'tr-TR':
            dictionary = {
               'I': 'ı', 
               'ı': 'h~', 
               'İ': 'i', 
               'Ş': 's~', 
               'ş': 's~', 
               'Ğ': 'g~', 
               'ğ': 'g~', 
               'Ü': 'u~', 
               'ü': 'u~', 
               'Ö': 'o~', 
               'ö': 'o~', 
               'Ç': 'c~', 
               'ç': 'c~'
        }
        # German Dictionary
        if locale == 'de-DE':
            dictionary = {
               ....
               ....
        }
        
        for key, value in dictionary.items():
            val = val.replace(key, value)
        
        return val.lower()
 
    return sort_str(value)
    
$$ LANGUAGE plpythonu;
```

以下示例代码展示了如何查询修改后的 Python UDF：

```
SELECT first_name FROM my_table ORDER BY collate_order(first_name, 'tr-TR');
```

# 将 Lambda 函数，以接收来自不同 AWS 区域中的 S3 存储桶的事件通知
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions"></a>

*Suresh Konathala，Amazon Web Services*

*Andrew Preston 和 Arindom Sarkar，无*

## Summary
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-summary"></a>

[Amazon Simple Storage Service (Amazon S3) 事件通知](https://docs.aws.amazon.com/AmazonS3/latest/userguide/NotificationHowTo.html)会针对您的 S3 存储桶中的某些事件（例如，对象创建事件、对象移除事件或恢复对象事件）发布通知。您可使用 AWS Lambda 函数根据应用程序的要求处理这些通知。但是，Lambda 函数无法直接订阅来自不同 AWS 区域托管的 S3 存储桶的通知。

这种模式的方法通过为每个区域使用 Amazon Simple Notiﬁcation Service (Amazon SNS)主题，部署[扇出场景](https://docs.aws.amazon.com/sns/latest/dg/sns-common-scenarios.html)来处理来自跨区域 S3 存储桶的 Amazon S3 通知。这些区域 SNS 主题将 Amazon S3 事件通知发送到也包含您的 Lambda 函数的中央区域中的 Amazon Simple Queue Service (Amazon SQS) 队列。Lambda 函数订阅此 SQS 队列，并根据您组织的要求处理事件通知。

## 先决条件和限制
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 多个区域中的现有 S3 存储桶，包括用于托管 Amazon SQS 队列和 Lambda 函数的中央区域。
+ 已安装和配置 AWS 命令行界面（AWS CLI）。有关这方面的更多信息，请参阅 AWS CLI 文档中的[安装、更新和卸载 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)。 
+ 熟悉 Amazon SNS 的扇出场景。有关这方面的更多信息，请参阅 Amazon SNS 文档中的[常见 Amazon SNS 场景](https://docs.aws.amazon.com/sns/latest/dg/sns-common-scenarios.html)。

## 架构
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-architecture"></a>

下图显示了此模式的方法的架构。 

![\[工作流使用 Amazon SNS、S3 和 SQS 来处理来自跨区域 S3 存储桶的事件通知。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/cf6c1804-8c41-46f1-9f17-ff361708c595/images/760cf4c0-0cb3-48d1-92ae-1cf0fa8ae076.png)


下图显示了如下工作流：

1. Amazon S3 向同一区域的 SNS 主题发送有关 S3 存储桶（例如，已创建对象、删除对象或恢复对象）的事件通知。

1. SNS 主题将事件发布到中央区域的 SQS 队列。

1. SQS 队列配置为 Lambda 函数的事件源，并缓冲 Lambda 函数的事件消息。 

1. Lambda 函数轮询 SQS 队列中的消息，并根据您的应用程序的要求处理 Amazon S3 事件通知。

 

**技术堆栈**
+ Lambda
+ Amazon SNS
+ Amazon SQS
+ Amazon S3

## 工具
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-tools"></a>
+ [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) – AWS 命令行界面（AWS CLI）是一种开源工具，用于通过命令行 Shell 中的命令与 Amazon Web Services 交互。仅需最少的配置，即可使用 AWS CLI 开始运行命令，以便从终端程序中的命令提示符实现与基于浏览器的 AWS 管理控制台所提供的功能等同的功能。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) — AWS CloudFormation 可帮助您建模和设置 AWS 资源，快速一致地配置这些资源，并在资源的整个生命周期中对其进行管理。您可以使用模板来描述资源及其依赖关系，然后将它们作为堆栈一起启动和配置，而不必单独管理资源。您可以跨多个 AWS 账户和 AWS 区域管理和预调配堆栈。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) – AWS Lambda 是一项计算服务，支持无需预置或管理服务器即可运行代码。只有在需要时 Lambda 才运行您的代码，并且能自动扩缩，从每天几个请求扩展到每秒数千个请求。您只需为消耗的计算时间付费 - 代码未运行时不产生费用。
+ [Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) – Amazon Simple Notiﬁcation Service (Amazon SNS) 可协调和管理发布者和客户端之间消息的传送或发送，包括 Web 服务器和电子邮件地址。订阅用户接收所有发布至他们所订阅主题的消息，并且一个主题的所有订阅用户收到的消息都相同。
+ [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) – Amazon Simple Queue Service (Amazon SQS) 提供了一个安全、持久且可用的托管队列，以允许您集成和分离分布式软件系统与组件。Amazon SQS 支持标准队列和 FIFO 队列。

## 操作说明
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-epics"></a>

### 在您的中央区域创建 SQS 队列和 Lambda 函数
<a name="create-the-sqs-queue-and-lambda-function-in-your-central-region"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 Lambda 触发器创建 SQS 队列。 | 登录 AWS 管理控制台，按照 AWS Lambda 文档中的[将 Lambda 与 Amazon SQS 结合使用](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-example.html)教程中的说明在您的中央区域创建以下资源：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions.html)确保将 SQS 队列配置为您的 Lambda 函数的事件源。 | AWS DevOps，云架构师 | 

### 创建 SNS 主题，并为每个所需区域中的 S3 存储桶设置事件通知
<a name="create-an-sns-topic-and-set-up-event-notifications-for-the-s3-buckets-in-each-required-region"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  创建 SNS 主题以接收 Amazon S3 事件通知。 | 在您想要接收 Amazon S3 事件通知的区域中创建 SNS 主题。有关这方面的更多信息，请参阅 Amazon SNS 文档中的[创建 SNS 主题](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)。 确保记录您的 SNS 主题的 Amazon 资源名称（ARN）。  | AWS DevOps，云架构师 | 
| 为中央 SQS 队列订阅 SNS 主题。 | 为您的中央区域托管的 SQS 队列订阅您的 SNS 主题。有关这方面的更多信息，请参阅 Amazon SNS 文档中的[订阅 SNS 主题](https://docs.aws.amazon.com/sns/latest/dg/sns-create-subscribe-endpoint-to-topic.html)。 | AWS DevOps，云架构师 | 
| 更新 SNS 主题访问策略。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions.html)<pre>{<br />  "Version": "2012-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Sid": "0",<br />      "Effect": "Allow",<br />      "Principal": {<br />        "Service": "s3.amazonaws.com"<br />      },<br />      "Action": "sns:Publish",<br />      "Resource": "arn:aws:sns:us-west-2::s3Events-SNSTopic-us-west-2"<br />    }<br />  ]<br />}</pre> | AWS DevOps，云架构师 | 
| 为区域中的每个 S3 存储桶设置通知。 | 为区域中的每个 S3 存储桶设置事件通知。有关这方面的更多信息，请参阅 Amazon S3 文档中的[使用 Amazon S3 控制台启用和配置事件通知](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enable-event-notifications.html)。在**目标**部分中，选择 **SNS 主题**，并指定您之前创建的 SNS 主题的 ARN。 | AWS DevOps，云架构师 | 
| 在所需的各个区域中，重复此操作。 | 针对您希望从中接收 Amazon S3 事件通知的每个区域（包括您的中央区域），重复此操作说明中的任务。 | AWS DevOps，云架构师 | 

## 相关资源
<a name="subscribe-a-lambda-function-to-event-notifications-from-s3-buckets-in-different-aws-regions-resources"></a>
+ [配置访问策略](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-add-permissions.html)（Amazon SQS 文档）
+ [将 SQS 队列配置为事件源](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html#events-sqs-eventsource)（AWS Lambda 文档）
+ [配置 SQS 队列以启动 Lambda 函数](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-lambda-function-trigger.html)（Amazon SQS 文档）
+ [AWS::Lambda::Function 资源](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html)（AWS CloudFormation 文档）

# 三种用于将数据转换为 Apache Parquet 的 AWS Glue ETL 作业类型
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet"></a>

*Adnan Alvee、Nith Govindasivan 和 Karthikeyan Ramachandran，Amazon Web Services*

## Summary
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-summary"></a>

在 Amazon Web Services（AWS）Cloud 上，AWS Glue 是一项完全托管的提取、转换、加载（ETL）服务。AWS Glue 使您能够经济高效地对数据进行分类、清理和扩充，并在各种数据存储和数据流之间可靠地移动数据。

此模式在 AWS Glue 中提供了不同的作业类型，并使用三种不同的脚本来演示 ETL 作业的创作。

您可以使用 AWS Glue 在 Python Shell 环境中编写 ETL 作业。您还可以在托管 Apache Spark 环境中使用 Python (PySpark) 或 Scala 创建批处理和流式处理 ETL 作业。为了开始创作 ETL 作业，此模式侧重于使用 Python shell、和 Scala 的批处理 ETL 作业。 PySparkPython Shell 作业适用于需要较低计算能力的工作负载。托管 Apache Spark 环境适用于需要高计算能力的工作负载。

Apache Parquet 旨在支持高效的压缩和编码方案。它可以加快分析工作负载的速度，因为它以列式方式存储数据。从长远来看，将数据转换为 Parquet 可以为您节省存储空间、成本和时间。要详细了解 Parquet，请参阅博客文章 [Apache Parquet：如何使用开源列式数据格式成为大侠](https://blog.openbridge.com/how-to-be-a-hero-with-powerful-parquet-google-and-amazon-f2ae0f35ee04)。

## 先决条件和限制
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-prereqs"></a>

**先决条件**
+ AWS Identity and Access Management（IAM）角色（如果您没有角色，请参阅[其他信息](#three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-additional)部分）。

## 架构
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-architecture"></a>

**目标技术堆栈 **
+ AWS Glue
+ Amazon Simple Storage Service（Amazon S3）
+ Apache Parquet

**自动化和扩缩**
+ [AWS Glue 工作流程](https://docs.aws.amazon.com/glue/latest/dg/workflows_overview.html)支持 ETL 管线的完全自动化。
+ 您可以将数据处理单元的数量 (DPUs) 或工作器类型更改为水平和垂直扩展。

## 工具
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-tools"></a>

**Amazon Web Services**
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一项完全托管的 ETL 服务，用于在各种数据存储和数据流之间对数据进行分类、清理、扩充和移动。

**其他工具**
+ [Apache Parquet](https://parquet.apache.org/) 是一种专为存储和检索而设计的开源列式数据文件格式。

**配置**

使用以下设置来配置 AWS Glue ETL 的计算能力。要降低成本，请在运行此模式中提供的工作负载时使用最低设置。 
+ **Python Shell** – 您可以使用 1 个 DPU 来利用 16 GB 的内存，也可以使用 0.0625 DPU 来使用 1 GB 的内存。此模式使用 0.0625 DPU，这是 AWS Glue 控制台中的默认设置。
+ **Python 或 Scala for Spark** – 如果您在控制台中选择与 Spark 相关的作业类型，AWS Glue 默认使用 10 个 Worker 和 G.1X Worker 类型。这种模式使用两个 Worker（这是允许的最小数量），标准 Worker 类型足够且具有成本效益。

下表显示了 Apache Spark 环境的不同 AWS Glue Worker 类型。由于 Python Shell 作业不使用 Apache Spark 环境来运行 Python，因此它未包含在表中。


| 
| 
|  | 标准 | G.1X | G.2X | 
| --- |--- |--- |--- |
| vCPU | 4 | 4 | 8 | 
| 内存 | 16 GB | 16 GB | 32 GB | 
| 磁盘空间 | 50 GB | 64 GB | 128 GB | 
| 每个工作线程的执行程序 | 2 | 1  | 1 | 

**代码**

有关此模式中使用的代码，包括 IAM 角色和参数配置，请参阅[其他信息](#three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-additional)部分。

## 操作说明
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-epics"></a>

### 上传数据
<a name="upload-the-data"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将数据上传到新的或现有 S3 存储桶。 | 在账户中创建 S3 存储桶或使用现有 S3 存储桶。从[附件](#attachments-8c926709-8fa4-417f-9aaf-bcc8113d018f)部分上传 sample\$1data.csv 文件，并记下 S3 存储桶和前缀位置。 | 常规 AWS | 

### 创建并运行 AWS Glue 作业
<a name="create-and-run-the-aws-glue-job"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 AWS Glue 作业。 | 在 AWS Glue 控制台的 ETL 部分下方，添加一个 AWS Glue 作业。选择相应的工作类型、AWS Glue 版本以及相应的工作人员 DPU/Worker 类型和数量。有关详细信息，请参阅*配置*部分。 | 开发人员、云或数据 | 
| 更改输入和输出位置。 | 复制与 AWS Glue 作业对应的代码，然后更改您在**上传数据**操作说明中记下的输入和输出位置。 | 开发人员、云或数据 | 
| 配置参数。 | 您可以使用[其他信息](#three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-additional)部分中提供的片段为 ETL 作业设置参数。AWS Glue 在内部使用四个参数名称：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet.html)必须在 AWS Glue 控制台上明确输入该 `--JOB_NAME`参数。选择**作业**、**编辑作业**、**安全配置、脚本库和作业参数（可选）**。输入 `--JOB_NAME` 作为密钥并提供一个值。您也可以使用 AWS 命令行界面（AWS CLI）或 AWS Glue API 来设置此参数。Spark 使用该 `--JOB_NAME` 参数，在 Python Shell 环境作业中不需要该参数。必须在每个参数名称之前添加 `--`；否则，代码将无法运行。例如，对于代码片段，位置参数必须由 `--input_loc` 和 `--output_loc` 调用。 | 开发人员、云或数据 | 
| 运行 ETL 作业。 | 运行作业并检查输出。注意与原始文件相比减少了多少空间。 | 开发人员、云服务或数据 | 

## 相关资源
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-resources"></a>

**参考**
+ [Apache Spark](https://spark.apache.org/)
+ [AWS Glue：工作原理](https://docs.aws.amazon.com/glue/latest/dg/how-it-works.html)
+ [AWS Glue 定价](https://aws.amazon.com/glue/pricing/)

**教程和视频**
+ [什么是 AWS Glue？](https://www.youtube.com/watch?v=qgWMfNSN9f4)

## 附加信息
<a name="three-aws-glue-etl-job-types-for-converting-data-to-apache-parquet-additional"></a>

**IAM 角色**

创建 AWS Glue 作业时，您可以使用具有以下代码片段所示权限的现有 IAM 角色或新角色。

要创建新角色，请使用以下 YAML 代码。

```
# (c) 2022 Amazon Web Services, Inc. or its affiliates. All Rights Reserved. This AWS Content is provided subject to the terms of the AWS Customer
# Agreement available at https://aws.amazon.com/agreement/ or other written agreement between Customer and Amazon Web Services, Inc.

AWSTemplateFormatVersion: "2010-09-09"

Description: This template will setup IAM role for AWS Glue service.

Resources:
  rGlueRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Service:
                - "glue.amazonaws.com"
            Action:
              - "sts:AssumeRole"
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSGlueServiceRole
      Policies:
        - PolicyName: !Sub "${AWS::StackName}-s3-limited-read-write-inline-policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - "s3:PutObject"
                  - "s3:GetObject"
                Resource: "arn:aws:s3:::*/*"
      Tags:
        - Key  : "Name"
          Value : !Sub "${AWS::StackName}"

Outputs:
  oGlueRoleName:
    Description: AWS Glue IAM role
    Value:
      Ref: rGlueRole
    Export:
      Name: !Join [ ":", [ !Ref "AWS::StackName", rGlueRole ] ]
```

**AWS Glue (Python Shell)**

Python 代码使用 Pandas 和 PyArrow 库将数据转换为 Parquet。Pandas 库已经可用。该 PyArrow 库是在你运行模式时下载的，因为这是一次性运行。您可以使用 wheel 文件 PyArrow 转换为库并将该文件作为库包提供。有关打包 Wheel 文件的更多信息，请参阅[提供您自己的 Python 库](https://docs.aws.amazon.com/glue/latest/dg/add-job-python.html)。

*AWS Glue Python Shell 参数*

```
from awsglue.utils import getResolvedOptions

args = getResolvedOptions(sys.argv, ["input_loc", "output_loc"])
```

*AWS Glue（Python Shell）代码*

```
from io import BytesIO
import pandas as pd
import boto3
import os
import io
import site
from importlib import reload
from setuptools.command import easy_install
install_path = os.environ['GLUE_INSTALLATION']
easy_install.main( ["--install-dir", install_path, "pyarrow"] )
reload(site)
import pyarrow


input_loc = "s3://bucket-name/prefix/sample_data.csv"
output_loc = "s3://bucket-name/prefix/"


input_bucket = input_loc.split('/', 1)[0]
object_key = input_loc.split('/', 1)[1]


output_loc_bucket = output_loc.split('/', 1)[0]
output_loc_prefix = output_loc.split('/', 1)[1] 


s3 = boto3.client('s3')
obj = s3.get_object(Bucket=input_bucket, Key=object_key)
df = pd.read_csv(io.BytesIO(obj['Body'].read()))


parquet_buffer = BytesIO()
s3_resource = boto3.resource('s3')
df.to_parquet(parquet_buffer, index=False) 
s3_resource.Object(output_loc_bucket, output_loc_prefix +  'data' + '.parquet').put(Body=parquet_buffer.getvalue())
```

**使用 Python 的 AWS Glue Spark 作业**

要在 Python 中使用 AWS Glue Spark 作业类型，请选择 **Spark** 作为作业类型。选择**作业启动时间缩短的 Spark 3.1、Python 3（Glue 版本 3.0）**作为 AWS Glue 版本。

*AWS Glue Python 参数*

```
from awsglue.utils import getResolvedOptions

args = getResolvedOptions(sys.argv, ["JOB_NAME", "input_loc", "output_loc"])
```

*使用 Python 代码的 AWS Glue Spark 作业*

```
import sys
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.transforms import *
from awsglue.dynamicframe import DynamicFrame
from awsglue.utils import getResolvedOptions
from awsglue.job import Job


sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)

input_loc = "s3://bucket-name/prefix/sample_data.csv"
output_loc = "s3://bucket-name/prefix/"

inputDyf = glueContext.create_dynamic_frame_from_options(\
    connection_type = "s3", \
    connection_options = { 
        "paths": [input_loc]}, \
    format = "csv",
    format_options={
        "withHeader": True,
        "separator": ","
    })


outputDF = glueContext.write_dynamic_frame.from_options(\
    frame = inputDyf, \
    connection_type = "s3", \
    connection_options = {"path": output_loc \
        }, format = "parquet")
```

对于大量压缩的大文件（例如，1,000 个文件，每个文件约为 3 MB），请使用带有 `recurse` 参数的 `compressionType` 参数读取前缀内的所有可用文件，如以下代码所示。

```
input_loc = "bucket-name/prefix/"
output_loc = "bucket-name/prefix/"

inputDyf = glueContext.create_dynamic_frame_from_options(
                    connection_type = "s3", 
                    connection_options = {"paths": [input_loc], 
                                            "compressionType":"gzip","recurse" :"True",
                                            },
                    format = "csv",
                    format_options={"withHeader": True,"separator": ","}
                    )
```

对于大量压缩的小文件（例如，1,000 个文件，每个文件大小约为 133 KB），请使用 `groupFiles` 参数以及 `compressionType` 和 `recurse` 参数。`groupFiles` 参数将小文件分组为多个大文件，`groupSize` 参数将分组控制为以字节为单位的指定大小（例如，1 MB）。以下代码片段提供了在代码中使用这些参数的示例。

```
input_loc = "bucket-name/prefix/"
output_loc = "bucket-name/prefix/"

inputDyf = glueContext.create_dynamic_frame_from_options(
                    connection_type = "s3", 
                    connection_options = {"paths": [input_loc], 
                                            "compressionType":"gzip","recurse" :"True",
                                             "groupFiles" :"inPartition",  "groupSize" :"1048576",
                                            },
                    format = "csv",
                    format_options={"withHeader": True,"separator": ","}
                    )
```

无需对 Worker 节点进行任何更改，这些设置就使 AWS Glue 作业可以读取多个文件（大或小，有或没有压缩），然后以 Parquet 格式将它们写入目标。

**使用 Scala 的 AWS Glue Spark 作业**

要在 Scala 中使用 AWS Glue Spark 作业类型，请选择 **Spark** 作为作业类型，选择**语言**作为 **Scala**。选择**作业启动时间缩短的 Spark 3.1、Scala 2（Glue 版本 3.0）**作为 AWS Glue 版本。为了节省存储空间，以下 Scala 示例中的 AWS Glue 还使用该 `applyMapping` 功能来转换数据类型。

*AWS Glue Scala 参数*

```
import com.amazonaws.services.glue.util.GlueArgParser val args = GlueArgParser.getResolvedOptions(sysArgs, Seq("JOB_NAME", "inputLoc", "outputLoc").toArray)
```

*使用 Scala 代码的 AWS Glue Spark 作业*

```
import com.amazonaws.services.glue.GlueContext
import com.amazonaws.services.glue.MappingSpec
import com.amazonaws.services.glue.DynamicFrame
import com.amazonaws.services.glue.errors.CallSite
import com.amazonaws.services.glue.util.GlueArgParser
import com.amazonaws.services.glue.util.Job
import com.amazonaws.services.glue.util.JsonOptions
import org.apache.spark.SparkContext
import scala.collection.JavaConverters._


object GlueScalaApp {
  def main(sysArgs: Array[String]) {
    
    @transient val spark: SparkContext = SparkContext.getOrCreate()
    val glueContext: GlueContext = new GlueContext(spark)

    val inputLoc = "s3://bucket-name/prefix/sample_data.csv"
    val outputLoc = "s3://bucket-name/prefix/"

    val readCSV = glueContext.getSource("csv", JsonOptions(Map("paths" -> Set(inputLoc)))).getDynamicFrame()

    val applyMapping = readCSV.applyMapping(mappings = Seq(("_c0", "string", "date", "string"), ("_c1", "string", "sales", "long"),
    ("_c2", "string", "profit", "double")), caseSensitive = false)

    val formatPartition = applyMapping.toDF().coalesce(1)

    val dynamicFrame = DynamicFrame(formatPartition, glueContext)

    val dataSink = glueContext.getSinkWithFormat(
        connectionType = "s3", 
        options = JsonOptions(Map("path" -> outputLoc )),
        transformationContext = "dataSink", format = "parquet").writeDynamicFrame(dynamicFrame)
  }
}
```

## 附件
<a name="attachments-8c926709-8fa4-417f-9aaf-bcc8113d018f"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/8c926709-8fa4-417f-9aaf-bcc8113d018f/attachments/attachment.zip)

# 使用亚马逊 Athena 和亚马逊可视化 Amazon Redshift 审计日志 QuickSight
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight"></a>

*Sanket Sirsikar 和 Gopal Krishna Bhatia，Amazon Web Services*

## Summary
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-summary"></a>

安全性是 Amazon Web Services（AWS）云上数据库操作不可或缺的一部分。您的组织应确保监视数据库用户活动和连接，以检测潜在的安全事件和风险。此模式有助于您监控数据库以确保安全并进行故障排除，该流程通常称为数据库审计。

 此模式提供了一个 SQL 脚本，可以自动创建 Amazon Athena 表和亚马逊报告控制面板的视图，从而帮助您审计 A QuickSight mazon Redshift 日志。这可确保负责监控数据库活动的用户能够方便地访问数据安全功能。 

## 先决条件和限制
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 现有 Amazon Redshift 集群。有关更多信息，请参阅 Amazon Redshift 文档中的[创建 Amazon Redshift 集群](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-data-launch-cluster.html)。
+ 访问现有 Athena 工作组。有关更多信息，请参阅 Amazon Athena 文档中的工作组的[工作原理](https://docs.aws.amazon.com/athena/latest/ug/user-created-workgroups.html)。 
+ 具有所需 AWS Identity and Access Management（IAM）权限的现有 Amazon Simple Storage Service（Amazon S3）源存储桶。有关更多信息，请参阅 Amazon Redshift 文档中的[数据库审计日志](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html)记录中的 [Amazon Redshift 审计日志记录的存储桶权限](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html#db-auditing-bucket-permissions)。

## 架构
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-architecture"></a>

![\[Data flow diagram showing Amazon Redshift, logs, S3 bucket, Amazon Athena, and Amazon Quick.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/90e69009-001e-4ced-bef0-3c361f93ae87/images/9fde7f01-17ab-4207-8a59-a12daf85a382.png)


 

**技术堆栈 **
+ Athena
+ Amazon Redshift 
+ Amazon S3 
+ QuickSight

## 工具
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-tools"></a>
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) – Athena 是一种交互式查询服务，方便使用标准 SQL 分析 Amazon S3 的数据。 
+ [Amazon QuickSight](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) — QuickSight 是一项可扩展、无服务器、可嵌入、由机器学习提供支持的商业智能 (BI) 服务。 
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html) – Amazon Redshift 是一种完全托管的企业 PB 级数据仓库服务。 
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一项面向互联网的存储服务。

## 操作说明
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-epics"></a>

### 配置 Amazon Redshift 集群
<a name="configure-the-amazon-redshift-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  为 Amazon Redshift 集群启用审计日志记录。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight.html) | 数据库管理员、数据工程师 | 
| 在 Amazon Redshift 集群参数组中启用日志记录。 | 您可以使用 AWS 管理控制台、Amazon Redshift API 参考或 AWS 命令行界面（AWS CLI）同时启用对连接日志、用户日志和用户活动日志的审计。 要审计用户活动日志，您还必须启用 `enable_user_activity_logging` 数据库参数。如果您仅启用审计日志记录功能，但不启用相关参数，则数据库审计日志将仅为连接日志和用户日志记录信息，而不为用户活动日志记录信息。默认情况下未启用 `enable_user_activity_logging` 参数，但可以将它从 `false` 更改为 `true` 以便启用它。您需要使用已启用的 `user_activity_logging` 参数创建一个新的集群参数组，并将它附加到 Amazon Redshift 集群。有关详情，请参阅 Amazon Redshift 文档中的[修改集群](https://docs.aws.amazon.com/redshift/latest/mgmt/managing-clusters-console.html#modify-cluster)。有关此任务的更多信息，请参阅 Amazon Redshift 文档中的 [Amazon Redshift 参数组](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html)和[使用控制台配置审计](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing-console.html)。 | 数据库管理员、数据工程师 | 
| 为 Amazon Redshift 集群日志记录配置 S3 存储桶权限。 | 当您启用日志记录时，Amazon Redshift 会收集日志记录信息并将其上载到 S3 存储桶中存储的日志文件。您可以使用现有的 S3 存储桶，也可以创建一个新的存储桶。确保 Amazon Redshift 具有访问 S3 存储桶所需的 IAM 权限。有关这方面的更多信息，请参阅 Amazon Redshift 文档中的[数据库审计日志记录](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html)中的 [Amazon Redshift 审计日志记录的存储桶权限](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html#db-auditing-bucket-permissions)。 | 数据库管理员、数据工程师 | 

### 创建 Athena 表和视图
<a name="create-the-athena-table-and-views"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Athena 表和视图以从 S3 存储桶查询 Amazon Redshift 审计日志数据。 | 打开 Amazon Athena 控制台，并使用 `AuditLogging.sql` SQL 脚本（附加）中的数据定义语言（DDL）查询为用户活动日志、用户日志和连接日志创建表和视图。有关更多信息和说明，请参阅 Amazon Athena 研讨会中的[创建表和运行查询](https://athena-in-action.workshop.aws/30-basics/301-create-tables.html)教程。 | 数据工程师 | 

### 在 QuickSight 控制面板中设置日志监控
<a name="set-up-log-monitoring-in-the-quicksight-dashboard"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 Athena 作为数据源创建 QuickSight 控制面板。 | 打开亚马逊 QuickSight 控制台，按照亚马逊 Athena 研讨会的 “[ QuickSight 使用 Athena 进行可视化](https://athena-in-action.workshop.aws/30-basics/307-quicksight.html)” 教程中的说明创建控制 QuickSight 面板。 | 数据库管理员、数据工程师 | 

## 相关资源
<a name="visualize-amazon-redshift-audit-logs-using-amazon-athena-and-amazon-quicksight-resources"></a>
+ [在 Athena 中创建表并运行查询](https://athena-in-action.workshop.aws/30-basics/301-create-tables.html)
+ [ QuickSight 使用 Athena 进行可视化](https://athena-in-action.workshop.aws/30-basics/307-quicksight.html)

## 附件
<a name="attachments-90e69009-001e-4ced-bef0-3c361f93ae87"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/90e69009-001e-4ced-bef0-3c361f93ae87/attachments/attachment.zip)

# 使用 Amazon Quick Sight 可视化所有 AWS 账户的 IAM 凭证报告
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight"></a>

*Parag Nagwekar 和 Arun Chandapillai，Amazon Web Services*

## Summary
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-summary"></a>


| 
| 
| 警告：IAM 用户具有长期凭证，这会带来安全风险。为帮助减轻这种风险，我们建议仅向这些用户提供执行任务所需的权限，并在不再需要这些用户时将其移除。 | 
| --- |

您可以使用 AWS Identity and Access Management（IAM）凭证报告，帮助您满足贵组织的安全、审计和合规要求。[凭证报告](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html)提供您 AWS 账户中所有用户的列表，并显示他们的凭证状态，如密码、访问密钥和多重身份验证（MFA）设备。您可以为由 [AWS Organizations](https://docs.aws.amazon.com/whitepapers/latest/organizing-your-aws-environment/core-concepts.html) 管理的多个 AWS 账户使用凭证报告。

此模式包括步骤和代码，可帮助您使用 Amazon Quick Sight 控制面板为组织中的所有 AWS 账户创建和共享 IAM 证书报告。您可以与组织中的利益相关者共享控制面板。这些报告可帮助您的组织实现以下目标业务成果：
+ 识别与 IAM 用户相关的安全事件
+ 追踪 IAM 用户向单点登录（SSO）身份验证的实时迁移
+ 追踪 IAM 用户访问的 AWS 区域
+ 保持合规
+ 与其他利益相关者共享信息

## 先决条件和限制
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户
+ 具有成员账户的[组织](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_tutorials_basic.html)。
+ 有权访问 Organizations 中账户的 [IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html)
+ 已[安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html#getting-started-install-instructions)和[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) AWS 命令行界面（AWS CLI）版本 2。
+ [订阅](https://docs.aws.amazon.com/quicksight/latest/user/signing-up.html) A [mazon Quick 企业版](https://docs.aws.amazon.com/quicksight/latest/user/editions.html)

## 架构
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-architecture"></a>

**技术堆栈**
+ Amazon Athena
+ Amazon EventBridge
+ Amazon Quick Sight
+ Amazon Simple Storage Service（Amazon S3）
+ AWS Glue
+ AWS Identity and Access Management（IAM）
+ AWS Lambda
+ AWS Organizations

**目标架构**

下图显示了用于设置从多个 AWS 账户捕获 IAM 凭证报告数据的工作流架构。

![\[下面的屏幕截图阐明了架构图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/8724ff28-40f6-4c43-9c65-fbd18bbbfd0f/images/e780916a-4ab7-4fdc-8ecc-c837c7d90d13.png)


1. EventBridge 每天调用 Lambda 函数。

1. Lambda 函数在整个组织的每个 AWS 账户中扮演 IAM 角色。然后，该函数创建 IAM 凭证报告，并将报告数据存储在集中式 S3 存储桶中。必须在 S3 存储桶上启用加密，并停用公共访问。

1. AWS Glue 爬网程序每天都会爬取 S3 存储桶，并相应地更新 Athena 表。

1. Quick Sight 导入和分析证书报告中的数据，并构建一个可由利益相关者可视化并与其共享的仪表板。

## 工具
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-tools"></a>

**Amazon Web Services**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一种交互式查询服务，方便使用标准 SQL 分析 Amazon S3 的数据。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一项无服务器事件总线服务，可帮助您将应用程序与来自各种来源的实时数据连接起来。例如，Lambda 函数、使用 API 目标的 HTTP 调用端点或其他 AWS 账户中的事件总线。
+ [Amazon Quick Sight](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) 是一种云级商业智能（BI）服务，可用于在单独的控制面板中可视化、分析和报告数据。Quick Sight 是 Amazon Quick 的核心组件，提供交互式数据可视化、SPICE 内存分析、嵌入式分析和仪表板共享。
+ [AWS Identity and Access Management (AWS IAM) ](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)通过控制验证和授权使用您 AWS 资源的用户，帮助您安全地管理对您 AWS 资源的访问。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，而无需预置或管理服务器。它仅在需要时运行您的代码，并且能自动扩缩，因此您只需为使用的计算时间付费。

**代码**

此模式的代码可在 GitHub [getiamcredsreport-allaccounts-org](https://github.com/aws-samples/getiamcredsreport-allaccounts-org)存储库中找到。您可以使用此存储库中的代码在 Organizations 的 AWS 账户中创建 IAM 凭证报告，并将其存储至中心位置。

## 操作说明
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-epics"></a>

### 设置基础设施
<a name="set-up-the-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 Amazon Quick 企业版。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html) | AWS 管理员、AWS DevOps、云管理员、云架构师 | 
| 将 Amazon Quick Sight 与亚马逊 S3 和 Athena 集成。 | 在部署 AWS 堆栈之前，您必须[授权](https://docs.aws.amazon.com/quicksight/latest/user/troubleshoot-connect-to-datasources.html) Quick Sight 使用 Amazon S3 和 Athena。 CloudFormation  | AWS 管理员、AWS DevOps、云管理员、云架构师 | 

### 部署基础设施
<a name="deploy-the-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆 GitHub 存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html) | AWS 管理员 | 
| 部署基础设施。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html) | AWS 管理员 | 
| 创建 IAM 权限策略。 | 使用以下权限，为组织中的每个 AWS 账户[创建 IAM 策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html)：<pre>{<br />  "Version": "2012-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Effect": "Allow",<br />      "Action": [<br />        "iam:GenerateCredentialReport",<br />        "iam:GetCredentialReport"<br />        ],<br />      "Resource": "*"<br />    }<br />  ]<br />}</pre> | AWS DevOps、云管理员、云架构师、数据工程师 | 
| 创建带有信任策略的 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html)<pre>{<br />   "Version": "2012-10-17",		 	 	 <br />   "Statement":[<br />      {<br />         "Effect":"Allow",<br />         "Principal":{<br />            "AWS":[<br />               "arn:aws:iam::<MasterAccountID>:role/<LambdaRole>"<br />            ]<br />         },<br />         "Action":"sts:AssumeRole"<br />      }<br />   ]<br />}</pre>请将 `arn:aws:iam::<MasterAccountID>:role/<LambdaRole>` 替换为您之前记下的 Lambda 角色的 ARN。各个组织通常使用自动化技术，为他们的 AWS 账户创建 IAM 角色。建议您使用此自动化技术（如果有）。或者，您可以使用****代码存储库中的 `CreateRoleforOrg.py` 脚本。该脚本需要现有的管理角色，或任何其他有权在每个 AWS 账户中创建 IAM 策略和角色的 IAM 角色。 | 云管理员、云架构师、AWS 管理员 | 
| 配置 Amazon Quick Sight 以可视化数据。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight.html) | AWS DevOps、云管理员、云架构师、数据工程师 | 

## 附加信息
<a name="visualize-iam-credential-reports-for-all-aws-accounts-using-amazon-quicksight-additional"></a>

**其他注意事项**

请考虑以下事项：
+ 使用 CloudFormation 部署基础设施后，您可以等待在 Amazon S3 中创建并由 Athena 分析的报告，直到 Lambda 和 AWS Glue 按计划运行。或者，您可手动运行 Lambda 在 Amazon S3 中获取报告，然后运行 AWS Glue 爬网程序，以获取根据数据创建的 Athena 表。
+ Quick 是一款强大的工具，可根据您的业务需求分析和可视化数据。您可以使用 Quick 中的[参数](https://docs.aws.amazon.com/quicksight/latest/user/parameters-in-quicksight.html)根据您选择的数据字段来控制控件数据。此外，您还可以使用快速分析从数据集中创建参数（例如，账户、日期和用户字段，`user`分别为`partition_0``partition_1`、和），以添加帐户、日期和用户的参数控件。
+ 要构建您自己的 Quick Sight 控制面板，请参阅 AWS Workshop Studio 网站上的[快速研讨会](https://catalog.workshops.aws/quicksight/en-US)。
+ 要查看 Quick Sight 仪表板示例，请参阅 GitHub [getiamcredsreport-allaccounts-org](https://github.com/aws-samples/getiamcredsreport-allaccounts-org)代码存储库。

**目标业务成果**

您可以使用此模式来实现以下目标业务成果：
+ **识别与 IAM 用户相关的安全事件** — 使用单一控制面板调查组织每个 AWS 账户的每个用户。您可跟踪 IAM 用户最近访问的各个 AWS 区域及其使用的服务的趋势。
+ **跟踪 IAM 用户向 SSO 身份验证的实时迁移** — 通过使用 SSO，用户可使用单个凭证登录一次并访问多个 AWS 账户和应用程序。如果您计划将 IAM 用户迁移至 SSO，此模式可以帮助您过渡到 SSO，并追踪所有 AWS 账户中的所有 IAM 用户凭证使用情况（例如访问 AWS 管理控制台或访问密钥的使用情况）。
+ **追踪 IAM 用户访问的 AWS 区域** — 您可出于各种目的控制 IAM 用户对区域的访问权限，例如数据主权和成本控制。您还可追踪任何 IAM 用户对区域的使用情况。
+ **保持合规** — 遵循最低权限原则，您只能授予执行特定任务所需 IAM 权限。此外，您还可以跟踪对 Amazon Web Services 的访问权限、AWS 管理控制台以及长期凭证的使用情况。
+ **与其他利益相关者共享信息** — 您可以与其他利益相关者共享精心策划的控制面板，无需授予他们访问 IAM 凭证报告或 AWS 账户的权限。

# 更多模式
<a name="analytics-more-patterns-pattern-list"></a>

**Topics**
+ [使用 Amazon Cognito 和 AWS Amplify UI 对现有 React 应用程序用户执行身份验证](authenticate-react-app-users-cognito-amplify-ui.md)
+ [使用 Amazon Textract 从 PDF 文件中自动提取内容](automatically-extract-content-from-pdf-files-using-amazon-textract.md)
+ [在 Amazon A SageMaker I Studio Lab 中使用 Deepar 计算时间序列构建冷启动预测模型](build-a-cold-start-forecasting-model-by-using-deepar.md)
+ [使用 AWS Cost Explorer 成本管理服务为 Amazon EMR 集群创建详细的成本和使用情况报告](create-detailed-cost-and-usage-reports-for-amazon-emr-clusters-by-using-aws-cost-explorer.md)
+ [为 Amazon RDS 和 Amazon Aurora 创建详细的成本和使用情况报告](create-detailed-cost-and-usage-reports-for-amazon-rds-and-amazon-aurora.md)
+ [使用 AWS Cost Explorer 成本管理服务为 AWS Glue 作业创建详细的成本和使用情况报告](create-detailed-cost-and-usage-reports-for-aws-glue-jobs-by-using-aws-cost-explorer.md)
+ [使用 Kinesis Data Streams 和 Firehose 将 DynamoDB 记录传送到亚马逊 S3 AWS CDK](deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk.md)
+ [使用 AWS CodePipeline CI/CD 管道部署 AWS Glue 作业](deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline.md)
+ [使用 Amazon Cognito 和 iaC 自动化将 Amazon Quick Sight 视觉组件嵌入到网络应用程序中](embed-quick-sight-visual-components-into-web-apps-cognito-iac.md)
+ [估算 Amazon DynamoDB 表的存储成本](estimate-storage-costs-for-an-amazon-dynamodb-table.md)
+ [使用 Terraform 执行 Amazon Redshift SQL 查询](execute-redshift-sql-queries-using-terraform.md)
+ [提取和查询 AWS IoT SiteWise 数据湖中的元数据属性](extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake.md)
+ [在 Quick Sight 中使用 AWS Mainframe Modernization 和 Amazon Q 生成数据见解](generate-data-insights-by-using-aws-mainframe-modernization-and-amazon-q-in-quicksight.md)
+ [在 Quick Sight 中使用 AWS Mainframe Modernization 和 Amazon Q 生成 Db2 z/OS 数据见解](generate-db2-zos-data-insights-aws-mainframe-modernization-amazon-q-in-quicksight.md)
+ [为 SageMaker 笔记本实例提供对另一个 AWS 账户中 CodeCommit 存储库的临时访问权限](give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.md)
+ [在 Amazon Data Firehose 资源未使用密钥加密时进行识别并发出警报 AWS KMS](identify-and-alert-when-amazon-data-firehose-resources-are-not-encrypted-with-an-aws-kms-key.md)
+ [将 psycopg2 库导入到以与你的 PostgreS AWS Lambda QL 数据库进行交互](import-psycopg2-library-lambda.md)
+ [在 Microsoft Sentinel 中摄取和分析 AWS 安全日志](ingest-analyze-aws-security-logs-sentinel.md)
+ [使用 AWS DMS 在 SSL 模式下将 Amazon RDS for Oracle 迁移到 Amazon RDS for PostgreSQL](migrate-amazon-rds-for-oracle-to-amazon-rds-for-postgresql-in-ssl-mode-by-using-aws-dms.md)
+ [使用 Oracle GoldenGate 平面文件适配器将 Oracle 数据库迁移到 Amazon RDS for Oracle](migrate-an-oracle-database-to-amazon-rds-for-oracle-by-using-oracle-goldengate-flat-file-adapters.md)
+ [使用 AWS DMS 和 AWS SCT 将 Oracle 数据库迁移至 Amazon Redshift](migrate-an-oracle-database-to-amazon-redshift-using-aws-dms-and-aws-sct.md)
+ [使用 PrivateLink 适用于 Amazon S3 的 DistCp AWS 将数据从本地 Hadoop 环境迁移到 Amazon S3](migrate-data-from-an-on-premises-hadoop-environment-to-amazon-s3-using-distcp-with-aws-privatelink-for-amazon-s3.md)
+ [从 Couchbase Server 迁移至 AWS 上的 Couchbase Capella](migrate-from-couchbase-server-to-couchbase-capella-on-aws.md)
+ [将本地 Cloudera 工作负载迁移到 Cloudera Data Platform on AWS](migrate-on-premises-cloudera-workloads-to-cloudera-data-platform-on-aws.md)
+ [使用应用程序恢复控制器管理 EMR 集群的多可用区失效转移](multi-az-failover-spark-emr-clusters-arc.md)
+ [使用 IaC 原则自动 blue/green 部署 Amazon Aurora 全球数据库](p-automate-blue-green-deployments-aurora-global-databases-iac.md)
+ [使用 GitHub 操作基于 AWS CloudFormation 模板配置 AWS Service Catalog 产品](provision-aws-service-catalog-products-using-github-actions.md)
+ [AWS Glue 使用 pytest 框架对 Python ETL 作业运行单元测试](run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.md)
+ [为 AWS 设置一个 Grafana 监控控制面板 ParallelCluster](set-up-a-grafana-monitoring-dashboard-for-aws-parallelcluster.md)
+ [将不同账户中的 Amazon Redshift 集群中的数据卸载到 Amazon S3](unload-data-from-amazon-redshift-cross-accounts-to-amazon-s3.md)
+ [使用 Flask 实现 AI/ML 模型结果的可视化以及 AWS Elastic Beanstalk](visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.md)