Sub topic 15
Looping over inputs with For each tasks
This chapter assumes you can create a multi-task job, pass job parameters, and share task values between tasks. If any of that is unfamiliar, review those chapters first.
What a For each task does
A For each task runs one nested task many times, once per item in a list of inputs. Use it when the same logic must run for many values, such as one notebook run per country, table, or date. Without it, you would copy the same task many times or write a loop inside one notebook. A loop inside a notebook gives you no separate retries, logs, or status for each item.
The For each task has two parts:
- inputs: the list to loop over. It can be a JSON array written directly in the task, a job parameter, or a task value from an upstream task.
- task: the single nested task that runs for each item. It reads the current item through
{{input}}.
You can set a concurrency value to limit how many iterations run at the same time.
Example: one iteration per table
First, an upstream notebook publishes the list as a task value.
tables = ["orders", "customers", "products"]
dbutils.jobs.taskValues.set(key="tables", value=tables)Next, the For each task reads that list and passes each item to a nested notebook task.
{
"task_key": "process_tables",
"depends_on": [{"task_key": "list_tables"}],
"for_each_task": {
"inputs": "{{tasks.list_tables.values.tables}}",
"concurrency": 2,
"task": {
"task_key": "process_table_iteration",
"notebook_task": {
"notebook_path": "/Workspace/Shared/process_table",
"base_parameters": {"table_name": "{{input}}"}
}
}
}
}The nested notebook reads its parameter as a widget:
table_name = dbutils.widgets.get("table_name")
df = spark.table(f"sales.{table_name}")
print(f"{table_name}: {df.count()} rows")With concurrency set to 2, Databricks runs two tables at once and starts the third when one finishes. Downstream tasks, such as summarize, wait until every iteration has finished.
Common errors
- Passing a plain string.
inputsmust resolve to an array. A single value will not loop as you expect. - Expecting iterations to share values. Each iteration is isolated. A task value set inside the nested task is not available to its sibling iterations.
- Leaving concurrency too high. Many iterations can overload a cluster or a source system. Start low and raise it.
- Nesting loops. A For each task cannot contain another For each task. Use a Run Job task if you need a second level.
Exercise
Your job has a task list_regions that sets a task value regions to a list of region names. Write the inputs value for a For each task that loops over it, and name the expression a nested task uses to read the current region.
Show answer
The inputs value is "{{tasks.listregions.values.regions}}". The nested task reads the current region with {{input}}, for example in baseparameters as "region": "{{input}}".