Call a dict variable from yml to dbt script

299 views Asked by At

When I try to run dbt script, saying in dbt_project.yml, I have a variable as:

var:
   event:
      event_1: 
         start_date: 1
         end_date: 2 
      event_2:
         start_date: 1
         end_date: 2 

Is there a way I can call this variable in the SQL script I have tried {{ var("event['event_1']['start_date']") }} doesn't seem to work always complained about not being found in config

===

Follow up question

if we want to use jinja to call that variable, how should I do it, I have tried to use this but doesn't seem to work

{% set events = ["event_1", "event_2"] %}
 {% for e in events %}
  {{var("event_variables").e.start_date}}
{% endfor %}

2

There are 2 answers

2
connecttopawan On

Yes, you can call the variable in the SQL script using the var() function. For example, the following code will call the start_date property of the event_1 object:

select * from events
where event_date >= {{ var("event['event_1']['start_date']") }}
and event_date <= {{ var("event['event_1']['end_date']") }};

The var() function takes two arguments: the name of the variable and an optional default value. If the variable is not defined, the default value will be used. In this case, the default value is None.

The var() function is a Jinja function, so you need to wrap it in curly braces when you use it in a SQL script.

Here is the complete code for the SQL script:

{% set event = var("event") %}

select * from events
where event_date >= {{ var("event['event_1']['start_date']") }}
and event_date <= {{ var("event['event_1']['end_date']") }};

This code will first load the event variable from the dbt_project.yml file. Then, it will use the var() function to call the start_date property of the event_1 object. Finally, it will use the where clause to filter the events table to only include rows where the event_date is between the start date and end date of the event_1 event.

If you want to use jinja then, please try:

{% set event = var("event") %}

{% with event as e %}

select * from events
where event_date >= {{ e['event_1']['start_date'] }}
and event_date <= {{ e['event_1']['end_date'] }};

{% endwith %}
0
Amandine On

About your follow-up question, you can try the following:

{% set events = var("event") %}
 {% for e in events.values() %}
  {{ e.start_date }}
{% endfor %}