<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gabriel Campos on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Campos on Medium]]></description>
        <link>https://medium.com/@gabriel.campis?source=rss-1e95c2b0bc7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YWdxLPnNHXPGjKRkEVGrZQ.png</url>
            <title>Stories by Gabriel Campos on Medium</title>
            <link>https://medium.com/@gabriel.campis?source=rss-1e95c2b0bc7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:11:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabriel.campis/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Date dimension: How to Create a Practical and Useful Date Dimension in dbt]]></title>
            <link>https://medium.com/indiciumtech/date-dimension-how-to-create-a-practical-and-useful-date-dimension-in-dbt-5ee70a18f3bb?source=rss-1e95c2b0bc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ee70a18f3bb</guid>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[gauss]]></category>
            <dc:creator><![CDATA[Gabriel Campos]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 18:47:33 GMT</pubDate>
            <atom:updated>2024-12-01T23:25:02.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*NvwV5FtmS7TbLIvzs-U7fA.png" /></figure><p><em>A date dimension is a special table containing information about dates over a specific period. Its usage is crucial in data analysis environments like data warehouses. Creating one can significantly enhance the structure and context of data and simplify data development, grouping, aggregation, and filtering, for instance. In this text, I aim to demonstrate how to develop a useful date dimension using dbt and some packages that streamline its creation, like dbt_utils and dbt_dates. If you read until the end, you will see how to obtain a holiday column, including variable holidays like Carnival, Easter, and Corpus Christi, which are more complex to calculate.</em></p><p><strong>Context</strong></p><p>In the world of data analysis, the importance of a date dimension is often underestimated, but we cannot stress enough how essential it is to simplify and enhance our analyses. A well-designed date dimension is a fundamental tool for any analytical environment, and it plays a critical role in facilitating data comprehension and decision-making. Let’s delve into why this dimension is so crucial and how it can streamline our analyses.</p><p>Furthermore, a date dimension provides an organized framework for temporal data. It assigns a time context to information, which helps analysts better understand when events occurred. This is especially important when dealing with large volumes of data over time, as it enables data to be easily filtered and aggregated based on specific dates.</p><p>Additionally, with a date dimension, it becomes much simpler to identify trends and patterns over time. Analysts can easily compare current performance with the past, identify seasonality, and assess the impact of specific events on particular dates — all with just a join of this table. This helps answer critical questions such as “How did our sales perform this quarter compared to the previous quarter?” or “What was the impact of our last marketing campaign last year?”</p><p><strong>What are the important fields to have in a date dimension?</strong></p><p>It’s always essential to understand the business specifics to determine the most necessary fields for this table to facilitate analyses and assist business users in decision-making. Generally, the most basic fields to include in a date dimension are: <strong>Date; Day of the Year; Day of the Week; Month; Year; Bimonthly; Quarterly; Semester.</strong></p><p>In addition to these fields, it’s also important to provide them in a descriptive form. For example:</p><ul><li><strong>Semester</strong> | 2</li><li><strong>Semester Name</strong> | Second Semester</li><li><strong>Month</strong> | 7</li><li><strong>Month Name</strong> | July</li></ul><p>Furthermore, more complex fields can be crucial depending on the types of analyses to be performed. Some examples of these fields are:</p><ul><li><strong>Holidays</strong>: A field that identifies whether the date is a holiday or a special day. This can be important for analyses that take into account consumer behavior during holidays. It’s a more complex field to develop, especially because some holidays, like certain religious ones, are not fixed and depend on factors like the position of the sun, Easter dates, etc.</li><li><strong>Work Period</strong>: Indicates whether the date is a business day (workday), weekend, or holiday (non-workday). This can be useful for analyses that depend on behavior during workdays and weekends.</li></ul><p>Other information may not be as common but is relatively easy to create and can be necessary for business analyses:</p><ul><li><strong>Seasonal Information</strong>: For sectors highly influenced by seasonality, such as retail or tourism, you can include seasonal information like “holiday season” or “peak season.”</li><li>You could include the<strong> seasons of the year</strong>. It’s also important to consider geographical aspects because a company that exports goods to different hemispheres and geographical regions might want information on different seasons for the same month. For example, Summer in Europe and Winter in Argentina. This helps in understanding certain analyses. Or, if the business is related to the Northeast region of Brazil, you could have a “rainy season” or “dry season,” which could facilitate specific analyses.</li><li>Depending on the business requirements, you might even consider including very specific things. A very specific piece of information could be, for example, a column indicating years with El Niño, which can be important for certain agricultural analyses when these phenomena affect harvests.</li></ul><p>As you can see, it’s always important to pay attention to the nuances of the analyses and construct the date dimension to best facilitate and assist the users who will rely on this information.</p><p><strong>Let’s Work!</strong><br>To create the date dimension quickly and efficiently, we can utilize some packages available for dbt.</p><ul><li><a href="https://hub.getdbt.com/dbt-labs/dbt_utils/latest/"><strong>dbt_utils</strong></a>: The dbt utils package is quite versatile and offers a range of functions that aid developers. It’s worth exploring its capabilities. Regarding dates, the dbt_utils package includes the date spine function, which greatly simplifies the creation of a date dimension. However, it requires a bit more development to customize it to our liking.</li><li><a href="https://hub.getdbt.com/calogica/dbt_date/latest/"><strong>dbt_date</strong></a><strong>: </strong>The dbt_date package is quite interesting. In addition to simplifying date functions and making them agnostic to different analytical databases, it includes functions that can create complete date dimensions with all the general fields. Furthermore, some functions implement to this dimension as<a href="https://calogica.com/sql/dbt/2018/11/15/retail-calendar-in-sql.html"> 4–5–4 calendar</a> information. That’s why it’s the easiest way to create a date dimension.</li></ul><p>While the dbt_date package provides the data we need in a much more straightforward manner, there’s one challenge that I haven’t been able to solve as of writing this text. With dbt_utils, we can generate a date with a variable time interval of range, for example, setting the end_date to always be current_date plus 100 years. However, I haven’t found a simple way to achieve the same in the dbt_date package.</p><p><strong><em>First Step: Installing the Required Packages</em></strong></p><p>Firstly, you should list the necessary packages and their required versions in the packages.yml file.</p><figure><img alt="Screenshot of package.yml file" src="https://cdn-images-1.medium.com/max/345/1*4VRpSEU2peH9gagtFKyaMg.png" /><figcaption>Image 1 —Screenshot of packages.yml file.</figcaption></figure><p>If you don’t have this file, you can create it as shown in Image 1. In Image 2, you can see how to configure the package installations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*QqV-EZpIH9ghorUxk-6Y7A.png" /><figcaption>Image 2 — Screenshot of how to configure packages.yml.</figcaption></figure><p>So, after following these steps, you need to run the following command:</p><pre>dbt deps</pre><p>If everything goes as planned, you’ll have a folder with the dbt_packages containing the installed packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*k3U_MsQKSeD7oZ6-56ZbCw.png" /><figcaption>Image 3 — Screenshot of dbt_packages folder created with dbt deps.</figcaption></figure><p>Now that we have everything installed, let’s develop the table.</p><p><strong><em>Second step: develop the model.</em></strong></p><p>I’ll demonstrate how to create a date dimension using both packages, so you can choose the one that best suits your needs.</p><ol><li><strong><em>Using dbt_date:</em></strong><em> The easiest way to create a date dimension is with dbt_date!</em></li></ol><p>You just need to input the start date and end date using the package’s macro in the dbt model, as shown in the following example, and then run the dbt command to generate the table.</p><pre>{{ dbt_date.get_date_dimension(&quot;1990-01-01&quot;, &quot;2050-12-31&quot;) }}</pre><pre>dbt run --select dim_dates</pre><p>To materialize it as a table, you can include a configuration at the beginning of the model or set it directly in the dbt_project.yml.</p><pre>{{<br>    config(<br>        materialized = &quot;table&quot;<br>    )<br>}}<br><br>{{ dbt_date.get_date_dimension(&quot;1990-01-01&quot;, &quot;2050-12-31&quot;) }}</pre><p>And you will have a table like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNYR0zxu2DsH8Iq_P6aesQ.png" /><figcaption>Image 4 — Screenshot of the dim_dates created using dbt_date.get_date_dimension with the default columns.</figcaption></figure><p>In the following image, you can see all the fields that the package already provides us. However, you can complement this table with other important information if you find it necessary by creating additional CTEs in the model and bringing in other variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*HaMjq_huW7MWNJU7SUg8KQ.png" /><figcaption>Image 5 — Screenshot of default columns generated using dbt_date.get_date_dimension</figcaption></figure><p>To incorporate additional columns into your model, follow these steps in the example, using a CTE:</p><pre>with <br>    raw_generated_data as (<br>        {{ dbt_date.get_date_dimension(&quot;2015-01-01&quot;, &quot;2050-12-31&quot;) }}<br>    )<br><br>    , portuguese_renamed as (<br>        select <br>            raw_generated_data.*<br>            , case<br>                when raw_generated_data.day_of_week = 1 then &quot;Domingo&quot;<br>                when raw_generated_data.day_of_week = 2 then &quot;Segunda-feira&quot;<br>                when raw_generated_data.day_of_week = 3 then &quot;Terça-feira&quot;<br>                when raw_generated_data.day_of_week = 4 then &quot;Quarta-feira&quot;<br>                when raw_generated_data.day_of_week = 5 then &quot;Quinta-feira&quot;<br>                when raw_generated_data.day_of_week = 6 then &quot;Sexta-feira&quot;<br>                when raw_generated_data.day_of_week = 7 then &quot;Sábado&quot;<br>            end as day_of_week_name_pt<br>        from raw_generated_data<br>    )<br><br>select *<br>from portuguese_renamed</pre><p>Here, I am adding a column indicating the day of the week in Portuguese.</p><p>A very interesting thing is that when generating a date dimension with these packages (including using dbt utils), at least in BigQuery, which is the data warehouse I’m using for this example, it doesn’t process data for its creation, even if there are many rows being generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wlaqvuha76PUGbAdUY1E-A.png" /><figcaption>Image 6 — Screenshot of how much date dimension is processed.</figcaption></figure><p>As I mentioned earlier, the only difficulty I encountered with the dbt_date package was generating future dates with a predefined interval, which can be quite useful to avoid having to update the code eventually, even if you set a sufficiently large fixed interval when creating the date dimension using dbt_date. I couldn’t resolve this in a straightforward manner, except by modifying the macro.</p><p><strong><em>2. using dbt_utils</em></strong></p><p>Using the dbt_utils package to create a date dimension is a bit more involved, as you will need to, from the dates generated by the package’s function, create the necessary fields for your date dimension, including the more generic fields.</p><p>To do this, you need to be familiar with the date functions of the SQL in your data warehouse. In this example, I am using BigQuery.</p><p>Below, I provide a very simple example of how to create a date dimension using the dbt_utils package. Note that with this package, you can create a date dimension with an automatic interval starting from today’s date (or a specific date) for a scheduled period in the future. In the example below, it started in <em>1970–01–01</em> to the current date plus more than one hundred years.</p><pre>/* generating dates using the macro from the dbt-utils package */<br>with <br>    dates_raw as (<br>    {{ dbt_utils.date_spine(<br>        datepart=&quot;day&quot;,<br>        start_date=&quot;cast(&#39;1970-01-01&#39; as date)&quot;,<br>        end_date=&quot;date_add(current_date(), interval 100 year)&quot;<br>        )<br>    }}<br>)<br><br>/* extracting some date information and renaming some columns to Portuguese */<br>    , days_info as (<br>        select <br>            cast(date_day as date) as data_dia<br>            , extract(dayofweek from date_day) as dia_da_semana<br>            , extract(month from date_day) as mes<br>            , extract(quarter from date_day) as trimestre<br>            , extract(dayofyear from date_day) as dia_do_ano<br>            , extract(year from date_day) as ano<br>            , format_date(&#39;%B&#39;, date_day) as mes_ingles<br>            , format_date(&#39;%d-%m&#39;, date_day) as dia_mes<br>        from dates_raw<br>    )<br><br>/* renaming the column meanings, translating them into Portuguese */<br>    , days_named as (<br>        select<br>            *<br>            , case<br>                when dia_da_semana = 1 then &#39;Domingo&#39;<br>                when dia_da_semana = 2 then &#39;Segunda-feira&#39;<br>                when dia_da_semana = 3 then &#39;Terça-feira&#39;<br>                when dia_da_semana = 4 then &#39;Quarta-feira&#39;<br>                when dia_da_semana = 5 then &#39;Quinta-feira&#39;<br>                when dia_da_semana = 6 then &#39;Sexta-feira&#39;<br>                else &#39;Sábado&#39; <br>            end as nome_do_dia<br>            , case<br>                when mes = 1 then &#39;Janeiro&#39;<br>                when mes = 2 then &#39;Fevereiro&#39;<br>                when mes = 3 then &#39;Março&#39;<br>                when mes = 4 then &#39;Abril&#39;<br>                when mes = 5 then &#39;Maio&#39;<br>                when mes = 6 then &#39;Junho&#39;<br>                when mes = 7 then &#39;Julho&#39;<br>                when mes = 8 then &#39;Agosto&#39;<br>                when mes = 9 then &#39;Setembro&#39;<br>                when mes = 10 then &#39;Outubro&#39;<br>                when mes = 11 then &#39;Novembro&#39;<br>                else &#39;Dezembro&#39; <br>            end as nome_do_mes<br>            , case<br>                when mes = 1 then &#39;Jan&#39;<br>                when mes = 2 then &#39;Fev&#39;<br>                when mes = 3 then &#39;Mar&#39;<br>                when mes = 4 then &#39;Abr&#39;<br>                when mes = 5 then &#39;Mai&#39;<br>                when mes = 6 then &#39;Jun&#39;<br>                when mes = 7 then &#39;Jul&#39;<br>                when mes = 8 then &#39;Ago&#39;<br>                when mes = 9 then &#39;Set&#39;<br>                when mes = 10 then &#39;Out&#39;<br>                when mes = 11 then &#39;Nov&#39;<br>                else &#39;Dez&#39; <br>            end as abrev_do_mes<br>            , case<br>                when trimestre = 1 then &#39;1º Trimestre&#39;<br>                when trimestre = 2 then &#39;2º Trimestre&#39;<br>                when trimestre = 3 then &#39;3º Trimestre&#39;<br>                else &#39;4º Trimestre&#39; <br>            end as nome_trimestre<br>            , case<br>                when trimestre in(1,2) then 1<br>                else 2<br>            end as semestre<br>            , case<br>                when trimestre in(1,2) then &#39;1º Semestre&#39;<br>                else &#39;2º Semestre&#39;<br>            end as nome_semestre<br>        from days_info<br>    )<br><br>/* rearranging the columns */<br>    , final_cte as (<br>        select <br>            data_dia<br>            , dia_da_semana<br>            , nome_do_dia<br>            , mes<br>            , mes_ingles<br>            , nome_do_mes<br>            , abrev_do_mes<br>            , trimestre<br>            , nome_trimestre<br>            , semestre<br>            , nome_semestre<br>            , dia_do_ano<br>            , ano<br>        from days_named<br>    )<br><br>select * <br>from final_cte</pre><p>Furthermore, as I can demonstrate in the screenshot below, the processing time remained at zero even when generating a large number of data rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlOq2O454KjMxmvCMTM7qg.png" /><figcaption>Image 7 — Screenshot of how much date dimension using dbt_utils is processed.</figcaption></figure><p><strong><em>Extra: Including the holiday field in our date dimension</em></strong></p><blockquote><em>Although you can easily upload a CSV file via </em>dbt seed<em> with a mapping of holidays for the year, sometimes it’s a bit tedious to do it manually and update it now and then. Plus, you may not find a table with all the holidays in a very distant future timeframe. (By the way, I think this is a great strategy! I’m just teaching you another one. Keeping things simple is always good!)</em></blockquote><p>As I mentioned earlier, a holiday field is one of the interesting fields to have in a date dimension. However, calculating it can be a bit tricky since not all holidays have fixed dates. Many religious holidays like Carnival or Corpus Christi are tied to Easter, which can vary. Therefore, to calculate these religious holidays, you need to determine the date of Easter.</p><p>To make it clearer, Carnival is a celebration that occurs 47 days before Easter. The date of Easter, in turn, is calculated based on the lunar cycle and the spring equinox. As a result, the date of Carnival can vary from February to March, depending on the date of Easter. Easter’s date is determined by the lunar calendar and follows the spring equinox in the Northern Hemisphere. It falls on the first Sunday after the first full moon following the spring equinox. Corpus Christi, on the other hand, is celebrated 50 days after Easter Sunday.</p><p>As you can see, understanding the date of Easter is crucial for calculating these religious holidays and including them in our date dimension.</p><p>For this example of creating a holiday column, I’ll use the Brazilian calendar as a reference. In Brazil, there are 8 fixed holidays and 3 non-fixed holidays, which are the religious ones. The Carnival holiday, in particular, can have more than one non-working day.</p><p>Here is an example of how to generate the Easter date using Gauss’s Easter algorithm that I found in <a href="https://www.sqlservercentral.com/scripts/calculating-easter-in-sql">this text</a>. I rewrote the author’s query for Bigquery and used a CTE, as I find it easier to develop and more readable.</p><pre>with <br>    dates_raw as (<br>    /* generating dates using the macro from the dbt-utils package */<br>    {{ dbt_utils.date_spine(<br>        datepart=&quot;day&quot;,<br>        start_date=&quot;cast(&#39;1970-01-01&#39; as date)&quot;,<br>        end_date=&quot;date_add(current_date(), interval 100 year)&quot;<br>        )<br>    }}<br>)<br><br>    , days_info as (<br>    /* extracting some date information and renaming some columns to portuguese */<br>        select <br>            cast(date_day as date) as data_dia<br>            , extract(dayofweek from date_day) as dia_da_semana<br>            , extract(month from date_day) as mes<br>            , extract(quarter from date_day) as trimestre<br>            , extract(dayofyear from date_day) as dia_do_ano<br>            , extract(year from date_day) as ano<br>            , format_date(&#39;%b&#39;, date_day) as mes_ingles<br>            , format_date(&#39;%d-%m&#39;, date_day) as dia_mes<br>        from dates_raw<br>    )<br><br>    , days_named as (<br>    /* extracting some date information and renaming some columns to portuguese */<br>        select<br>            *<br>            , case<br>                when dia_da_semana = 1 then &#39;domingo&#39;<br>                when dia_da_semana = 2 then &#39;segunda-feira&#39;<br>                when dia_da_semana = 3 then &#39;terça-feira&#39;<br>                when dia_da_semana = 4 then &#39;quarta-feira&#39;<br>                when dia_da_semana = 5 then &#39;quinta-feira&#39;<br>                when dia_da_semana = 6 then &#39;sexta-feira&#39;<br>                else &#39;sábado&#39; <br>            end as nome_do_dia<br>            , case<br>                when mes = 1 then &#39;janeiro&#39;<br>                when mes = 2 then &#39;fevereiro&#39;<br>                when mes = 3 then &#39;março&#39;<br>                when mes = 4 then &#39;abril&#39;<br>                when mes = 5 then &#39;maio&#39;<br>                when mes = 6 then &#39;junho&#39;<br>                when mes = 7 then &#39;julho&#39;<br>                when mes = 8 then &#39;agosto&#39;<br>                when mes = 9 then &#39;setembro&#39;<br>                when mes = 10 then &#39;outubro&#39;<br>                when mes = 11 then &#39;novembro&#39;<br>                else &#39;dezembro&#39; <br>            end as nome_do_mes<br>            , case<br>                when mes = 1 then &#39;jan&#39;<br>                when mes = 2 then &#39;fev&#39;<br>                when mes = 3 then &#39;mar&#39;<br>                when mes = 4 then &#39;abr&#39;<br>                when mes = 5 then &#39;mai&#39;<br>                when mes = 6 then &#39;jun&#39;<br>                when mes = 7 then &#39;jul&#39;<br>                when mes = 8 then &#39;ago&#39;<br>                when mes = 9 then &#39;set&#39;<br>                when mes = 10 then &#39;out&#39;<br>                when mes = 11 then &#39;nov&#39;<br>                else &#39;dez&#39; <br>            end as abrev_do_mes<br>            , case<br>                when trimestre = 1 then &#39;1º trimestre&#39;<br>                when trimestre = 2 then &#39;2º trimestre&#39;<br>                when trimestre = 3 then &#39;3º trimestre&#39;<br>                else &#39;4º trimestre&#39; <br>            end as nome_trimestre<br>            , case<br>                when trimestre in(1,2) then 1<br>                else 2<br>            end as semestre<br>            , case<br>                when trimestre in(1,2) then &#39;1º semestre&#39;<br>                else &#39;2º semestre&#39;<br>            end as nome_semestre<br>        from days_info<br>    )<br><br>    /* creating day of easter with gauss&#39; easter algorithm */<br><br>    , passo1 as (<br>        select<br>            days_named.*<br>            , mod(ano, 19) as a<br>        from days_named<br>    )<br><br>    , passo2 as (<br>        select<br>            p1.*<br>            , cast(floor(p1.ano / 100) as int64) as b<br>            , mod(p1.ano, 100) as c<br>        from passo1 as p1<br>    )<br>    <br>    , passo3 as (<br>        select<br>            p2.*<br>            , cast(floor(p2.b / 4) as int64) as d<br>            , mod(p2.b, 4) as e<br>            , cast(floor((p2.b + 8) / 25) as int64) as f<br>            , cast(floor((p2.b - cast(floor((p2.b + 8) / 25) as int64) + 1) / 3) as int64) as g<br>        from passo2 as p2<br>    )<br>    <br>    , passo4 as (<br>        select<br>            p3.*<br>            , mod((19 * p3.a + p3.b - p3.d - p3.g + 15), 30) as h<br>        from passo3 as p3<br>    )<br>    <br>    , passo5 as (<br>        select<br>            p4.*<br>            , cast(floor(p4.c / 4) as int64) as i<br>            , mod(p4.c, 4) as k<br>            , mod((32 + 2 * p4.e + 2 * cast(floor(p4.c / 4) as int64) - p4.h - mod(p4.c, 4)), 7) as l<br>        from passo4 as p4<br>    )<br>    <br>    , passo6 as (<br>        select<br>            p5.*<br>            , cast(floor((p5.a + 11 * p5.h + 22 * p5.l) / 451) as int64) as m<br>        from passo5 as p5<br>    )<br>    <br>    , passo7 as (<br>        select<br>            p6.*<br>            , p6.ano as ano_pascoa<br>            , cast(floor((p6.h + p6.l - 7 * p6.m + 114) / 31) as int64) as mes_pascoa<br>            , mod((p6.h + p6.l - 7 * p6.m + 114), 31) + 1 as dia_pascoa<br>        from passo6 as p6<br>    )<br><br>    , final_easter_rule as (<br>        select<br>            *<br>            , cast(concat(ano_pascoa,&#39;-&#39;, mes_pascoa,&#39;-&#39;, dia_pascoa) as date) as data_pascoa<br>        from passo7 as p7<br>    )<br><br>    , final_cte as (<br>      /* creating hollidays and rearranging the columns */<br>        select<br>            data_dia<br>            , dia_da_semana<br>            , nome_do_dia<br>            , mes<br>            , mes_ingles<br>            , dia_mes<br>            , nome_do_mes<br>            , abrev_do_mes<br>            , trimestre<br>            , nome_trimestre<br>            , semestre<br>            , nome_semestre<br>            , dia_do_ano<br>            , ano<br>            , data_pascoa<br>            , case<br>                when dia_mes = &#39;01-01&#39; then &#39;Confraternização Universal (ano novo)&#39;<br>                when dia_mes = &#39;21-04&#39; then &#39;Tiradentes&#39;<br>                when dia_mes = &#39;01-05&#39; then &#39;Dia do Trabalhador&#39;<br>                when dia_mes = &#39;07-09&#39; then &#39;Independência do Brasil&#39;<br>                when dia_mes = &#39;12-10&#39; then &#39;Nossa Senhora Aparecida&#39;<br>                when dia_mes = &#39;02-11&#39; then &#39;Finados&#39;<br>                when dia_mes = &#39;15-11&#39; then &#39;Proclamação da República&#39;<br>                when dia_mes = &#39;25-12&#39; then &#39;Natal&#39;<br>                when data_dia = date_sub(data_pascoa, interval 48 day) then &#39;Primeiro dia de Carnaval&#39;<br>                when data_dia = date_sub(data_pascoa, interval 47 day) then &#39;Segundo dia de Carnaval&#39;<br>                when data_dia = date_sub(data_pascoa, interval 2 day) then &#39;Paixão de Cristo&#39;<br>                when data_dia = date_add(data_pascoa, interval 60 day) then &#39;Corpus Christi&#39;<br>                when ano &gt;= 2024 and dia_mes = &#39;20-11&#39; then &#39;Dia Nacional de Zumbi e da Consciência Negra&#39;<br>                else null <br>            end as nome_feriado<br>        from final_easter_rule<br>    )<br><br>select * <br>from final_cte</pre><p>To make this example more practical, we can generate the Easter date through a macro that we can create ourselves and call later in the code. But <strong>I will do this in an upcoming text here on Medium</strong>, so this current text doesn’t get too long.</p><p>Now let’s verify if our holidays are correct. To do that, we will query the date dimension we created to obtain the holiday results for 2024 and compare them to an official Brazilian calendar. However, remember we could even automatically do a singular test using dbt to verify the accuracy of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*nc8MEZiUn0KIP-a4mdIgdw.png" /><figcaption>Image 8 — query in BigQuery to get results from our date dimension about holidays in 2024</figcaption></figure><p>Next, we have the query result, and we will compare it with information from an official calendar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*z9GQYXMF4yC1Ojt62KezLQ.png" /><figcaption>Image 9 — result from the previous query</figcaption></figure><p>It is evident that our result aligns with the <a href="https://www.anbima.com.br/feriados/fer_nacionais/2024.asp">official one</a>. :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*mEY27GnqTS_WySBNH4iHFw.png" /><figcaption>Image 10 — Calendar from Anbima — Associação Brasileira das Entidades dos Mercados Financeiro e de Capitais (in Portuguese).</figcaption></figure><blockquote>PS.: In 2024, the Brazilian Government instituted a new national holiday, the National Day of Zumbi and Black Consciousness, celebrated on November 20th. Therefore, to make our date dimension even more complete, we would need to add a new rule for holidays, where starting in 2024, November 20th becomes a holiday.</blockquote><p>In this brief text, I’ve attempted to demonstrate the significance of having a date dimension in your data warehouse. I’ve also introduced some key field examples and shown how we can create them practically in dbt using various packages. Furthermore, I’ve shown how to develop a column for holidays in the date dimension, including those holidays that depend on the date of Easter for their calculation.</p><p>I hope this text has been useful to you in some way!</p><p>Thank you! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ee70a18f3bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/indiciumtech/date-dimension-how-to-create-a-practical-and-useful-date-dimension-in-dbt-5ee70a18f3bb">Date dimension: How to Create a Practical and Useful Date Dimension in dbt</a> was originally published in <a href="https://medium.com/indiciumtech">Indicium AI Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple tips to make datasets cleaner using dbt and BigQuery]]></title>
            <link>https://medium.com/indiciumtech/simple-tips-to-make-datasets-cleaner-using-dbt-and-bigquery-bf904f2b78dd?source=rss-1e95c2b0bc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf904f2b78dd</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[ephemeral]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Gabriel Campos]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 21:19:34 GMT</pubDate>
            <atom:updated>2024-04-13T20:56:33.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*nKthp8VnirwYdi0Qhfo3MA.jpeg" /></figure><p>It is quite common that during the process of building a data warehouse (DW), table names can be changed, leaving several old tables unused in the DW, or for each personal schema, there are test tables no longer in use. In the long run, this can create a lot of pollution within these schemas so developers can get confused about whether that table is still in use or not, or whether such tables can be deleted. Also, these tables can stay there in the database just taking up unnecessary space. So, thinking about improving this situation, I want to describe two very simple tips that can help to make schemas (called datasets in BigQuery) a little more organized.</p><h3><strong>The first tip pertains to table expiration settings in the development environment</strong></h3><p>By default, tables created by dbt never expire. However, you can define expiration rules through dbt so that tables generated by a model will expire after a specified number of hours. There are two methods to configure this:</p><pre>{{ config(<br>    hours_to_expiration = 72<br>) }}<br><br>select *<br>from my_model</pre><p>This configuration above can be done in the model and causes the table generated by the model to expire in 72 hours (you can choose the expiration time that is most convenient for you). However, I particularly prefer the second option below, which is made in dbt_project.yml.</p><pre>...<br><br>models:<br>  project_dbt: <br>    +hours_to_expiration: 72<br>     staging: ...</pre><p>I prefer this second option as I find it easier to set up with some jinja a configuration that causes table expiration in 72h to be inserted only into tables in the development schemas/datasets. An example of how to do this is shown below.</p><pre>models:<br>  project_dbt: <br>    +hours_to_expiration: &quot;{{ &#39;72&#39; if target.name==&#39;dev&#39; else none }}&quot;<br>     staging: ...</pre><blockquote><em>Usually, the development targets are set as “dev” in profiles.yml in dbt, that’s why I use it in the code</em></blockquote><p>This configuration dictates that if the model runs in development, a clause will be enforced causing the tables to expire in 72 hours. However, if the model runs in production, this setting will not be applied. <strong>It’s crucial to avoid using this configuration in the production pipeline to prevent the expiration of production tables.</strong></p><p>Now, you can apply this setting differently to development schemas if you believe it’s more suitable for the project. When a table generated by a model is no longer in use and is forgotten in the development database, there’s no need to worry because it will be automatically deleted from the database after the specified time.</p><h3><strong>The second tip is related to the ephemeral configuration in dbt</strong></h3><p>Another strategy to maintain a cleaner schema/dataset in production involves using ephemeral materialization in dbt. This materialization type doesn’t directly write to the database, making it suitable for use on layers before the mart layer. With this setup, dbt writes the layers preceding the materialized layer as CTEs, avoiding the creation of intermediate tables in the database.</p><p>Implementing this configuration results in a cleaner production schema, as it eliminates the need for staging and intermediate tables that form the marts’ layer. Moreover, it can lead to storage savings, especially in Data Warehouses where storage costs apply.</p><blockquote><em>However, it’s essential to exercise caution when configuring ephemeral materialization. Personally, I recommend applying this configuration only in production. During development, materializing as a table might be more appropriate.</em></blockquote><p>One of the main drawbacks of ephemeral materialization is its impact on the debugging process. Since it doesn’t write to the database, debugging becomes more challenging as observing its output and correcting errors becomes more cumbersome. This is why I prefer applying this configuration solely in the production environment.</p><p>Having laid out these considerations, here’s an example of how to configure ephemeral materialization specifically for the production environment. This configuration is implemented in the dbt_project.yml file.</p><pre>...<br><br>models:<br>  project_dbt: <br>    +hours_to_expiration: &quot;{{ &#39;72&#39; if target.name==&#39;dev&#39; else none }}&quot;<br>     staging:    <br>        +materialized: &quot;{{&#39;ephemeral&#39; if target.name==&#39;prod&#39; else &#39;table&#39; }}&quot;<br>     intermediate:<br>        +materialized: &quot;{{&#39;ephemeral&#39; if target.name==&#39;prod&#39; else &#39;table&#39; }}&quot;<br>     marts:<br>        +materialized: table<br>...</pre><p>In this simple article, I showed you how to make datasets/schemas a little cleaner with table expiration time strategies and materialization as ephemeral.</p><p>Feel free to comment with your questions and suggestions, or to criticize.</p><p>For more content like this, you can follow <a href="https://medium.com/indiciumtech">Indicium</a> here on Medium and <a href="https://www.linkedin.com/company/indiciumtech/">Linkedin</a>, and <a href="https://www.linkedin.com/in/gabrielcampis/">follow me</a> on those networks as well. ;)</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf904f2b78dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/indiciumtech/simple-tips-to-make-datasets-cleaner-using-dbt-and-bigquery-bf904f2b78dd">Simple tips to make datasets cleaner using dbt and BigQuery</a> was originally published in <a href="https://medium.com/indiciumtech">Indicium AI Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sampling data with dbt and BigQuery: a strategy to reduce costs]]></title>
            <link>https://medium.com/indiciumtech/sampling-data-with-dbt-and-bigquery-a-strategy-to-reduce-costs-ef059b9e2144?source=rss-1e95c2b0bc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef059b9e2144</guid>
            <category><![CDATA[cost-management]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sample]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <dc:creator><![CDATA[Gabriel Campos]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 17:44:57 GMT</pubDate>
            <atom:updated>2023-02-24T19:59:11.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Qwc--mAcxwlL0xlcUVHgw.png" /></figure><p>When modeling data with <strong><em>dbt</em></strong> or simply when creating some table directly through <strong><em>BigQuery</em></strong>, you may have come across very large tables, which made data transformation costs quite expensive, especially in environments that charge for processing. So my goal with this text is to describe a way to work with data transformation using sample data, with <em>dbt</em> and <em>BigQuery</em>. I hope with this text to help others who are interested in better managing the costs of data transformations in projects that involve building a data warehouse, or to bring a discussion about how to work with sample data in a better way.</p><h3><strong>Tablesample function and partitioned tables</strong></h3><p>Before going into how to work directly with sample data in <em>dbt</em> and <em>BigQuery</em>, it seems appropriate to first talk about the <strong><em>BigQuery</em> tablesample function</strong> and the use of <strong>partitioned tables</strong>.</p><p>Let’s say you want to run the following example query in order to reduce costs:</p><pre>select<br>  food_id<br>  , food_type<br>  , food_descripton<br>from `food_project.schema_food.food_table_raw`<br>where date = &#39;2022-07-08&#39;<br>limit 5</pre><p>It is a common misconception that using the <strong><em>where</em></strong> clause will reduce data processing. It doesn’t work because in order to find the <strong><em>where</em></strong> condition, <em>BigQuery</em> will examine all records to identify if the date (2022–07–08) used in <strong><em>where</em></strong> clause is part of the record. Also, using limit does not reduce the amount of data processed. Another mistake is to think that the limit clause will bring in a random subset of data from a table. It doesn’t happen.</p><p>According to the google cloud platform documentation about the <a href="https://cloud.google.com/bigquery/docs/table-sampling"><strong><em>tablesample</em> </strong>function</a>, we have that:</p><blockquote>Unlike the LIMIT clause, TABLESAMPLE returns a random subset of data from a table. Also, BigQuery does not cache the results of queries that include a TABLESAMPLE clause, so the query might return different results each time.</blockquote><p>Thus, the following query selects a 30% sample of the data from the table:</p><pre>select<br>  food_id<br>  , food_type<br>  , food_descripton<br>from `food_project.schema_food.food_table_raw` tablesample system (30 percent)</pre><p>According to the official documentation of the<strong> tablesample</strong> function, <em>BigQuery</em> tables are stored in data blocks. Therefore, in this example the tablesample clause caused the query to randomly select 30% table blocks by reading the rows only in the selected blocks, which also saves costs by not having to read the entire table.</p><p>You can combine the <strong>tablesample</strong> with other clauses, such as where. In the following example case, the query selects data from only 30% of blocks in the table and searches within these selected blocks only those that have the desired date.</p><pre>select<br>  food_id<br>  , food_type<br>  , food_descripton<br>from `food_project.schema_food.food_table_raw` tablesample system (30 percent)<br>where cd_date = &#39;2022-07-08&#39;</pre><p>There are other examples of clause combinations and more definitions of the function in its <a href="https://cloud.google.com/bigquery/docs/table-sampling"><strong>official documentation</strong></a>.</p><p>Another way to further reduce costs is to create the sample tables as <strong>partitioned tables</strong>. The following example <strong>partitions</strong> the table by extraction date.</p><pre>create or replace table `food_project.schema_food.food_table_sample` partition by date_trunc(extraction_date, day) as (<br><br>select<br>  food_id<br>  , food_type<br>  , food_descripton<br>from `food_project.schema_food.food_table_raw` tablesample system (30 percent)<br>where cd_date = &#39;2022-07-08&#39;<br>  <br>)</pre><p>According to the <a href="https://www.cloudskillsboost.google/focuses/3694?locale=en&amp;parent=catalog"><strong>GCP courses </strong>about<strong> </strong>partitioned table</a>,</p><blockquote>a partitioned table is a table that is divided into segments, called partitions, that make it easier to manage and query your data. By dividing a large table into smaller partitions, you can improve query performance, and control costs by reducing the number of bytes read by a query.</blockquote><p>However, if you create samples from already partitioned tables you should keep in mind that <strong><em>tablesample</em></strong> from partitioned tables tend to be more biased, since partitioning produces blocks where the rows in each block have the same partitioning key.</p><h3><strong>Creating and working with data sample in dbt</strong></h3><p>After having covered the topics of partitioned tables and tablesample function, my goal is to present a way of working with <strong>sample data</strong> in <em>dbt</em>, using <em>BigQuery</em>.</p><p>First, you must create a folder for samples inside the models folder of your <em>dbt</em> project. You can name it as “samples”, for example. It is interesting to have a folder for each data source within the “samples” folder you created, in order to better organize your work.</p><p>Inside the <strong>sample folder</strong> and inside the data source folder where you want to sample, you should create a <strong>.sql</strong> file to write the code that does the sampling.</p><pre>{{ config(<br> materialized=&#39;table&#39;,<br>   partition_by={<br>    &quot;field&quot;: &quot;extraction_date&quot;,<br>    &quot;data_type&quot;: &quot;date&quot;,<br>   }<br>)}}<br><br>with <br> raw_table as (<br>      select<br>        food_id<br>        , food_type<br>        , food_descripton<br>       , parse_date(&#39;%Y-%m-%d&#39;, extracted_at) as extraction_date<br>      from {{ source(&#39;data_source_food&#39;, &#39;food_table_raw&#39;) }} tablesample system (30 percent)<br>      where cd_date = &#39;2022-07-08&#39;<br>    )<br><br>select *<br>from raw_table</pre><p>Note that we are partitioning the sample table created by extraction date, and we are selecting only 30% of the storage blocks in the table with a where clause that specifies only the cd_date is ‘2022–07–08’.</p><p><strong>Attention:</strong> When sampling data, make sure you get the same sample range. For example, if table1 needs to join with table2 and both have a sample with different dates, there will certainly be a “miss join” between these tables.</p><p>After creating the sample model for the desired table, add a <strong>sample_source.yml</strong> file for this created table, as in the following example:</p><pre>version: 2<br><br>sources:<br>  - name: sample_raw_food<br>    tables: <br>      - name: sample_food_table</pre><p>After these steps you should have set up some specifics in your <strong>profiles</strong> file and in <strong>dbt_project.yml</strong>. Below you will find an example of how to do it in <strong>profiles.yml</strong>.</p><pre>project_dbt:<br>  target: dev<br>  outputs:<br>    dev:<br>      type: bigquery<br>      method: oauth<br>      project: dw-project<br>      dataset: stg_analyst_name<br>      threads: 2<br>      timeout_seconds: 300<br>      priority: interactive<br>      retries: 1<br>      maximum_bytes_billed: 5500000000<br>    sample:<br>      type: bigquery<br>      method: oauth<br>      project: dw-project<br>      dataset: sample_raw<br>      threads: 2<br>      timeout_seconds: 300<br>      priority: interactive<br>      retries: 1<br>      maximum_bytes_billed: 5500000000</pre><p>Notice that there is a sample configuration, in addition to the usual configuration for running on the dev environment, just below the personal configuration. This makes it possible to run the following code for the samples to be inserted into the sample_raw schema:</p><pre>dbt run --target sample</pre><p>or</p><pre>dbt run -m sample_model --target sample</pre><p>Then, by running these codes, you will cause dbt to create in the <em>BigQuery</em> sample schema the tables with the sample results. (Schema is called dataset in <em>BigQuery</em>)</p><p>After generating the sample data in schema sample, you could already work with this data. However, there is another interesting configuration in <strong>dbt_project.yml</strong> that might reduces costs.</p><p>After you create a sample data, you don’t need to create it again and again. So, let’s set dbt_project to disable the folder where the sample data is located. Data models in the sample folder will not run if the +enabled clause is set to false.</p><pre>models:<br>project_dbt:<br> samples:<br>     +enabled: false<br>        +materialized: table<br>        source_food:<br>         +schema: food</pre><p>Notice that there is an enable field, which enables permission to run data models from “samples” folder. Whenever you want to run a data sample, you must change the enabled from <strong><em>false</em></strong> to <strong><em>true</em></strong>. By making this change you will cause the data models in the “samples” folder to be enabled to run. After running the models to create the samples, disable it by changing it to <strong><em>false</em></strong> again. This will reduce unnecessary costs, since data samples will not be generated constantly.</p><p>You can make this switch from <strong><em>True</em></strong> to<strong> <em>False</em></strong> happen automatically. Just use the following Jinja as shown in the code below.</p><pre>models:<br>project_dbt:<br> samples:<br>     +enabled: &quot;{{ true if target.name==&#39;sample&#39; else false }}&quot;<br>        +materialized: table<br>        source_food: <br>         +schema: food</pre><h3><strong>Alternating between the sample data and the original data</strong></h3><p>After all the necessary settings are made, you can now use the sample data to do the data transformations and build your Data Warehouse in order to save costs.</p><p>However, it is important to use some <strong>jinja</strong> in the models that use the sample data specifically. So dbt can switch between the sample data, in the development environments and the original data in the production environment. Below is an example of how to use <strong>jinja</strong> to achieve this alternation of environments.</p><pre>with <br> example_table as (<br>     select <br>        food_id<br>        , food_type<br>        , food_description<br>       {% if target.name == &#39;prod&#39; %}<br>       from {{ source(&#39;data_source_food&#39;, &#39;food_table_raw&#39;) }}<br>       {% else %}<br>       from {{ source(&#39;sample_raw_food&#39;, &#39;sample_food_table&#39;) }}<br>       {% endif %}<br>    )<br>    <br>select *<br>from example_table</pre><p>This way, if we are not running in production or without the target prod, <em>dbt</em> will run the model with the data from the sample table.</p><h3><strong>Closing remarks</strong></h3><p>Using sample data to transform and to model data is very important for cost management in a project that uses a larger volume of data.</p><p>I briefly presented the tablesample function and how to partition tables in <em>BigQuery</em>, and a strategy for working with sample data using <em>dbt</em>. I hope this text will be useful to anyone who is interested in <em>dbt</em> optimization.</p><p>I have described the strategy that I know. If you know another more interesting one for working with sample data, or would like to contribute some improvement whith this one, I’ll be very glad. This would be of immense importance to the <em>dbt</em> community.</p><p>I hope you like it. Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef059b9e2144" width="1" height="1" alt=""><hr><p><a href="https://medium.com/indiciumtech/sampling-data-with-dbt-and-bigquery-a-strategy-to-reduce-costs-ef059b9e2144">Sampling data with dbt and BigQuery: a strategy to reduce costs</a> was originally published in <a href="https://medium.com/indiciumtech">Indicium AI Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>