【问题标题】:Google Apps Script - How to stream JSON data into BigQuery?Google Apps 脚本 - 如何将 JSON 数据流式传输到 BigQuery?
【发布时间】:2020-01-21 08:47:32
【问题描述】:

在此参考https://developers.google.com/apps-script/advanced/bigquery

为了将 CSV 数据加载到 BigQuery 中,他们使用:

var file = DriveApp.getFileById(csvFileId);
  var data = file.getBlob().setContentType('application/octet-stream');

  // Create the data upload job.
  var job = {
    configuration: {
      load: {
        destinationTable: {
          projectId: projectId,
          datasetId: datasetId,
          tableId: tableId
        },
        skipLeadingRows: 1
      }
    }
  };
  job = BigQuery.Jobs.insert(job, projectId, data);

据我了解,他们向 BigQuery file.getBlob().setContentType('application/octet-stream'); 发送了一个 blob,这并不友好

如何在 Apps 脚本中将 JSON 发送到 BigQuery?

使用库 @google-cloud/bigquery(在 Apps 脚本之外的项目中使用),我可以执行以下操作:

https://cloud.google.com/bigquery/streaming-data-into-bigquery#streaminginsertexamples

// Import the Google Cloud client library
const { BigQuery } = require('@google-cloud/bigquery')
const moment = require('moment')

exports.insertUsageLog = async (userId) => {
  const datasetId = 'usage'
  const tableId = 'logs'
  const rows = [
    // The JSON data is collected here
    {
      timestamp: moment.utc().toISOString(),
      userId,
      // Something else ...
    },
  ]

  // Create a client
  const bigqueryClient = new BigQuery()

  // Insert data into a table
  await bigqueryClient
    .dataset(datasetId)
    .table(tableId)
    .insert(rows)
  console.log(`Inserted ${rows.length} rows`)
}

【问题讨论】:

    标签: json google-apps-script google-bigquery google-apps-script-addon jsonlines


    【解决方案1】:

    BigQuery.Jobs.insert() 的数据负载必须是一个 blob。

    您可以从 CSV 内容或 newline delimited JSON 创建该 Blob。换行符分隔的 JSON 是 JSON 的一种独特形式,即 required by BigQuery。 Apps 脚本本身不支持它。但是,您应该能够通过创建自定义 replacer function and passing it as a parameter to JSON.stringify() 将标准 JSON 转换为该格式。或者,您可能能够利用现有的 Javascript 库(您可能能够通过 NPM 找到一些东西,或者只是在 Github 上进行搜索)。

    生成换行符分隔的 JSON(作为字符串或字节数组)后,您需要使用 Utilities.newBlob() 将其转换为 blob 并将其传递给 BigQuery.Jobs.insert() 方法。

    【讨论】:

    • 请注意,换行分隔的 json 本身并不是 json,而是由换行分隔的有效 json 列表。
    • @Dimu Designs:谢谢。因为发送到 BigQuery 的数据必须是 blob,所以据我了解,库 @google-cloud/bigquery 将处理您为我们提到的所有这些任务?您可以在此处查看示例:cloud.google.com/bigquery/….
    • 顺便说一句,我查看了这篇文章hackernoon.com/json-lines-format-76353b4e588d,我终于知道为什么BigQuery 使用ndjson
    • @Dimu Designs:npm 上有一些支持 ndjson 的包,但是对于 Apps Script,我找不到任何东西。你能推荐一个函数来完成这项工作吗?
    • Dimu 和 @TheMaster:我收到另一个错误“GoogleJsonResponseException:对 bigquery.jobs.insert 的 API 调用失败并出现错误:权限不足”。 apps 脚本项目和大查询都在同一个 GCP 项目下,而且我没有看到在哪里为 apps 脚本配置服务帐户,所以我认为它应该自动获得权限,对吧?
    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多