我在BigQuery上有一组表,其中包含某种数据,并且我想通过我定义的JavaScript函数处理该数据。 JS函数将旧数据映射到新模式,该模式必须是新表实现的模式。
我的一组表具有一个公共前缀,我想通过创建具有不同前缀但保留所有后缀相同的表将它们全部迁移到新架构。
示例:我有100个名为raw_data_SUFFIX
的表,我想使用一个名为parsed_data_SUFFIX
的新模式将它们迁移到100个表,并保留每个后缀。
这是用于迁移数据的简单查询
SELECT some_attribute, parse(another_attribute) as parsed
FROM `<my-project>.<dataset>.data_*`
是否可以通过BigQuery UI来做到这一点?
答案 0 :(得分:0)
为了实现您的目标,您必须使用DDL语句CREATE TABLE,如下所示:
CREATE TABLE 'project_id.dataset.table' AS SELECT * FROM `project_id.dataset.table_source`
但是,不可能使用通配符来引用多个目的地。如文档here中所述,使用通配符时存在一些限制,其中包括:
包含DML语句的查询不能使用通配符表作为 查询的目标。例如,通配符表可用于 UPDATE查询的FROM子句,但不能将通配符表用作 UPDATE操作的目标。
尽管如此,您仍可以使用Python API向BigQuery发出请求。然后,将每个视图保存到一个新表中,每个表的名称都带有一个新的前缀和旧的后缀。您可以按照以下步骤进行操作:
from google.cloud import bigquery
client = bigquery.Client()
dataset_id = 'your_dataset_id'
#list all the tables as objects , each obj has table.project,table.dataset_id,table.table_id
tables = client.list_tables(dataset_id)
#initialising arrays (not necessary)
suffix=[]
table_reference=[]
#looping through all the tables in you dataset
for table in tables:
#Filter if the table's name start with the prefix
if "your_table_prefix" in table.table_id:
#retrieves the suffix, which will be used in the new table's name
#extracts the suffix of the table's name
suffix=table.table_id.strip('your_table_prefix')
#reference the source table
table_reference=".".join([table.project,table.dataset_id,table.table_id])
#table destination with new prefix and old suffix
job_config = bigquery.QueryJobConfig()
table_ref = client.dataset(dataset_id).table("_".join(['new_table_prefix',suffix]))
job_config.destination = table_ref
sql='''
CREATE TEMP FUNCTION
function_name ( <input> )
RETURNS <type>
LANGUAGE js AS """
return <type>;
""";
SELECT function_name(<columns>) FROM `{0}`'''.format(table_reference)
query_job = client.query(
sql,
# Location must match that of the dataset(s) referenced in the query
# and of the destination table.
location='US',
job_config=job_config)
query_job.result() # Waits for the query to finish
print('Query results loaded to table {}'.format(table_ref.path))
请注意,在sql
查询中,首先使用''',然后使用“”“ 来定义查询和 JS Temp Function 。
我想指出的是,您必须确保您的环境具有适当的软件包才能将Python API用于BigQuery here。您可以使用pip install --upgrade google-cloud-bigquery
来安装BigQuery软件包。