【问题标题】:How can I automatically create BigQuery tables from my Cloud Storage bucket?如何从我的 Cloud Storage 存储分区自动创建 BigQuery 表?
【发布时间】:2020-05-21 08:10:38
【问题描述】:

我想创建一个每天凌晨 2 点运行的作业。此作业必须通过从 Cloud Storage 存储分区读取我的文件来创建 BigQuery 表。我怎样才能做到这一点?

【问题讨论】:

  • 文件格式是什么?如何生成表名?你有多少个文件?您要追加到现有表还是截断它们?
  • 文件是 Firestore 导出 (.export_metadata)。这些是我的 Firestore 子集合导出。我有 4 个子收藏。这些子集合中的每一个都有 419 个文档。我想截断现有表并重新加载它们。

标签: google-cloud-platform google-bigquery google-cloud-functions google-cloud-storage google-cloud-scheduler


【解决方案1】:

您可以将 Firestore 备份直接导入 BigQuery。设置一个load job,sourceFormat 等于DATASTORE_BACKUP(即使对于firestore也是如此),writeDisposition 为WRITE_TRUNCATE

您可以将其包装到云函数中。您可以直接使用 API 或client libraries。如果您需要代码示例,请将您的语言告诉我,我会看看能为您做什么。

编辑

你需要在你的 package.json 中导入这些依赖

    "@google-cloud/bigquery": "^4.7.0",
    "@google-cloud/storage": "^5.0.1",

然后,这里是具有静态值的函数。如果需要,您可以构建更动态的东西(例如通过阅读函数参数)。

const {Storage} = require('@google-cloud/storage');
const {BigQuery} = require('@google-cloud/bigquery');

const bigquery = new BigQuery();
const storage = new Storage();
//
const bucketName = "my_bucket" //to change
const fileExport = "path/to/my_export.export_metadata" //to change
const datasetId = "data" //to change
const tableId = "dsexport" //to change
exports.loadDSExport = async (req, res) => {

    // Configure the load job. For full list of options, see:
    // https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad
    const metadata = {
        sourceFormat: 'DATASTORE_BACKUP',
        autodetect: true,
        location: 'EU', // Set your correct region
        writeDisposition: "WRITE_TRUNCATE",
    };

    // Load data from a Google Cloud Storage file into the table
    const [job] = await bigquery
        .dataset(datasetId)
        .table(tableId)
        .load(storage.bucket(bucketName).file(fileExport), metadata);
    // load() waits for the job to finish
    // Can take time, increase function timeout if needed

    // Check the job's status for errors
    const errors = job.status.errors;
    if (errors && errors.length > 0) {
        //Handle error and return code here
        throw errors;
    }

    console.log(`Job ${job.id} completed.`);
    res.send(`Job ${job.id} completed.`);
};

然后,像这样部署你的函数(这里是私有模式)

gcloud beta functions deploy --runtime nodejs10 --trigger-http --entry-point loadDSExport --region europe-west1 loadDSExport

【讨论】:

  • 我需要帮助编写云函数。你能给我一个示例云函数,我可以用它来执行 bq load 命令吗?下面的 bq load 命令通过 CLI 工作: bq --location=asia-east1 load \ --replace --source_format=DATASTORE_BACKUP \ firestore.nric_test \ gs://gcp_firestore_ae1/export_20200521/all_namespaces/kind_nric_img/all_namespaces_kind_nric_img.export_metadata跨度>
  • 你喜欢什么语言?去?节点? Python? Java 来了,但我也可以!
  • Node 或 Java 都可以
  • 使用 Node 版本编辑 @NehaShaikh
  • @soheshdoshi,创建一个新问题,我可以调整 Python 中的代码。无法评论,与这里的问题无关!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 2019-05-29
  • 1970-01-01
  • 2021-03-06
  • 2018-03-17
  • 2017-11-15
  • 2021-12-10
相关资源
最近更新 更多