Use Cloud Run Functions to Load BigQuery
Main article: https://www.skills.google/paths/1336/course_templates/1157/labs/603516
Enable these APIs:
-
Cloud Functions API
-
Cloud Run Admin API
-
Eventarc API
-
Cloud Build API
-
Artifact Registry API
-
Cloud Pub/Sub API
-
Cloud Logging API
Set IAM permissions (UI)
-
Go to
IAM & Admin → IAM -
Find the service account:
PROJECT_NUMBER-compute@developer.gserviceaccount.com
-
Add role:
-Eventarc Event Receiver
-Pub/Sub Publisher
Create the BigQuery dataset (UI)
-
Open Google BigQuery
-
Click Create Dataset
Fill:
Dataset ID: loadavroCreate.
Create the Cloud Function (UI)
→ Cloud Functions -> NodeJS
Name: loadbigqueryfromavro
Runtime: Node.js 20
Trigger type -> Cloud Storage
Event type -> Create
google.cloud.storage.object.v1.finalized
the code:
const functions = require('@google-cloud/functions-framework');
const { Storage } = require('@google-cloud/storage');
const { BigQuery } = require('@google-cloud/bigquery');
const storage = new Storage();
const bigquery = new BigQuery();
functions.cloudEvent('loadBigQueryFromAvro', async (cloudEvent) => {
try {
console.log('FULL EVENT:', JSON.stringify(cloudEvent, null, 2));
const data = cloudEvent.data;
if (!data || !data.bucket || !data.name) {
throw new Error('Invalid event data');
}
const bucketName = data.bucket;
const fileName = data.name;
const datasetId = 'loadavro';
const tableId = fileName.replace('.avro', '');
const options = {
sourceFormat: 'AVRO',
autodetect: true,
createDisposition: 'CREATE_IF_NEEDED',
writeDisposition: 'WRITE_TRUNCATE',
};
const [job] = await bigquery
.dataset(datasetId)
.table(tableId)
.load(storage.bucket(bucketName).file(fileName), options);
console.log(`Job ${job.id} completed. Created table ${tableId}`);
} catch (error) {
console.error('Error:', error);
throw error;
}
});
and package.json:
{
"name": "load-bigquery-from-avro",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "functions-framework --target=loadBigQueryFromAvro --signature-type=cloudevent"
},
"dependencies": {
"@google-cloud/functions-framework": "^3.0.0",
"@google-cloud/storage": "^7.0.0",
"@google-cloud/bigquery": "^7.0.0"
}
}
Go to bucket -> settings -> copy the service account ->
-> Go to IAM -> give role: roles/pubsub.publisher
Download https://storage.googleapis.com/cloud-training/dataengineering/lab_assets/idegc/campaigns.avro
and then upload it into the bucket we created.
Comments
Post a Comment