

# BigQuery 连接
<a name="aws-glue-programming-etl-connect-bigquery-home"></a>

在 AWS Glue 4.0 及更高版本中，您可以使用 AWS Glue for Spark 在 Google BigQuery 中读取和写入表。您可以通过 Google SQL 查询从 BigQuery 中读取。您可以通过 AWS Glue 连接使用存储在 AWS Secrets Manager 中的凭证连接到 BigQuery。

有关 Google BigQuery 的更多信息，请参见 [Google Cloud BigQuery 网站](https://cloud.google.com/bigquery)。

## 配置 BigQuery 连接
<a name="aws-glue-programming-etl-connect-bigquery-configure"></a>

要从 AWS Glue 中连接到 Google BigQuery，您需要创建 Google Cloud Platform 凭证并将其存储在 AWS Secrets Manager 密钥中，然后将该密钥与 Google BigQuery AWS Glue 连接关联。

**要配置与 BigQuery 的连接：**

1. 在 Google Cloud Platform，创建并识别相关资源：
   + 创建或标识包含您想要连接的 BigQuery 表的 GCP 项目。
   + 启用 BigQuery API。有关更多信息，请参阅[使用 BigQuery 存储读取 API 读取表数据](https://cloud.google.com/bigquery/docs/reference/storage/#enabling_the_api)。

1. 在 Google Cloud Platform 中，创建和导出服务账户凭证：

   您可以使用 BigQuery 凭证向导来加快此步骤：[创建凭证](https://console.cloud.google.com/apis/credentials/wizard?api=bigquery.googleapis.com)。

   要在 GCP 中创建服务账户，请按照[创建服务账户](https://cloud.google.com/iam/docs/service-accounts-create)中的教程进行操作。
   + 选择**项目**时，请选择包含您的 BigQuery 表的项目。
   + 为您的服务账户选择 GCP IAM 角色时，请添加或创建一个角色，该角色将授予运行 BigQuery 作业的相应权限，以读取、写入或创建 BigQuery 表。

   要为您的服务账户创建凭证，请按照[创建服务账户密钥](https://cloud.google.com/iam/docs/keys-create-delete#creating)中的教程进行操作。
   + 在选择密钥类型时，请选择 **JSON**。

   现在，您应该已经下载了包含服务账户凭证的 JSON 文件。如下所示：

   ```
   {
     "type": "service_account",
     "project_id": "*****",
     "private_key_id": "*****",
     "private_key": "*****",
     "client_email": "*****",
     "client_id": "*****",
     "auth_uri": "https://accounts.google.com/o/oauth2/auth",
     "token_uri": "https://oauth2.googleapis.com/token",
     "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
     "client_x509_cert_url": "*****",
     "universe_domain": "googleapis.com"
   }
   ```

1. 将您的凭证 JSON 文件上传到适当安全的 Amazon S3 位置。保留文件路径*s3secretpath* 以备将来的步骤使用。

1. 在 AWS Secrets Manager 中，使用您的 Google Cloud Platform 凭证创建密钥。要在 Secrets Manager 中创建密钥，请按照 AWS Secrets Manager 文档中[创建 AWS Secrets Manager 密钥](https://docs.aws.amazon.com//secretsmanager/latest/userguide/create_secret.html)中的教程进行操作。创建密钥后，保留密钥名称 *secretName*，以供下一步使用。

   创建键/值对时，请按以下方式指定键和值：
   + 对于 `token_uri`、`client_x509_cert_url`、`private_key_id`、`project_id`、`universe_domain`、`auth_provider_x509_cert_url`、`auth_uri`、`client_email`、`private_key`、`type`、`client_id` 键，请在下载的 JSON 文件中指定相应的值。
   + 对于 `spark.hadoop.google.cloud.auth.service.account.json.keyfile` 键，请指定 *s3secretpath*。

1. 在 AWS Glue Data Catalog 中，按照 [添加 AWS Glue 连接](console-connections.md) 中的步骤创建连接。创建连接后，保留连接名称 *connectionName*，以供下一步使用。
   + 在选择**连接类型**时，请选择 Google BigQuery。
   + 选择 **AWS 密钥**时，请提供 *secretName*。

1. 向与您的 AWS Glue 作业关联的 IAM 角色授予读取 *secretName* 的权限。

1. 在 AWS Glue 作业配置中，提供 *connectionName* 作为**附加网络连接**。

## 从 BigQuery 表格中读取
<a name="aws-glue-programming-etl-connect-bigquery-read"></a>

**先决条件** 
+ 您想从中读取的 BigQuery 表。您需要 `[dataset].[table]` 形式的 BigQuery 表和数据集名称。我们称之为 *tableName*。
+ BigQuery 表的计费项目。您将需要项目的名称 *parentProject*。如果没有计费父项目，请使用包含该表的项目。
+ BigQuery 身份验证信息。完成*使用 AWS Glue 管理连接凭证*的步骤，以配置您的身份验证信息。您需要 AWS Glue 连接的名称 *connectionName*。

例如：

```
bigquery_read = glueContext.create_dynamic_frame.from_options(
    connection_type="bigquery",
    connection_options={
        "connectionName": "connectionName",
        "parentProject": "parentProject",
        "sourceType": "table",
        "table": "tableName",
    }
```

您还可以提供查询，以筛选返回到您的 DynamicFrame 的结果。您将需要配置 `query`、`sourceType`、`viewsEnabled` 和 `materializationDataset`。

例如：

**其他先决条件：**

您需要创建或识别一个 BigQuery 数据集 *materializationDataset*，BigQuery 可以在其中为您的查询编写实体化视图。

您需要向您的服务账户授予相应的 GCP IAM 权限，才能在 *materializationDataset* 中创建表。

```
glueContext.create_dynamic_frame.from_options(
            connection_type="bigquery",
            connection_options={
                "connectionName": "connectionName",
                "materializationDataset": materializationDataset,
                "parentProject": "parentProject",
                "viewsEnabled": "true",
                "sourceType": "query",
                "query": "select * from bqtest.test"
            }
        )
```

## 写入 BigQuery 表
<a name="aws-glue-programming-etl-connect-bigquery-write"></a>

此示例直接写入 BigQuery 服务。BigQuery 还支持“间接”写入方法。有关配置间接写入的更多信息，请参阅 [在 Google BigQuery 中使用间接写入](#aws-glue-programming-etl-connect-bigquery-indirect-write)。

**先决条件** 
+ 您想向其中写入的 BigQuery 表。您需要 `[dataset].[table]` 形式的 BigQuery 表和数据集名称。您也可以提供一个将自动创建的新表名。我们称之为 *tableName*。
+ BigQuery 表的计费项目。您将需要项目的名称 *parentProject*。如果没有计费父项目，请使用包含该表的项目。
+ BigQuery 身份验证信息。完成*使用 AWS Glue 管理连接凭证*的步骤，以配置您的身份验证信息。您需要 AWS Glue 连接的名称 *connectionName*。

例如：

```
bigquery_write = glueContext.write_dynamic_frame.from_options(
    frame=frameToWrite,
    connection_type="bigquery",
    connection_options={
        "connectionName": "connectionName",
        "parentProject": "parentProject",
        "writeMethod": "direct",
        "table": "tableName",
    }
)
```

## BigQuery 连接选项参考
<a name="aws-glue-programming-etl-connect-bigquery-reference"></a>
+ `project` – 默认：Google Cloud 服务账户默认。用于读/写。与您的表格关联的 Google Cloud 项目的名称。
+ `table` -（必需）用于读/写。格式为 `[[project:]dataset.]` 的 BigQuery 表的名称。
+ `dataset` – 如果未通过 `table` 选项进行定义，则为必填项。用于读/写。包含您的 BigQuery 表的数据集的名称。
+ `parentProject` – 默认：Google Cloud 服务账户默认。用于读/写。与用于计费的 `project` 关联的 Google Cloud 项目的名称。
+ `sourceType` – 用于读取。读取时为必填项。有效值：`table`，`query` 告知 AWS Glue 是按表读取还是按查询读取。
+ `materializationDataset` – 用于读取。有效值：字符串。用于存储视图实例化的 BigQuery 数据集的名称。
+ `viewsEnabled` – 用于读取。默认值：false。有效值：true、false。配置 BigQuery 是否使用视图。
+ `query` – 用于读取。在 `viewsEnabled` 为真时使用。GoogleSQL DQL 查询。
+ `temporaryGcsBucket` – 用于写入。在 `writeMethod` 设置为默认值（`indirect`）时为必填。写入 BigQuery 时用于存储中间形式数据的 Google Cloud Storage 存储桶的名称。
+ `writeMethod` - 默认值：`indirect`。有效值：`direct`、`indirect`。用于写入。指定用于写入数据的方法。
  + 如果设置为 `direct`，则您的连接器将使用 BigQuery 存储写入 API 进行写入。
  + 如果设置为 `indirect`，则您的连接器将 Google Cloud Storage，然后使用加载操作将其传输到 BigQuery。您的 Google Cloud 服务账户将需要相应的 GCS 权限。

## 在 Google BigQuery 中使用间接写入
<a name="aws-glue-programming-etl-connect-bigquery-indirect-write"></a>

此示例使用间接写入，将数据写入 Google Cloud Storage 并将其复制到 Google BigQuery。

**先决条件**

您需要一个临时的 Google Cloud Storage 存储桶 *temporaryBucket*。

AWS Glue 的 GCP 服务账户的 GCP IAM 角色需要适当的 GCS 权限才能访问 *temporaryBucket*。

**其他配置：**

**要使用 BigQuery 配置间接写入，请执行以下操作：**

1. 评测 [配置 BigQuery 连接](#aws-glue-programming-etl-connect-bigquery-configure) 并找到或重新下载您的 GCP 凭证 JSON 文件。识别 *SecretName*，这是您的作业中使用的 Google BigQuery AWS Glue 连接的 AWS Secrets Manager 密钥。

1. 将您的凭证 JSON 文件上传到适当安全的 Amazon S3 位置。保留文件路径*s3secretpath* 以备将来的步骤使用。

1. 编辑 *secretName*，添加 `spark.hadoop.google.cloud.auth.service.account.json.keyfile` 密钥。将值设置为 *s3secretpath*。

1. 向您的 AWS Glue 作业 Amazon S3 授予访问 *s3secretpath* 的 IAM 权限。

现在，您可以将临时 GCS 存储桶位置提供给您的写入方法。您无需提供 `writeMethod`，因为 `indirect` 历史上是默认设置。

```
bigquery_write = glueContext.write_dynamic_frame.from_options(
    frame=frameToWrite,
    connection_type="bigquery",
    connection_options={
        "connectionName": "connectionName",
        "parentProject": "parentProject",
        "temporaryGcsBucket": "temporaryBucket",
        "table": "tableName",
    }
)
```