Writing a DAG: operators and dependencies
Airflow (Cloud Composer) · 14 questions
Short notes
Key idea
A DAG file creates a DAG object and the tasks inside it, then sets their order with >>. The TaskFlow API (@dag, @task) lets plain Python functions become tasks.
Syntax
from airflow.decorators import dag, task
from airflow.operators.bash import BashOperator
import pendulum
@dag(schedule="@daily", start_date=pendulum.datetime(2024, 1, 1, tz="Asia/Kolkata"), catchup=False)
def sales():
@task
def extract(): ...
@task
def load(rows): ...
done = BashOperator(task_id="done", bash_command="echo ok")
load(extract()) >> done
sales()
a >> bmeans b runs after a;[a, b] >> cwaits for both.
Example
extract >> [clean_orders, clean_customers] >> build_mart runs the two cleaning tasks in parallel, then the mart once both succeed.
Traps
- Forgetting to call the DAG function (
sales()) means no DAG appears. - Every task needs a unique
task_idwithin the DAG. - Don't hit databases or APIs at the top of the file; that runs every time the scheduler parses it.
- A static
start_date; never usedatetime.now().
Want the full lesson with step-by-step examples, a project and a certificate? Airflow (Cloud Composer) course, ₹120 →
Questions
5 free questions- Question 1easy
What does
load >> transform >> testmean? - Question 2medium
In this DAG, which tasks can run at the same time?
start >> [load_orders, load_customers] [load_orders, load_customers] >> build_facts
- Question 3medium
Why shouldn't a DAG file query BigQuery at the top level, outside any task?
- Question 4medium
What's wrong with
start_date=datetime.now()? - Question 5hard
What does
chain(start, [load_a, load_b], [clean_a, clean_b], build)create?
Writing a DAG: operators and dependencies
Writing a DAG: operators and dependencies
Writing a DAG: operators and dependencies
Writing a DAG: operators and dependencies
Writing a DAG: operators and dependencies
9 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.