dbt
(data build tool) is revolutionizing the way we do the process of extracting value from our data.
This package allows Jupyter notebooks to be used for developing dbt models and analyses in complement with other dbt command line tools and VS Code extensions.
pip install git+https://github.com/butchland/nbdbt.git
The %%dbt
cell magic allows you to create models and analyses in your dbt project.
To use the %%dbt
cellmagic in your notebook, you have to load the dbt cellmagic module first via %load_ext
or %reload_ext
line magics
%reload_ext nbdbt.dbt_cellmagic
The %dbtconfig
line magic configures a default project (and optionally the dbt profiles directory with -d
flag as well as the notebook path with the -n
flag).
%dbtconfig -p ../my_dbt_project -n notebooks/index.ipynb
The next cell uses the %%dbt
cell magic which will create a new model my_third_model
and compile it as well.
%%dbt -a my_fourth_model models/my_fourth_model.sql
select *
from {{ ref('my_second_dbt_model') }}
We then assigned the result of the compilation to the my_third_model
variable, which is a Dbt (cell) magic object
my_fourth_model
The ref
method on DbtMagicObject
allows us to run the query and save the results into a dataframe.
results = my_fourth_model.ref()
results # dataframe
The dbt magic object also has access to other useful properties (like the compiled sql used to create the results)
print(my_fourth_model._compiled_sql)
We can then run the usual dbt commands to generate the model
%cd ../my_dbt_project
! dbt run --select my_fourth_model
%cd ../nbs
import nbdbt.dbt_cellmagic as nbc
nbc.clear_cache() # clears nbdtcache