如何使用 bigquery 运算符将查询参数传递给 sql 文件

gan*_*til 3 airflow google-cloud-composer

我需要在 sql 文件中访问 BigqueryOperator 传递的参数,但是我ERROR - queryParameters argument must have a type <class 'dict'> not <class 'list'> 使用以下代码时出现错误:

t2 = bigquery_operator.BigQueryOperator(
task_id='bq_from_source_to_clean',
sql='prepare.sql',
use_legacy_sql=False,
allow_large_results=True,
query_params=[{ 'name': 'threshold_date', 'parameterType': { 'type': 'STRING' },'parameterValue': { 'value': '2020-01-01' } }],
destination_dataset_table="{}.{}.{}".format('xxxx',
                                            'xxxx',
                                            'temp_airflow_test'),
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_TRUNCATE",
dag=dag
Run Code Online (Sandbox Code Playgroud)

)

查询:

select  cast(DATE_ADD(a.dt_2, interval 7 day) as DATE) as dt_1
,a.dt_2
,cast('2010-01-01' as DATE) as dt_3 
from (select cast(@threshold_date as date) as dt_2) a
Run Code Online (Sandbox Code Playgroud)

我正在使用 Google 作曲家版本composer-1.7.0-airflow-1.10.2

提前致谢。

nor*_*bjd 8

深入研究源代码后,似乎BigQueryHook在 Airflow 1.10.3 中修复了一个错误。

您定义的方式query_params适用于较新版本的 Airflow,并且应该是根据 BigQuery API的列表:请参阅https://cloud.google.com/bigquery/docs/parameterized-queries#bigquery_query_params_named-python

无论如何,您会收到此错误,因为在 Airflow 1.10.2 中,query_params定义为 a dict,请参阅:

https://github.com/apache/airflow/blob/1.10.2/airflow/contrib/hooks/bigquery_hook.py#L678

query_param_list = [
    ...
    (query_params, 'queryParameters', None, dict),
    ...
]
Run Code Online (Sandbox Code Playgroud)

这会导致内部_validate_value函数抛出一个TypeError

https://github.com/apache/airflow/blob/1.10.2/airflow/contrib/hooks/bigquery_hook.py#L1954

def _validate_value(key, value, expected_type):
    """ function to check expected type and raise
    error if type is not correct """
    if not isinstance(value, expected_type):
        raise TypeError("{} argument must have a type {} not {}".format(
            key, expected_type, type(value)))
Run Code Online (Sandbox Code Playgroud)

我没有query_params在 Airflow 1.10.2(或任何单元测试...)中找到任何示例,但我认为这只是因为它不可用。

这些错误已由这些提交修复:

这些更改已嵌入到 Airflow 1.10.3 中,但截至目前,Airflow 1.10.3 在 Composer 中不可用 ( https://cloud.google.com/composer/docs/concepts/versioning/composer-versions#new_environments ) :最新版本已于 2019 年 5 月 16 日发布并嵌入版本 1.10.2。

等待这个新版本,我看到了 2 种方法来解决您的问题:

  • 复制/粘贴 和 的固定版本BigQueryOperator并将BigQueryHook它们嵌入到您的源中以使用它们,或者扩展现有的BigQueryHook和覆盖有问题的方法。我不确定您是否可以BigQueryHook直接修补(在 Composer 环境中无法访问这些文件)
  • 自己模板化您的 SQL 查询(而不是使用query_params