Este documento mostra como executar cargas de trabalho em lote sem servidor para Apache Spark SQL e PySpark para criar uma tabela Apache Iceberg com metadados armazenados no metastore do BigLake. Para informações sobre outras formas de executar código Spark, consulte os artigos Execute código PySpark num bloco de notas do BigQuery e Execute uma carga de trabalho do Apache Spark
Antes de começar
Se ainda não o fez, crie um Google Cloud projeto e um contentor do Cloud Storage.
Configure o seu projeto
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Enable the Dataproc, BigQuery, and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin
), which contains theserviceusage.services.enable
permission. Learn how to grant roles. -
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Enable the Dataproc, BigQuery, and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin
), which contains theserviceusage.services.enable
permission. Learn how to grant roles. Crie um contentor do Cloud Storage no seu projeto.
- In the Google Cloud console, go to the Cloud Storage Buckets page.
- Click Create.
- On the Create a bucket page, enter your bucket information. To go to the next
step, click Continue.
-
In the Get started section, do the following:
- Enter a globally unique name that meets the bucket naming requirements.
- To add a
bucket label,
expand the Labels section ( ),
click add_box
Add label, and specify a
key
and avalue
for your label.
-
In the Choose where to store your data section, do the following:
- Select a Location type.
- Choose a location where your bucket's data is permanently stored from the Location type drop-down menu.
- If you select the dual-region location type, you can also choose to enable turbo replication by using the relevant checkbox.
- To set up cross-bucket replication, select
Add cross-bucket replication via Storage Transfer Service and
follow these steps:
Set up cross-bucket replication
- In the Bucket menu, select a bucket.
In the Replication settings section, click Configure to configure settings for the replication job.
The Configure cross-bucket replication pane appears.
- To filter objects to replicate by object name prefix, enter a prefix that you want to include or exclude objects from, then click Add a prefix.
- To set a storage class for the replicated objects, select a storage class from the Storage class menu. If you skip this step, the replicated objects will use the destination bucket's storage class by default.
- Click Done.
-
In the Choose how to store your data section, do the following:
- Select a default storage class for the bucket or Autoclass for automatic storage class management of your bucket's data.
- To enable hierarchical namespace, in the Optimize storage for data-intensive workloads section, select Enable hierarchical namespace on this bucket.
- In the Choose how to control access to objects section, select whether or not your bucket enforces public access prevention, and select an access control method for your bucket's objects.
-
In the Choose how to protect object data section, do the
following:
- Select any of the options under Data protection that you
want to set for your bucket.
- To enable soft delete, click the Soft delete policy (For data recovery) checkbox, and specify the number of days you want to retain objects after deletion.
- To set Object Versioning, click the Object versioning (For version control) checkbox, and specify the maximum number of versions per object and the number of days after which the noncurrent versions expire.
- To enable the retention policy on objects and buckets, click the Retention (For compliance) checkbox, and then do the following:
- To enable Object Retention Lock, click the Enable object retention checkbox.
- To enable Bucket Lock, click the Set bucket retention policy checkbox, and choose a unit of time and a length of time for your retention period.
- To choose how your object data will be encrypted, expand the Data encryption section (Data encryption method. ), and select a
- Select any of the options under Data protection that you
want to set for your bucket.
-
In the Get started section, do the following:
- Click Create.
Conceda a função Editor de dados do BigQuery (
roles/bigquery.dataEditor
) à conta de serviço predefinida do Compute Engine,PROJECT_NUMBER-compute@developer.gserviceaccount.com
. Para ver instruções, consulte o artigo Conceda uma única função.Exemplo da CLI do Google Cloud:
gcloud projects add-iam-policy-binding PROJECT_ID \ --member PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role roles/bigquery.dataEditor
Notas:
Copie os seguintes comandos Spark SQL localmente ou no Cloud Shell para um ficheiro
iceberg-table.sql
.USE CATALOG_NAME; CREATE NAMESPACE IF NOT EXISTS example_namespace; DROP TABLE IF EXISTS example_table; CREATE TABLE example_table (id int, data string) USING ICEBERG LOCATION 'gs://BUCKET/WAREHOUSE_FOLDER'; INSERT INTO example_table VALUES (1, 'first row'); ALTER TABLE example_table ADD COLUMNS (newDoubleCol double); DESCRIBE TABLE example_table;
Substitua o seguinte:
- CATALOG_NAME: nome do catálogo do Iceberg.
- BUCKET e WAREHOUSE_FOLDER: bucket do Cloud Storage e pasta usados como diretório do armazém do Iceberg.
Execute o seguinte comando localmente ou no Cloud Shell a partir do diretório que contém
iceberg-table.sql
para enviar a carga de trabalho do Spark SQL.gcloud dataproc batches submit spark-sql iceberg-table.sql \ --project=PROJECT_ID \ --region=REGION \ --deps-bucket=BUCKET_NAME \ --version=2.2 \ --subnet=SUBNET_NAME \ --properties="spark.sql.catalog.CATALOG_NAME=org.apache.iceberg.spark.SparkCatalog,spark.sql.catalog.CATALOG_NAME.catalog-impl=org.apache.iceberg.gcp.bigquery.BigQueryMetastoreCatalog,spark.sql.catalog.CATALOG_NAME.gcp_project=PROJECT_ID,spark.sql.catalog.CATALOG_NAME.gcp_location=LOCATION,spark.sql.catalog.CATALOG_NAME.warehouse=gs://BUCKET/WAREHOUSE_FOLDER"
Notas:
- PROJECT_ID: o ID do seu Google Cloud projeto. Os IDs dos projetos estão listados na secção Informações do projeto no Google Cloud painel de controloda consola.
- REGION: Uma região do Compute Engine disponível para executar a carga de trabalho.
- BUCKET_NAME: o nome do seu contentor do Cloud Storage. O Spark carrega as dependências da carga de trabalho para uma pasta
/dependencies
neste contentor antes de executar a carga de trabalho em lote. O ficheiro WAREHOUSE_FOLDER está localizado neste contentor. --version
: versão 2.2 ou posterior do tempo de execução do Apache Spark sem servidor.- SUBNET_NAME: O nome de uma sub-rede de VPC no
REGION
. Se omitir esta flag, o Serverless for Apache Spark seleciona a sub-rededefault
na região da sessão. O Serverless para Apache Spark ativa o Acesso privado do Google (PGA) na sub-rede. Para ver os requisitos de conetividade de rede, consulte o artigo Google Cloud Configuração de rede do Serverless para Apache Spark. - LOCATION: uma localização do BigQuery suportada. A localização predefinida é "US".
--properties
Propriedades do catálogo.
Veja os metadados da tabela no BigQuery
Na Google Cloud consola, aceda à página BigQuery.
Ver metadados da tabela Iceberg.
- Copie o seguinte código PySpark localmente ou no
Cloud Shell
para um ficheiro
iceberg-table.py
.from pyspark.sql import SparkSession spark = SparkSession.builder.appName("iceberg-table-example").getOrCreate() catalog = "CATALOG_NAME" namespace = "NAMESPACE" spark.sql(f"USE `{catalog}`;") spark.sql(f"CREATE NAMESPACE IF NOT EXISTS `{namespace}`;") spark.sql(f"USE `{namespace}`;") # Create table and display schema spark.sql("DROP TABLE IF EXISTS example_iceberg_table") spark.sql("CREATE TABLE example_iceberg_table (id int, data string) USING ICEBERG") spark.sql("DESCRIBE example_iceberg_table;") # Insert table data. spark.sql("INSERT INTO example_iceberg_table VALUES (1, 'first row');") # Alter table, then display schema. spark.sql("ALTER TABLE example_iceberg_table ADD COLUMNS (newDoubleCol double);") spark.sql("DESCRIBE example_iceberg_table;")
Substitua o seguinte:
- CATALOG_NAME e NAMESPACE: o nome do catálogo do Iceberg
e o espaço de nomes combinam-se para identificar a tabela do Iceberg (
catalog.namespace.table_name
).
- CATALOG_NAME e NAMESPACE: o nome do catálogo do Iceberg
e o espaço de nomes combinam-se para identificar a tabela do Iceberg (
-
Execute o seguinte comando localmente ou no
Cloud Shell
a partir do diretório que contém
iceberg-table.py
para enviar a carga de trabalho do PySpark.gcloud dataproc batches submit pyspark iceberg-table.py \ --project=PROJECT_ID \ --region=REGION \ --deps-bucket=BUCKET_NAME \ --version=2.2 \ --subnet=SUBNET_NAME \ --properties="spark.sql.catalog.CATALOG_NAME=org.apache.iceberg.spark.SparkCatalog,spark.sql.catalog.CATALOG_NAME.catalog-impl=org.apache.iceberg.gcp.bigquery.BigQueryMetastoreCatalog,spark.sql.catalog.CATALOG_NAME.gcp_project=PROJECT_ID,spark.sql.catalog.CATALOG_NAME.gcp_location=LOCATION,spark.sql.catalog.CATALOG_NAME.warehouse=gs://BUCKET/WAREHOUSE_FOLDER"
Notas:
- PROJECT_ID: o ID do seu Google Cloud projeto. Os IDs dos projetos estão listados na secção Informações do projeto no Google Cloud painel de controlo da consola.
- REGION: Uma região do Compute Engine disponível para executar a carga de trabalho.
- BUCKET_NAME: o nome do seu contentor do Cloud Storage. O Spark carrega as dependências da carga de trabalho para uma pasta
/dependencies
neste contentor antes de executar a carga de trabalho em lote. --version
: versão 2.2 ou posterior do tempo de execução do Apache Spark sem servidor.- SUBNET_NAME: O nome de uma sub-rede de VPC no
REGION
. Se omitir esta flag, o Serverless para Apache Spark seleciona a sub-rededefault
na região da sessão. O Serverless para Apache Spark ativa o Acesso privado do Google (PGA) na sub-rede. Para ver os requisitos de conetividade de rede, consulte o artigo Google Cloud Configuração de rede sem servidor para o Apache Spark. - LOCATION: uma localização do BigQuery suportada. A localização predefinida é "US".
- BUCKET e WAREHOUSE_FOLDER: contentor do Cloud Storage e pasta usados como o diretório do armazém do Iceberg.
--properties
: Propriedades do catálogo.
- Ver o esquema da tabela no BigQuery.
- Na Google Cloud consola, aceda à página BigQuery. Aceda ao BigQuery Studio
- Ver metadados da tabela Iceberg.
Mapeamento de recursos de OSS para recursos do BigQuery
Tenha em atenção o seguinte mapeamento entre os termos de recursos de código aberto e os termos de recursos do BigQuery:
Recurso de OSS Recurso do BigQuery Espaço de nomes, base de dados Conjunto de dados Tabela particionada ou não particionada Tabela Ver Ver Crie uma tabela Iceberg
Esta secção mostra como criar uma tabela Iceberg com metadados no metastore do BigLake através do Serverless para Apache Spark, do Spark SQL e das cargas de trabalho em lote do PySpark.
Spark SQL
Execute uma carga de trabalho do Spark SQL para criar uma tabela Iceberg
Os passos seguintes mostram como executar uma carga de trabalho em lote do Spark SQL do Serverless for Apache Spark para criar uma tabela Iceberg com metadados da tabela armazenados no metastore do BigLake.
PySpark
Os passos seguintes mostram como executar uma carga de trabalho em lote do PySpark do Serverless para Apache Spark para criar uma tabela Iceberg com metadados da tabela armazenados no metastore do BigLake.