我需要通过 Java 更新 BigQuery 表架构。更改将是附加的(仅添加新列)。
我正在努力寻找实现这一目标的方法。在 Python 中,可能是这样的:
table_ref = client.dataset(dataset_id).table(table_id)
table = client.get_table(table_ref) # API request
original_schema = table.schema
new_schema = original_schema[:] # creates a copy of the schema
new_schema.append(bigquery.SchemaField('phone', 'STRING'))
table.schema = new_schema
table = client.update_table(table, ['schema']) # API request
在页面上https://cloud.google.com/bigquery/docs/managing-table-schemas ,据说使用补丁端点来完成此任务。
提出了一个问题来改进补丁 API,但我不知道结果 https://github.com/googleapis/google-cloud-java/issues/1564
任何帮助将不胜感激。谢谢
最佳答案
Java 中的想法与您共享的 Python 示例中的想法相同,即获取当前架构并向其添加新列。您可以使用我准备的代码片段来实现此目的,如下所示:
// Instantiate the BQ client
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
// Get the table, schema and fields from the already-existing table
Table table = bigquery.getTable(TableId.of("PROJECT_ID", "DATASET", "TABLE"));
Schema schema = table.getDefinition().getSchema();
FieldList fields = schema.getFields();
// Create the new field
Field newField = Field.of("column2", LegacySQLTypeName.STRING);
// Create a new schema adding the current fields, plus the new one
List<Field> field_list = new ArrayList<Field>();
for (Field f : fields) {
field_list.add(f);
}
field_list.add(newField);
Schema newSchema = Schema.of(field_list);
// Update the table with the new schema
Table updatedTable = table.toBuilder().setDefinition(StandardTableDefinition.of(newSchema)).build().update();
此代码使用 com.google.cloud.bigquery
包(请参阅其 documentation here )。然后,它指定架构定义,如 tables documentation 中的示例所示。 ,终于更新了。
关于java - 在 Java 中更新 BigQuery 架构/添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53087703/