使用Java从Google Cloud Storage向BigQuery加载数据

3

我想把Google Cloud Storage中的数据上传到BigQuery,但是我找不到任何描述如何实现此操作的Java样例代码。请问有人能给我一些提示吗?

实际上,我想要做的是将Google App Engine表格中的数据传输到BigQuery(并且每天同步),以便进行一些分析。我使用Google App Engine中的Google Cloud Storage服务将(新)记录写入Google Cloud Storage中的文件,唯一缺失的部分是将数据追加到BigQuery中的表格(或者为首次写入创建新表格)。诚然,我可以使用BigQuery浏览器工具手动上传/追加数据,但我希望这个过程是自动的,否则我需要每天手动完成。

1个回答

5

我不知道有没有任何Java样例可以将Google Cloud Storage中的表加载到BigQuery中。尽管如此,如果您按照运行查询作业的说明这里,您可以使用以下内容运行一个Load作业:

Job job = new Job();
JobConfiguration config = new JobConfiguration();
JobConfigurationLoad loadConfig = new JobConfigurationLoad();
config.setLoad(loadConfig);

job.setConfiguration(config);

// Set where you are importing from (i.e. the Google Cloud Storage paths).
List<String> sources = new ArrayList<String>();
sources.add("gs://bucket/csv_to_load.csv");
loadConfig.setSourceUris(sources);

// Describe the resulting table you are importing to:
TableReference tableRef = new TableReference();
tableRef.setDatasetId("myDataset");
tableRef.setTableId("myTable");
tableRef.setProjectId(projectId);
loadConfig.setDestinationTable(tableRef);

List<TableFieldSchema> fields = new ArrayList<TableFieldSchema>();
TableFieldSchema fieldFoo = new TableFieldSchema();
fieldFoo.setName("foo");
fieldFoo.setType("string");
TableFieldSchema fieldBar = new TableFieldSchema();
fieldBar.setName("bar");
fieldBar.setType("integer");
fields.add(fieldFoo);
fields.add(fieldBar);
TableSchema schema = new TableSchema();
schema.setFields(fields);
loadConfig.setSchema(schema);

// Also set custom delimiter or header rows to skip here....
// [not shown].

Insert insert = bigquery.jobs().insert(projectId, job);
insert.setProjectId(projectId);
JobReference jobRef =  insert.execute().getJobReference();

// ... see rest of codelab for waiting for job to complete.

有关加载配置对象的更多信息,请参见此处的 javadoc


1
非常感谢您的代码。我尝试了一下,它运行得非常好。为了让更多人能够使用这个片段,其中有一些小错误需要修正,如果您能稍微修改一下就太好了。1.第3行“JobConfigurationQLoad”应该改为“JobConfigurationLoad”;2.Jobs.insert()函数需要两个参数,第一个参数是一个字符串(虽然无论您放什么都没关系);3.在代码的最后一行,我认为您的意思是“JobReference jobRef”,而不是“jobId”。再次感谢! - Jack Guo
代码已经根据您提出的更改进行了更新。感谢您的反馈。 - Jordan Tigani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接