【问题标题】:Does pandas-gbq currently support parameterised queries?pandas-gbq 目前是否支持参数化查询?
【发布时间】:2020-04-09 22:09:41
【问题描述】:

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

虽然可能有更好和更有效的方法(注意:我不是软件工程师),但我目前正在 BigQuery 中研究 Parameterized Queries 以参数化日期列并在 Python 中的 for 循环中对其进行迭代。

有谁知道 pandas-gbq 目前是否支持参数化查询?提前致谢。

【问题讨论】:

    标签: python pandas google-bigquery


    【解决方案1】:

    是的,确实如此。不过,我建议您切换到也支持参数的官方 Google BigQuery 客户端库。

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

    使用 Pandas GBQ 设置参数

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

    configuration : dict, 作业的可选查询配置参数 加工。例如:

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

    这是来自该链接的完整代码示例,描述了如何在 Pandas 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 客户端库设置参数

    这是一篇关于从 Pandas-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
    

    【讨论】:

    • 没问题!如果您觉得我的回答有用,请随时接受。
    • 同样,我们如何在 query_config 中传递一个列表?
    【解决方案2】:

    一个简单的方法是使用 .to_dataframe()

    df = client.query(query, job_config=job_config).to_dataframe()
    

    请参考以下文档。

    Download query results to DataFrame

    Google Cloud Client Libraries for google-cloud-bigquery

    以下是示例代码-

    name = 'John'
    
    project_id = 'bqproject'
    dataset_id = 'bqdataset'
    table = 'bqtable'
    
    query =  """SELECT * FROM `%s.%s.%s` WHERE Name = @name"""%(project_id,dataset_id,table)
    
    job_config = bigquery.QueryJobConfig(
        query_parameters=[
            bigquery.ScalarQueryParameter("name", "STRING", name),
            
            ]
        )
    
    df = client.query(query, job_config=job_config).to_dataframe()
    df
    

    【讨论】:

      【解决方案3】:

      Ben P 发布的答案需要使用 Pandas GBQ 进行一些改进,因为我们收到以下错误:

      GenericGBQException:原因:400 POST https://bigquery.googleapis.com/bigquery/v2/projects/my-bigquery/jobs: 缺少查询参数值

      重要且缺少的配置参数是:

      'parameterValue': {'value': 'TX'}
      

      可以在Running a query with a configuration docs 示例中查看。

      将查询配置放在一起,我们得到:

      query_config = {
          'query': {
              'parameterMode': 'NAMED',
              'queryParameters': [
                  {
                      'name': 'state',
                      'parameterType': {'type': 'STRING'},
                      'parameterValue': {'value': 'TX'}
                  },
              ]
          }
      }
      

      我认为这将帮助我们大多数人来解决问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-06
        • 1970-01-01
        • 2019-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-30
        相关资源
        最近更新 更多