Airflow 气流:如何从BigQueryOperator推送xcom值?
这是我的接线员:Airflow 气流:如何从BigQueryOperator推送xcom值?,airflow,Airflow,这是我的接线员: bigquery_check_op = BigQueryOperator( task_id='bigquery_check', bql=SQL_QUERY, use_legacy_sql = False, bigquery_conn_id=CONNECTION_ID, trigger_rule='all_success', xcom_push=True, dag=dag ) 当我在UI中检查呈现页面时。那里什么也没有。
bigquery_check_op = BigQueryOperator(
task_id='bigquery_check',
bql=SQL_QUERY,
use_legacy_sql = False,
bigquery_conn_id=CONNECTION_ID,
trigger_rule='all_success',
xcom_push=True,
dag=dag
)
当我在UI中检查呈现页面时。那里什么也没有。
当我在控制台中运行SQL时,它返回值1400
,这是正确的。
为什么操作员不推XCOM
我不能使用
BigQueryValueCheckOperator
。此运算符设计为在值检查时失败。我不希望任何事情都失败。我只想根据查询的返回值对代码进行分支。最简单的答案是因为xcom\u push
不是nor或LoggingMixin中的参数之一
确实返回(并因此推送)一些数据,但它按表和列名工作。您可以通过将运行的查询输出到一个唯一命名的表(可能在名称中使用{{ds_nodash}}
),然后将该表用作此运算符的源来链接此行为,然后可以使用
您可以尝试使用BigQueryHook
来运行查询并处理BranchPythonOperator
中的一些数据
在其他地方,我们聊了聊,并想出了一些类似于这句话的东西,用于插入分支ythonoperator的可调用项:
cursor = BigQueryHook(bigquery_conn_id='connection_name').get_conn().cursor()
# one of these two:
cursor.execute(SQL_QUERY) # if non-legacy
cursor.job_id = cursor.run_query(bql=SQL_QUERY, use_legacy_sql=False) # if legacy
result=cursor.fetchone()
return "task_one" if result[0] is 1400 else "task_two" # depends on results format
下面是使用BigQueryHook和BranchPythonOperator实现这一点的方法:
from airflow.operators.python_operator import BranchPythonOperator
from airflow.contrib.hooks import BigQueryHook
def big_query_check(**context):
sql = context['templates_dict']['sql']
bq = BigQueryHook(bigquery_conn_id='default_gcp_connection_id',
use_legacy_sql=False)
conn = bq.get_conn()
cursor = conn.cursor()
results = cursor.execute(sql)
# Do something with results, return task_id to branch to
if results == 0:
return "task_a"
else:
return "task_b"
sql = "SELECT COUNT(*) FROM sales"
branching = BranchPythonOperator(
task_id='branching',
python_callable=big_query_check,
provide_context= True,
templates_dict = {"sql": sql}
dag=dag,
)
首先,我们创建一个python可调用函数,可以使用它执行查询并选择要分支的任务id。其次,我们创建BranchPythonOperator