pandasgbq目前是否支持参数化查询?

2024-04-20 01:56:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用Pandas/Pandas gbq在Python中创建一个简单的ETL管道,从BigQuery到Pandas dataframe中读取给定日期范围内的每天,并从查询结果创建单独的每日表(写回BigQuery)。你知道吗

虽然可能有更好更有效的方法(注意:我不是软件工程师),但我目前正在研究BigQuery中的Parameterized Queries来参数化date列,并在Python中的for循环中迭代它。你知道吗

有人知道pandas gbq目前是否支持参数化查询吗?提前谢谢。你知道吗


Tags: 方法dataframepandasfor参数date软件管道
1条回答
网友
1楼 · 发布于 2024-04-20 01:56:49

是的,是的。但是,我建议您切换到官方的googlebigquery客户端库,它也支持参数。你知道吗

BigQuery客户端库: https://cloud.google.com/bigquery/docs/reference/libraries#client-libraries-install-python

使用GBQ设置参数

您可以使用configuration参数在GBQ查询中设置参数,引用Pandas GBQ docs

configuration : dict, optional Query config parameters for job processing. For example:

configuration = {‘query’: {‘useQueryCache’: False}}

下面是该链接的完整代码示例,它描述了如何在GBQ中参数化查询:

import pandas

sql = """
    SELECT name
    FROM `bigquery-public-data.usa_names.usa_1910_current`
    WHERE state = @state
"""
query_config = {
    'query': {
        'parameterMode': 'NAMED',
        'queryParameters': [
            {
                'name': 'state',
                'parameterType': {'type': 'STRING'}
            },
        ]
    }
}
df = pandas.read_gbq(sql, configuration=query_config)

使用BigQuery客户端库设置参数

下面是一篇关于从GBQ迁移到BigQuery客户端库的优秀文章: https://cloud.google.com/bigquery/docs/pandas-gbq-migration

下面是一些示例Python代码,我使用官方BQ客户端库在查询中使用参数:

table_name = "my_table"
job_config = bigquery.QueryJobConfig()
# Set the destination table
table_ref = client.dataset(dataset_id).table(table_name)
job_config.destination = table_ref
job_config.write_disposition = 'WRITE_APPEND'
sql = """
SELECT * FROM dataset.table WHERE visit_date = date
"""
query_params = [bigquery.ScalarQueryParameter('date', 'DATE', date)]
job_config.query_parameters = query_params

# Start the query, passing in the extra configuration.
query_job = client.query(
    sql,
    location='EU',
    job_config=job_config)  # API request - starts the query

query_job.result()  # Waits for the query to finish

相关问题 更多 >