用于将数据从Google电子表格加载到bigquery的独立脚本

时间:2016-08-26 07:15:50

标签: google-apps-script google-sheets google-bigquery

我编写了一个独立的脚本,用于将数据从csv文件加载到bigquery,但我想知道如何将数据从电子表格加载到bigquery。这是我将数据从csv加载到bigquery的代码。我想知道在哪里更改谷歌电子表格而不是csv文件。

function loadCsv() {
  // Replace this value with the project ID listed in the Google
  // Developers Console project.
  var projectId = '775034665452';
  var datasetId = 'DEV';
  // Sample CSV file of Google Trends data conforming to the schema below.
  // https://docs.google.com/file/d/0BwzA1Orbvy5WMXFLaTR1Z1p2UDg/edit
  var csvFileId = '0BwzA1Orbvy5WMXFLaTR1Z1p2UDg';

  // Create the table.
  var tableId = 'pets_' + new Date().getTime();
  var table = {
    tableReference: {
      projectId: projectId,
      datasetId: datasetId,
      tableId: tableId
    },
    schema: {
      fields: [
        {name: 'week', type: 'STRING'},
        {name: 'cat', type: 'INTEGER'},
        {name: 'dog', type: 'INTEGER'},
        {name: 'bird', type: 'INTEGER'}
      ]
    }
  };
  table = BigQuery.Tables.insert(table, projectId, datasetId);
  Logger.log('Table created: %s', table.id);

  // Load CSV data from Drive and convert to the correct format for upload.
  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);
  Logger.log('Load job started. Check on the status of it here: ' +
      'https://bigquery.cloud.google.com/jobs/%s', projectId);
}

1 个答案:

答案 0 :(得分:0)

您必须先将数据加载到BigQuery中,然后才能运行查询。

您可以通过以下方式load data

可以将加载的数据添加到新表中,附加到表中,也可以覆盖表。

BigQuery支持从多种源格式加载数据,包括CSV,JSON,Avro和Google Cloud Datastore备份文件。有关详细信息,请参阅Data Formats

加载 CSV 文件,请检查:https://cloud.google.com/bigquery/loading-data#loading_csv_files

相关问题