airflow - 如何使用 bigquery 运算符将查询参数传递给 sql 文件
问题描述
我需要在 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
)
数据:
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
我正在使用谷歌作曲家版本composer-1.7.0-airflow-1.10.2
提前致谢。
解决方案
在深入研究源代码后,似乎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),
...
]
这会导致内部_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)))
我没有query_params
在 Airflow 1.10.2 (或任何单元测试......)中找到任何示例,但我认为这只是因为它不可用。
这些错误已由这些提交修复:
- https://github.com/apache/airflow/commit/0c797a830e3370bd6e39f5fcfc128a8fd776912e#diff-ee06f8fcbc476ea65446a30160c2a2b2R784:更改
dict
为list
- https://github.com/apache/airflow/pull/4876:更新文档
这些更改已嵌入 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。
等待这个新版本,我看到了两种解决问题的方法:
- 复制/粘贴和的固定版本
BigQueryOperator
并将BigQueryHook
它们嵌入到您的源代码中以使用它们,或扩展现有的BigQueryHook
并覆盖错误的方法。我不确定您是否可以BigQueryHook
直接打补丁(在 Composer 环境中无法访问这些文件) - 自己模板化您的 SQL 查询(而不是使用
query_params
)