<?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 Thành Phương on Medium]]></title>
        <description><![CDATA[Stories by Thành Phương on Medium]]></description>
        <link>https://medium.com/@phoenix-analytics?source=rss-2785565b1dc8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*sAhfwaaB2z8u0fFd.jpg</url>
            <title>Stories by Thành Phương on Medium</title>
            <link>https://medium.com/@phoenix-analytics?source=rss-2785565b1dc8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:26:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@phoenix-analytics/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[Building Data Warehouse in BigQuery using dbt]]></title>
            <link>https://phoenix-analytics.medium.com/building-data-warehouse-in-bigquery-using-dbt-a1c68a84f21e?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1c68a84f21e</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 02:16:34 GMT</pubDate>
            <atom:updated>2025-04-14T02:16:34.743Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I will guide you through the process of designing, implementing, and analyzing a near-real-time Data Warehouse (DW) prototype for a logistics company</p><p>💡 Our Data Platform will be constructed on Google Cloud</p><ul><li>Cloud Storage and Biglake engine for Data Lake House</li><li>BigQuery for an OLAP Data Warehouse</li><li>ETL Tools: DBT for transforming data</li><li>Data management tools: Open Metadata is a data observability platform that provides a place</li><li>Data Access and Analytical tools: Redash, Looker, Metabase,..</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-hlNX1OUwkmPdQXM.png" /><figcaption>Data Flow</figcaption></figure><ol><li>A data ingestion service that connects to and extracts the data you need from the applications, databases and websites that hold the data used to run your business</li><li>A data warehouse database is typically provided as a fully managed service by one of the big cloud vendors, for example, Google Cloud, so that you don’t have to buy servers and hire DBAs to tell you that none of the backups would restore and one ever tested them anyway</li><li>A self-service BI tool that’s designed to let business users get access to the data they need without having to ask IT to build reports for them</li></ol><h3>What is a Data Warehouse?</h3><p>A data warehouse is an enterprise system used for the analysis and reporting of structured and semi-structured data from multiple sources. It is well suited for ad hoc analysis and custom reporting requirements. Based on the requirements a data warehouse can store both current and historical data in one place and is designed to give a long-range view of data over time.</p><h3>The Importance of Data Warehousing</h3><p><strong>a. Improved Data Quality:</strong> Data warehousing processes, including data validation, cleaning, and transformation, lead to higher data quality and consistency.</p><p><strong>b. Enhanced Business Intelligence:</strong> A data warehouse enables valuable insights and data-driven decisions by providing a comprehensive view of an organization’s data.</p><p><strong>c. Increased Efficiency:</strong> Data warehouses consolidate data from multiple sources, reducing the time and effort required to access and analyze data.</p><p><strong>d. Scalability:</strong> Data warehouses are designed to handle large volumes of data, making them highly scalable and adaptable to an organisation&#39;s evolving needs.</p><p><strong>e. Historical Data Analysis:</strong> Data warehouses store historical data, allowing organizations to analyze trends and make informed decisions based on past performance.</p><h3>Medallion Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWUY5F9f7jHWmWKghGdnog.png" /></figure><p>in our data warehouse project, we decide to use the Medallion framework providing a structured and convenient approach to implement data quality measures at each layer of the data processing pipeline.</p><h3>Source layer</h3><p>The source layer is a logical layer that contains all the information about the data to be ingested into the data warehouse. These are all the data sources where raw data originates and is stored. They could include Sales, CRM, Marketing, ERP, IoT, and more systems.</p><p>Data is pulled from the source layer to the staging layer with different data ingestion techniques such as Batch Processing, Data Streaming, and Change Data Capture (CDC).</p><h3>Staging layer</h3><p>The staging area is the landing area for all the data sources before they are pushed to the warehouse layer. In this layer, data will be cleaned, de-duplicated, joined, split, and converted into a common format. Data quality and validation tools could cover data standardisation and validation.</p><p><a href="https://cloud.google.com/blog/products/data-analytics/open-data-lakehouse-on-google-cloud">Open data lakehouse on Google Cloud | Google Cloud Blog</a></p><p>by using Google BigQuery for example, with <a href="https://cloud.google.com/biglake?hl=en">BigLake</a> and Google Cloud Storage you can present all of these different datatypes as a single unified warehouse environment.</p><h3>Warehouse layer</h3><p>The warehouse layer contains all the enterprise data. The warehouse data is now subject-oriented, integrated, time-variant, and non-volatile. With ELT approaches, we shape and transform the data based on the subject-oriented requirements.</p><h3>Consumption layer</h3><p>The final building block of the data warehouse is the consumption layer, also known as the analytics layer. In this layer, data access is given to the end users. These end users can be data analysts, BI analysts, and customers. They access the data through reporting, analytical and querying tools.</p><h3>Proposed Kimball Data Warehouse Architecture</h3><p>Below is the proposed data warehouse architecture, which focuses on how the data flows from the old MySQL OLTP database to the new modernized dimensional data warehouse in BigQuery during the migration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqPqTw0BylN0HeXh1wVsDg.png" /></figure><p>With the insights from the data modelling and the data warehouse architecture design, we go ahead to create the<strong><em> three layers (datasets)</em></strong> in Bigquery using dbt. These (staging, warehouse, and analytics_obt or reporting) layers are identified by the “dbt prefix”.</p><h3>Proposed Data Modelling Concepts</h3><p>After a series of interviews with the business stakeholders and understanding their business requirements, we proposed the following data modelling concepts:</p><ul><li>Conceptual Data Model</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*EELid4kMRjx05RPH.png" /></figure><ul><li>Logical Data Model</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*oAfHrsrrxPX1UQKO.png" /></figure><ul><li>Physical Data Model</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*52UDpoj7GHKrIr4g.png" /></figure><h3>Applied Star Schema &amp; One Big Table Concept</h3><p>Join all of the data necessary for analytics into wide <a href="https://dataengineering.wiki/Concepts/Denormalization">denormalized</a> tables. One big table is a popular approach to serving analytics at larger scales and takes advantage of the benefits of <a href="https://dataengineering.wiki/Concepts/Column-oriented+Database">columnar databases</a>.</p><blockquote>Important Note: To maximize the performance &amp; querying from stakeholders side, and also the the user experience of the Data Products, <strong>de-normalized Fact table building should always be prioritized over building Dimension tables</strong>.</blockquote><p>In other words, it is always a better experience for analysts when they don’t need to do many JOINs at their queries if the needed columns are always in the Fact table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ls22ALcY7v8dw2Le6xQWmw.png" /><figcaption>Star Schema and One Big Table concept</figcaption></figure><h4>Dimension tables</h4><blockquote>A <strong>dimension</strong> is a structure that categorizes <a href="https://en.wikipedia.org/wiki/Fact_(data_warehouse)">facts</a> and <a href="https://en.wikipedia.org/wiki/Measure_(data_warehouse)">measures</a> in order to enable users to answer business questions. Commonly used dimensions are people, products, place and time</blockquote><h4>Fact tables</h4><blockquote>In <a href="https://en.wikipedia.org/wiki/Data_warehousing">data warehousing</a>, a <strong>fact table</strong> consists of the measurements, metrics or <a href="https://en.wikipedia.org/wiki/Fact_(data_warehouse)">facts</a> of a <a href="https://en.wikipedia.org/wiki/Business_process">business process</a>. It is located at the center of a <a href="https://en.wikipedia.org/wiki/Star_schema">star schema</a> or a <a href="https://en.wikipedia.org/wiki/Snowflake_schema">snowflake schema</a> surrounded by <a href="https://en.wikipedia.org/wiki/Dimension_table">dimension tables</a>.</blockquote><p><strong>Applied Structs Data Type in OBT</strong></p><p>Within each record, multiple attributes have their values. These attributes can either be referred to as keys or <em>Struct</em> columns.</p><blockquote><em>booking_id: 1234,</em></blockquote><blockquote><em>vehicles: “Van”,</em></blockquote><blockquote><em>extra_requirements: [</em></blockquote><blockquote><em>{“extra_requirement”: “extra helper”, “amount”: “500”},</em></blockquote><blockquote><em>{“extra_requirement”: “special helper”, “amount”: “100”}</em></blockquote><blockquote><em>],</em></blockquote><blockquote><em>…</em></blockquote><p><strong>Advantages</strong>:</p><ul><li>Enhance query performance by removing the need for joins. This can lead to significant speed improvements for analytical and reporting queries.</li><li>Simplified data model</li><li>Flexibility in data storage by using nested fields or struct data type in BigQuery</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Need to maintain and manage strictly</li><li>Complexity in data updates, not adapting to changes well.</li></ul><p>After creating one big table booking, users can create a datamart for the specific business unit,…</p><h3>Partitioned Tables</h3><p>Partitioning involves dividing data based on specific criteria. Similarly, partitioning in databases greatly improves query performance and reduces costs by limiting searches to relevant subsets of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*6Uh6mBgSHn4YNe2M.png" /></figure><h3>dbt Incremental Models</h3><p>A common incremental configuration in dbt looks like this:</p><pre>{{<br>    config(<br>        materialized=&#39;incremental&#39;<br>    )<br>}}<br><br>select *<br>from {{ ref(&#39;app_data_events&#39;) }}<br><br>{% if is_incremental() %}<br>  where event_time &gt;= (select coalesce(max(event_time),&#39;1900-01-01&#39;) from {{ this }} )<br>{% endif %}</pre><h4>A Better Solution: Using a Macro</h4><pre>{% macro get_max_day(model, column, default_date=&#39;2020-01-01&#39;) %}<br>  {% set sql_statement %}<br>    select coalesce(max({{ column }}), &#39;{{ default_date }}&#39;) from {{ model }}<br>  {% endset %}<br><br>  {% set filter_date = dbt_utils.get_single_value(sql_statement, default=default_date) %}<br>  {{ return(filter_date) }}<br>{% endmacro %}</pre><h4><strong>Incremental Model Example:</strong></h4><pre>{{<br>    config(<br>        materialized=&#39;incremental&#39;<br>    )<br>}}<br><br>{% if is_incremental() %}<br>  {% set filter_date = get_max_day(this, &#39;event_time&#39;) %}<br>{% endif %}<br><br>select *<br>from {{ ref(&#39;app_data_events&#39;) }}<br><br>{% if is_incremental() %}<br>  where event_time &gt;= &#39;{{ filter_date }}&#39;<br>{% endif %}</pre><h3>Data Warehouse Best Practices</h3><p>To build a robust and efficient data warehouse, it is essential to consider the following design principles and best practices:</p><p><strong>a. Define Clear Objectives:</strong> Establish clear goals and objectives for the data warehouse, ensuring that they align with the organization’s overall data strategy and business requirements.</p><p><strong>b. Identify Data Sources:</strong> Determine the data sources that will provide the necessary data for the data warehouse, considering factors such as data volume, variety, and velocity.</p><p><strong>c. Implement Data Integration and ETL Processes:</strong> Design and implement efficient ETL processes to ensure data consistency, accuracy, and compatibility between data sources and the data warehouse.</p><p><strong>d. Optimize Data Storage and Modeling:</strong> Select an appropriate database management system and data modelling technique for the data warehouse, considering factors such as scalability, performance, and data complexity.</p><p><strong>e. Ensure Data Security and Compliance:</strong> Implement data security measures, such as encryption, access controls, and audit logging, to protect sensitive data and comply with data protection regulations.</p><p><strong>f. Establish Data Governance and Metadata Management:</strong> Develop data governance policies and maintain comprehensive metadata to ensure that the data warehouse is managed effectively and consistently.</p><p><strong>g. Monitor and Optimize Performance:</strong> Regularly monitor the performance of the data warehouse and implement optimizations as needed to ensure that it continues to meet the organization’s requirements.</p><p><strong>h. Plan for Scalability and Future Growth:</strong> Design the data warehouse with scalability in mind, ensuring that it can grow and adapt as the organization’s data needs evolve.</p><h3>What is a Semantic layer?</h3><p>A semantic layer is a business representation of data and offers a unified and consolidated view of data across an organization. It&#39;s important to note that the semantic layer does not hold or store the actual data, it is a <strong>metadata</strong> and abstraction layer built on the source data</p><p>This abstraction over the data warehouse maps different data definitions from various data sources into a unified, consistent, and single view of data for analytics and other business purposes. Semantic layers create pre-defined views of processed data that abstract complexity and apply <strong>business-oriented definitions</strong>. Metrics like revenue or cost are defined.</p><p>Hence, a need for centralized metrics to give users a single source of truth and a semantic layer<strong>.</strong> Organizations can codify their metrics in a centralized place and have confidence that they’re getting the same number and context around that number wherever they consume data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DLaUN4ME8gYjbp1A.png" /></figure><p>Modern data stack with dbt’s semantic layer</p><p>Benefits of the dbt’s semantic layer include:</p><ul><li>centralized metrics defined once and used across the organization ensuring accuracy, clarity, and molecularity.</li><li>metrics can be used in downstream applications including machine learning models, automation tools, reverse ETL tools, and even spreadsheets.</li><li>increased ease in calculating metrics (dbt uses YAML files).</li><li>automated documentation to provide metric definition and context.</li></ul><p><strong>When NOT to use a Semantic Layer:</strong></p><p>Although the semantic layer can help data teams create functional self-serving reports and dashboards, it is only needed when the data infrastructure is relatively mature and there are lots of data users using multiple BI tools. The data warehouse used to build metrics must be relatively clean and formatted correctly into appropriate dimensions and fact tables.</p><p>If you are a data engineer in a startup, building a semantic layer may not be the best use of your time since building a data infrastructure to support a semantic layer will require significant effort.</p><p>However, the semantic layer can be a great value add for organizations using dbt that want to standardize metric definitions. If you would like to delve deeper into DBT’s semantic layer, please check out their <a href="https://www.getdbt.com/blog/build-centralize-and-deliver-consistent-metrics-with-the-dbt-semantic-layer">blog</a>. In my next blog post, I will show how you can use the dbt semantics layer in practice in dbt-Cloud.</p><h3>References</h3><ul><li><a href="https://www.udemy.com/course/analytics-engineering-bootcamp/">https://www.udemy.com/course/analytics-engineering-bootcamp/</a></li><li><a href="https://en.wikipedia.org/wiki/Ralph_Kimball">Ralph Kimball</a> — The father of data warehousing</li><li><a href="https://en.wikipedia.org/wiki/Dimensional_modeling">Dimensional modeling</a></li><li><a href="https://docs.getdbt.com/guides/best-practices/how-we-structure/4-marts">Marts: Business-defined entities | dbt Developer Hub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1c68a84f21e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Storytelling 101]]></title>
            <link>https://phoenix-analytics.medium.com/data-storytelling-101-557f29e31629?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/557f29e31629</guid>
            <category><![CDATA[data-storytelling]]></category>
            <category><![CDATA[presentations]]></category>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 09:17:30 GMT</pubDate>
            <atom:updated>2025-04-03T09:17:30.130Z</atom:updated>
            <content:encoded><![CDATA[<h3>Storytelling Framework</h3><p>This data storytelling framework is a dashboard layout for data visualization for clarity and for delivering engaging presentations to readers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*dhehM-KoZe2A-WeNLtYSew.png" /><figcaption>Layout flow</figcaption></figure><p>The image above illustrates two concepts for crafting your dashboard or report: the Pyramid Principle and the Onion Model. These concepts serve as guidance for structuring an optimal layout that facilitates easy comprehension of the information presented to the reader.</p><h3>Data Granularity</h3><p>In various contexts, “granularity” refers to the level of detail or precision in something. <strong>When discussing data, “granularity” refers to the level of detail of the data.</strong></p><ul><li><strong>Low granularity: </strong>the data is aggregated or summarized at a higher level, providing a broader overview or less detailed information.</li><li><strong>High granularity:</strong> the data is more detailed, providing more specific or finer-grained information<strong>.</strong></li></ul><p>So, low granularity implies a broader or less detailed view, while high granularity implies a more detailed or specific view.</p><h3>Workout</h3><p>The subject concerns the World Economic Indicator, determined by a nation’s GDP.</p><p><strong>Step 1: Addressing the Big Question</strong></p><p>This is a critical step in determining our analytical perspective. We’ll be focusing on <strong>how Indonesia’s GDP compares to other countries.</strong> This comparison will be the <strong>core element</strong> visualized in our analysis.</p><p><strong>Step 2: Structuring the Content Flow with the Onion Model</strong></p><p>In this context, we aim <strong>to compare Indonesia’s GDP with the top two GDPs in its regional context.</strong> To provide clarity, I<strong>ndonesia falls under Southeast Asia (SEA), a subset of the broader Asia (AS) region.</strong> With this in perspective, the Onion Model will be employed to enhance the conceptualization of the layout flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*63cL4sHkvSpcuehWkBO0zA.png" /></figure><p>The Application of the Onion Model</p><p>Think of the model like a magnifying glass. The smaller circle zooms in for a closer look at a specific part of the data. This close-up view shows more details (higher granularity) which is represented by a more concentrated colour. In contrast, the larger circle represents a broader view of the data with less detail (lower granularity), shown by a less intense colour.</p><p><strong>Step 3: Structuring Details with the Pyramid Principle</strong></p><p>The pyramid principle can be a helpful tool to expand on specific sections within your report or dashboard, providing a clear structure for additional details.</p><p>Originally, this principle helps structure your ideas and writing for clarity and conciseness. It works like a pyramid, with the key takeaway at the top, and supporting details forming the layers beneath. However, I’ve adapted the concept slightly in the context of data visualization. Here, the narrow pyramid base represents data with low detail (granularity), while the wider top signifies data with high detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*1EgkwTkBFYtSucNhHLZ0Kw.png" /></figure><p>The Application of the Pyramid Principle</p><p><strong>Step 4: Creating the Report</strong></p><p>This final report reflects the application of the established framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*UiElHTEmV_qMBMLvMlU9eA.png" /><figcaption>Indonesia’s Economic Performance Compared to Top GDP Countries</figcaption></figure><h4>Case Study 1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*toQ0AjBwBTlhIgpV413_VA.png" /></figure><p>The Percentage of TikTok Users Worldwide by Age Group as of 2022 (Image by Author)</p><p>The chart above presents TikTok user data by age across the globe. Age groups are listed horizontally, with corresponding percentages of total users on the vertical axis. While the chart shows the age breakdown of TikTok users globally, <strong>it</strong> <strong>lacks context</strong> that would make the data more insightful.</p><p>Adding these elements will help you communicate your chart’s message more clearly:</p><ul><li><strong>Title (Context):</strong> this section serves as the foundation for understanding the chart. It outlines the main context to ensure stakeholders can grasp the intended message you want to convey through the visual representation.</li><li><strong>Subtitle:</strong> this section provides additional details that help stakeholders interpret the visual element more effectively.</li><li><strong>Visual Element:</strong> this is where your chart or visual element goes. Be sure to highlight the key part that delivers your message.</li><li><strong>Source:</strong> this section is for citing your sources (if any).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*SSuIe6i5vc_R-a7sEgTtnA.png" /></figure><p>Making Chart Clearer with Context (Image by Author)</p><p>This approach allows us to establish various contexts as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*Y8w5PbtAO5wESpU4daBIeA.png" /></figure><p>The Chart Provides Context from Several Perspectives (Image by Author)</p><p>There are <strong>at least</strong> four interpretations that we can generate from a single chart. The context can vary, depending on which column(s) is highlighted.</p><ol><li>The first chart highlights the dominance of young people on TikTok, with over 60% of users being Gen Z and Millennials. This context is especially relevant when considering the young generation’s role and influence on social media platforms.</li><li>The second chart reveals a significant age difference among TikTok users. Young adults (18–24 years old) make up the largest demographic, representing nearly 35% of all users. In contrast, the 55+ age group has the smallest user base, at just over 3%.</li><li>Conversely, the third chart highlights the small portion of the older age group aged 55+. This context is relevant when considering the behaviour of older groups in social media.</li><li>The fourth chart reveals that users aged 18–24 constitute the largest demographic group on TikTok, representing 34.9% of the total user base.</li></ol><h4>Case Study 2</h4><p>The bar chart below illustrates the ten countries boasting the highest number of TikTok users in October 2023.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*O7MSxtUumqnDdtrML743qA.png" /></figure><p>Top 10 Countries with Most TikTok Users Worldwide as of October 2023 (Image by Author)</p><p>This chart provides a starting point for creating a compelling story. By looking at the data from various perspectives, we can gain deeper insights. <strong>One way is to zoom in on a particular country, like Indonesia</strong>, and use it as an example to study.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*nSrVLh19S-3lQ_CoZp9_vA.png" /></figure><p>Adding Context to the Chart: Highlighting a Specific Country (Image by Author)</p><ol><li>The bar chart presents the ten countries with the highest number of TikTok users as of October 2023, <strong>with a specific focus on Indonesia’s position within this ranking.</strong></li><li>The second chart adopts a <strong>doughnut format</strong> to isolate Indonesia’s user base. <strong>This visualization emphasizes Indonesia’s significant contribution, accounting for 8% of global TikTok users, which translates to approximately 106.52 million individuals.</strong> For comparative purposes, the remaining countries are aggregated into a single category within this representation.</li></ol><blockquote><em>Visual elements can be freely adapted to enhance information clarity. In the second option, I’ve chosen a donut chart to effectively represent the portion of a specific category compared to the whole, which is the percentage of Indonesia’s Tiktok users compared to worldwide users.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=557f29e31629" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design]]></title>
            <link>https://phoenix-analytics.medium.com/system-design-13f6636518ae?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/13f6636518ae</guid>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 09:52:27 GMT</pubDate>
            <atom:updated>2025-03-21T09:52:27.405Z</atom:updated>
            <content:encoded><![CDATA[<h3>Single Server Setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKp4lBWyF_YX-3jxn2CndA.png" /><figcaption>Single server</figcaption></figure><ol><li>Users access websites through domain names (DNS), a paid service provided by third parties that is not hosted by our servers.</li><li>Internet Protocol (IP) address is returned to the browser or mobile app</li><li>Once the IP address is obtained, Hypertext Transfer Protocol (HTTP) requests are sent directly to your web server.</li><li>The web server returns HTML pages or JSON responses for rendering.</li></ol><h3>Stateless vs Stateful Architecture</h3><p>A stateful server remembers client data (state) from one request to the next, while a stateless server does not keep any state information.</p><h3>Load Balancer</h3><p>A load balancer evenly distributes incoming traffic among web servers that are defined in a load-balanced set</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJZ8avbrpsm-fpDFJchSqg.png" /><figcaption>Load Balancer</figcaption></figure><ul><li>Users connect to the public IP of the load balancer directly. With this setup, web servers are unreachable directly by clients anymore → solved no failover issue</li><li>For better security, private IPs are used for communication between servers. A private IP is an IP address reachable only between servers in the same network; however, it is unreachable over the internet</li></ul><h3><strong>Databases</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0zyyDcOW7id6M38bEsdAQ.png" /><figcaption>Database</figcaption></figure><h3>Vertical scaling vs horizontal scaling</h3><ul><li>Vertical scaling, referred to as “scale up”, means the process of adding more power (CPU, RAM, etc.) to your servers</li><li>Vertical scaling has a hard limit. It is impossible to add unlimited CPU and memory to a single server.</li><li>Vertical scaling does not have failover and redundancy. If one server goes down, the website/app goes down with it completely</li><li>Horizontal scaling, also known as “scale-out” allows you to increase your pool of resources by adding more servers.</li><li>Sharding separates large databases into smaller, more easily managed parts called shards</li></ul><h3>Database Replication</h3><ul><li>A master database generally only supports write operations. A slave database gets copies of the data from the master database and only supports read operations</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zqtWE8QNXo31IRG5mSUmA.png" /><figcaption>Replication</figcaption></figure><h3>Cache</h3><p>A temporary storage area that stores the result of expensive responses or frequently accessed data in memory so that subsequent requests are served more quickly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3sFRlG-mdKlzkc4UOM_Okg.png" /></figure><ul><li>Consider using cache when data is read frequently but modified infrequently</li><li>Implement an expiration policy. Once cached data is expired, it is removed from the cache.</li><li>Consistency: This involves keeping the data store and the cache in sync</li><li>Mitigating failures: multiple cache servers across different data centres are recommended to avoid SPOF / overprovision of the required memory by certain percentages</li><li>Eviction Policy: Once the cache is full, any requests to add items to the cache might cause existing items to be removed</li></ul><h3>Content Delivery Network (CDN)</h3><p>A network of geographically dispersed servers is used to deliver static content. CDN servers cache static content like images, videos, CSS, JavaScript files, etc.</p><p>Intuitively, the more users are from CDN servers, the slower the website loads</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXA8kL_s71cvBEts9BRy8A.png" /></figure><ol><li>User A tries to get image.png by using an image URL. The URL’s domain is provided by the CDN provider. The following two image URLs are samples used to demonstrate what image URLs look like on Amazon and Akamai CDNs: • <a href="https://mysite.cloudfront.net/logo.jpg">https://mysite.cloudfront.net/logo.jpg</a> • <a href="https://mysite.akamai.com/image-manager/img/logo.jpg">https://mysite.akamai.com/image-manager/img/logo.jpg</a></li><li>If the CDN server does not have image.png in the cache, the CDN server requests the file from the origin, which can be a web server or online storage like Amazon S3.</li><li>The origin returns image.png to the CDN server, which includes the optional HTTP header Time-to-Live (TTL) which describes how long the image is cached.</li><li>The CDN caches the image and returns it to User A. The image remains cached in the CDN until the TTL expires.</li><li>User B sends a request to get the same image.</li><li>The image is returned from the cache as long as the TTL has not expired.</li></ol><h3>Message Queue</h3><p>A durable component, stored in memory, that supports asynchronous communication. It serves as a buffer and distributes asynchronous requests</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyIDaEASdTioz4Wn5HRC2g.png" /></figure><p>The producer and the consumer can be scaled independently. When the size of the queue becomes large, more workers are added to reduce the processing time. However, if the queue is empty most of the time, the number of workers can be reduced.</p><h3>Logging, Metrics and Automation</h3><p>Logging: Monitoring error logs is important because it helps to identify errors and problems in the system. You can monitor error logs at per server level or use tools to aggregate them to a centralized service for easy search and viewing. Metrics: Collecting different types of metrics helps us to gain business insights and understand the health status of the system. Some of the following metrics are useful: • Host level metrics: CPU, Memory, disk I/O, etc. • Aggregated level metrics: for example, the performance of the entire database tier, cache tier, etc. • Key business metrics: daily active users, retention, revenue, etc. Automation: When a system gets big and complex, we need to build or leverage automation tools to improve productivity. Continuous integration is a good practice, in which each code check-in is verified through automation, allowing teams to detect problems early. Besides, automating your build, test, deploy process, etc. could improve developer productivity significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiozCEoJal6DnjccvKHFEQ.png" /></figure><h3><strong>Hotel Booking System</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CX6yoQYfN4LXstg5AslVPw.png" /></figure><h3>Define APIs</h3><ul><li>GET /hotels: View all hotels by preselected location</li><li>GET /hotels/{hotel_id}: View hotel details</li><li>POST /reservations: Make a hotel reservation</li><li>POST /payments: Make a payment</li></ul><h3>APIs Requests and Responses</h3><ul><li>GET /hotels: can filter by price, room type, amenities, pagination, and sort. Return a list of hotels</li><li>POST /reservations: make a reservation with the guest name once payment is successful</li></ul><h3>Define Data Model</h3><p>We can build the models below using relational databases like Postgres.</p><h3>Define High-Level System</h3><p>We will build services into microservices. Each microservice calls its database.</p><ul><li>Guest Service which handles information for the logged user</li><li>Inventory Service which shows available hotels</li><li>Reservation Service which handles booking a hotel</li><li>Payment Service: we will be using 3rd party service like Stripe</li></ul><h3>System Level Optimizations:</h3><ul><li>Images can be stored in an S3 bucket which can be cached through CDN</li><li>Cached previous database results before calling the database again</li><li>Cached commonly popular hotels before going to the server</li><li>Cached last viewed hotels</li></ul><h3>UI Performance Optimizations</h3><ul><li>use React-Query to cache recent API requests from users</li><li>auto pre-fetch content before the next page or image is selected</li><li>support pagination for /GET requests</li><li>load images in different sizes by the viewport. Can fetch smaller size image of the viewport is small for responsive design</li><li>user debounce() when searching to prevent too many requests from fetching</li><li>make of useCallback() and useMemo() in React Components</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KA91zmuNMZtnz-o8b33EA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13f6636518ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark — Best Practices for Data Engineer]]></title>
            <link>https://phoenix-analytics.medium.com/spark-best-practices-for-data-engineer-bcd39c636fdf?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd39c636fdf</guid>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 06:57:10 GMT</pubDate>
            <atom:updated>2025-03-13T06:57:10.047Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spark — Best Practices for Data Engineer</h3><h3>Introduction</h3><p>Apache Spark has become a cornerstone in big data processing, and PySpark (Spark’s Python API) allows engineers to work efficiently with distributed data. However, working with large datasets at scale presents challenges, including <strong>slow transformations, inefficient joins, data skew, and poor query performance</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8_y0iGpa289xGlbR.png" /></figure><h3>Spark Overloads</h3><p>Many Data Engineers encounter these performance issues:</p><ul><li><strong>Slow Joins &amp; Aggregations</strong> → Large-scale joins causing excessive shuffling.</li><li><strong>Schema Evolution &amp; Type Issues</strong> → Schema inference leading to inconsistent column types.</li><li><strong>Data Skew &amp; Uneven Workloads</strong> → Certain keys overload specific partitions.</li><li><strong>Suboptimal Query Execution</strong> → Queries not leveraging Adaptive Query Execution (AQE) or optimizations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y0rQPaeXcF_DjxTa.png" /></figure><h3>Spark DataFrame</h3><p>PySpark supports multiple data formats, such as CSV, JSON, Parquet, Avro, and ORC. DataFrames provide an efficient abstraction for working with structured data, and they are independent of the source or target file format. A data frame can be created from any of these formats or other sources, such as databases and in-memory collections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e9Wz2g-aqR_x2vV_.png" /></figure><h3>The Risk of Schema Inference in Production</h3><p>While using inferSchema=True is convenient, it can increase load times because Spark performs an initial scan of a subset of rows to infer the schema before performing the actual data processing. Providing the schema upfront eliminates this extra step and improves performance. However, this consideration primarily applies to formats like CSV and JSON, as Parquet, ORC, and Avro already include schema information within their metadata.</p><h3>Defining Schemas Explicitly for Stability</h3><pre>from pyspark.sql.types import StructType, StructField, IntegerType, StringType<br><br># Define schema for stability and performance<br>schema = StructType([<br>    StructField(&quot;id&quot;, IntegerType(), True),<br>    StructField(&quot;name&quot;, StringType(), True),<br>    StructField(&quot;salary&quot;, IntegerType(), True)<br>])<br><br>df = spark.read.schema(schema).json(&quot;data.json&quot;)</pre><p>By explicitly defining schemas, Spark skips type inference, reducing unnecessary computations and ensuring data consistency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R5ssigULCYmKDibb.png" /></figure><h3>Optimizing Data Transformations</h3><h3>The Problem: Why Are Some PySpark Queries Slow?</h3><ul><li>Using <strong>wide transformations</strong> (groupBy(), join()) without optimization.</li><li>Running transformations without understanding <strong>lazy execution</strong>.</li><li>Not leveraging <strong>window functions</strong> for efficient aggregations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qvYZOU_UJZuS_sz_.png" /></figure><h3>Handling Performance Bottlenecks in PySpark</h3><h3>Issue 1: Data Skew in Joins</h3><p>Imagine an e-commerce dataset in which 90% of transactions come from a single region. This creates data skew, overloading certain partitions while underutilizing others.</p><h3>Why does Data Skew happen?</h3><p>Data skew occurs when certain keys are significantly more frequent than others, leading to an imbalance in how Spark partitions and processes the data. This issue is particularly problematic in <strong>joins</strong> and <strong>aggregations</strong>, where a small subset of keys may dominate processing time.</p><h3>Why Salting is Not Always the Best Solution</h3><p>A common misconception is that adding a randomized salt to a join key always alleviates skew. While salting can help distribute data more evenly, it requires <strong>careful application</strong>. Specifically, <strong>one of the datasets must contain duplicate records for all possible salt values to maintain correctness</strong>. Otherwise, the join logic will break, leading to incorrect results.</p><h3>Better Strategies for Handling Data Skew</h3><p>Instead of relying solely on salting, consider the following alternative strategies:</p><ol><li><strong>Refine Partitioning Strategy</strong> — If possible, repartition your data using repartition() or hash-partitioning techniques to distribute load more evenly.</li><li><strong>Leverage Adaptive Query Execution (AQE)</strong> — Spark’s AQE can dynamically optimize shuffle partitions at runtime to balance skewed workloads:</li></ol><pre>spark.conf.set(&quot;spark.sql.adaptive.enabled&quot;, True)</pre><p>3. <strong>Skew Join Optimization</strong> — Use <strong>Spark’s built-in skew join handling</strong> by enabling:</p><pre>spark.conf.set(&quot;spark.sql.adaptive.skewJoin.enabled&quot;, True)</pre><p>4. <strong>Broadcast Joins for Small Tables</strong> — If one table is small, use broadcasting to avoid excessive shuffling:</p><pre>from pyspark.sql.functions import <br>broadcast df_joined = df.join(broadcast(small_df), &quot;key&quot;)</pre><p>By prioritizing <strong>partitioning improvements and AQE</strong>, you can achieve better performance without introducing potential correctness issues from improper salting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KBJTyvn6YLH5p5BB.png" /></figure><h3>Issue 2: Slow Joins Due to Excessive Shuffling</h3><p>Large table joins lead to expensive shuffle operations, which slow down query performance.</p><h3>Solution:</h3><h3>Use Broadcast Joins for Small Tables</h3><pre>from pyspark.sql.functions import broadcast</pre><pre># Broadcast small_df to optimize join<br>df_joined = df.join(broadcast(small_df), &quot;key&quot;)</pre><p>Broadcasting eliminates unnecessary shuffling by distributing the smaller data frame to all nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4A-1IOhpaGmsWDQy.png" /></figure><h3>Adaptive Query Execution (AQE): Let Spark Optimize Queries for You</h3><h3>Issue 3: Static Query Execution Plans</h3><p>Without optimizations, Spark executes queries <strong>statically</strong>, often leading to suboptimal resource allocation.</p><h3>Solution:</h3><h3>Enable AQE for Dynamic Query Optimization</h3><pre>spark.conf.set(&quot;spark.sql.adaptive.enabled&quot;, True)</pre><p>AQE <strong>automatically optimizes</strong> shuffle partitions and coalesces them based on real-time execution statistics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-TdlHr9mtgfvJu2S.png" /></figure><h3>Key Takeaways:</h3><h3>What Every Data Engineer Should Know</h3><p>✅ <strong>Define schemas explicitly</strong> instead of relying on inference.<br>✅ <strong>Use AQE</strong> to dynamically optimize queries at runtime.<br>✅ <strong>Avoid expensive shuffle joins</strong> by using <strong>broadcast joins</strong> where possible. ✅ <strong>Handle data skew</strong> by using <strong>salting techniques</strong> for large datasets.<br>✅ <strong>Optimize data writes</strong> by using <strong>Parquet or Delta formats</strong>.<br>✅ <strong>Implement structured logging</strong> for debugging large-scale Spark jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p_njwvmUJGeC5PvU.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd39c636fdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics Engineer with DBT — Part 5]]></title>
            <link>https://phoenix-analytics.medium.com/analytics-engineer-with-dbt-part-5-512565d7338d?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/512565d7338d</guid>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 10:47:19 GMT</pubDate>
            <atom:updated>2025-03-10T10:47:19.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analytics Engineer with DBT — Part 5</h3><h3>Chapter 5. Building an end-to-end analytics engineering use case</h3><h3>Operational Data Modeling</h3><h4>Conceptual Model</h4><p>involves identifying the key entities, their attributes, and the associations between them. Through careful analysis and collaboration with stakeholders, capture the essence of the management system and translate it into a concise and comprehensive conceptual model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l42RII7UU2T7-mXO_jPsYA.png" /></figure><h4>Logical Model</h4><p>convert the conceptual ER exercise into a logical schema, we create a structured representation of entities, attributes, and their relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36cfIsgJADVt_SWE4EabkA.png" /></figure><h4>Physical Model</h4><p>delves into the practical aspects of data management, translate the logical model into specific storage configurations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*4S7dceaq4SHx6rnfFSvE4g.png" /></figure><h4>High-level Data Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ek3fH4iRHk934TbC19WYJw.png" /></figure><h4>Extracting and loading to staging in Google BigQuery</h4><pre>import mysql.connector as connection<br>import pandas as pd<br><br>def data_pipeline_mysql_to_bq(**kwargs):<br><br>    mysql_host = kwargs.get(&#39;mysql_host&#39;)<br>    mysql_database = kwargs.get(&#39;mysql_database&#39;)<br>    mysql_user = kwargs.get(&#39;mysql_user&#39;)<br>    mysql_password = kwargs.get(&#39;mysql_password&#39;)<br>    bq_project_id = kwargs.get(&#39;bq_project_id&#39;)<br>    dataset = kwargs.get(&#39;dataset&#39;)<br><br>    try:<br>        mydb = connection.connect(host=mysql_host\<br>                                , database = mysql_database\<br>                                , user=mysql_user\<br>                                , passwd=mysql_password\<br>                                ,use_pure=True)<br><br>        all_tables = &quot;Select table_name from information_schema.tables<br>                     where table_schema = &#39;{}&#39;&quot;.format(mysql_database)<br>        df_tables = pd.read_sql(all_tables,mydb,<br>                   parse_dates={&#39;Date&#39;: {&#39;format&#39;: &#39;%Y-%m-%d&#39;}})<br><br>        for table in df_tables.TABLE_NAME:<br>            table_name = table<br>      <br>      # Extract table data from MySQL<br>            df_table_data = extract_table_from_mysql(table_name, mydb)<br><br>            # Transform table data from MySQL<br>            df_table_data = transform_data_from_table(df_table_data)<br><br>            # Load data to bigquery<br>            load_data_into_bigquery(bq_project_id,<br>                                  dataset,table_name,df_table_data)<br><br>            # Show confirmation message<br>            print(&quot;Ingested table {}&quot;.format(table_name))<br><br>        mydb.close() #close the connection<br>    except Exception as e:<br>        mydb.close()<br>        print(str(e))<br><br><br>def extract_table_from_mysql(table_name, my_sql_connection):<br>    # Extract data from mysql table<br>    extraction_query = &#39;select * from &#39; + table_name<br>    df_table_data = pd.read_sql(extraction_query,my_sql_connection)<br>    return df_table_data<br><br>def transform_data_from_table(df_table_data):<br>    # Clean dates - convert to string<br>    object_cols = df_table_data.select_dtypes(include=[&#39;object&#39;]).columns<br>    for column in object_cols:<br>        dtype = str(type(df_table_data[column].values[0]))<br>        if dtype == &quot;&lt;class &#39;datetime.date&#39;&gt;&quot;:<br>            df_table_data[column] = df_table_data[column].map(lambda x: str(x))<br>    return df_table_data<br><br>def load_data_into_bigquery(bq_project_id, dataset,table_name,df_table_data):<br>    import pandas_gbq as pdbq<br>    full_table_name_bg = &quot;{}.{}&quot;.format(dataset,table_name)<br>    pdbq.to_gbq(df_table_data,full_table_name_bg,project_id=bq_project_id, if_exists=&#39;replace&#39;)</pre><h4>Analytical Data Modelling</h4><h4><strong>Identify the Business Processes</strong></h4><ul><li>In the pursuit of constructing an effective analytics data model, the initial phase involves identifying crucial business processes within the organization. Through discussions with key stakeholders and in-depth interviews, two primary objectives surfaced: tracking sales performance across different channels and monitoring website performance metrics</li></ul><h4><strong>Identify Facts and Dimensions in Dimensional Data Model</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tElFUOdzMAyzZNuOzp0u1Q.png" /></figure><h4><strong>Identify the Attributes of Dimensions</strong></h4><ul><li>For the “channels” dimension, attributes like channel surrogate key sk_channel, channel natural key nk_channel_id, and channel name dsc_channel_name were identified</li><li>in the “products” dimension, key attributes such as product surrogate key sk_product, product natural key nk_product_sku, product name dsc_product_name, and product unit price mtr_unit_price were recognized</li><li>For the “customers” dimension, attributes like customer surrogate key sk_customer, customer natural key nk_customer_id, and various customer details such as name (dsc_name), birthday date dt_date_birth, email address dsc_email_address, phone number dsc_phone_number, and country dsc_country were identified.</li></ul><blockquote>Surrogate keys are artificial identifiers assigned to records within a database table. They provide uniqueness, stability, and improved performance in data operations</blockquote><h4><strong>Define the Granularity for Business Facts</strong></h4><ul><li>The chosen granularity, captured at the transaction level for sales data fct_purchase_history and at the visit level for website performance analysis fct_visit_history, balances detailed analysis with data manageability and performance.</li><li>Delve into individual customer purchases and sales patterns, examine transaction details, understand customer behaviour, and conduct product-level analysis with transaction-level granularity</li><li>less granular aggregations like daily, weekly, or monthly aggregates can also be determined. Aggregating data provides a more concise representation, reducing data volume and simplifying analysis. This approach facilitates the identification of broader trends, seasonal patterns, or overall performance across different dimensions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=512565d7338d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics Engineer with DBT— Part 4]]></title>
            <link>https://phoenix-analytics.medium.com/analytics-engineer-with-dbt-part-4-39f0f89d6485?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f0f89d6485</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 10:39:23 GMT</pubDate>
            <atom:updated>2025-03-10T10:39:23.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chapter 4. Data Transformation with DBT</h3><h4>DBT Design Philosophy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOl2UQ4AlZ19AmZb781qHA.png" /></figure><h4><em>Code-Centric Approach</em></h4><p>At the core of DBT’s design philosophy is a code-centric approach to data modelling and transformation. Instead of relying on GUI-based interfaces or manual SQL scripts, but encourages users to define data transformations using code. This shift to code-driven development promotes collaboration, version control, and automation.</p><h4><em>Modularity for Reusability</em></h4><p>DBT promotes modularity, allowing data practitioners to create reusable code components. Models, macros, and tests can be organized into packages, facilitating code maintenance and scalability. This modular approach aligns with best practices and enhances code reusability.</p><h4><em>Transformations as SQL SELECT Statements</em></h4><p>Dbt models are defined as SQL SELECT statements, making them accessible to analysts and engineers with SQL skills. This design choice simplifies development and ensures data modelling follows SQL best practices closely.</p><h4><em>Declarative Language</em></h4><p>DBT uses a declarative language for defining data transformations. Analysts specify the desired outcome, and DBT handles the underlying implementation. This abstraction reduces the complexity of writing complex SQL code and enhances readability.</p><h4><em>Incremental Builds</em></h4><p>Efficiency is a key focus of DBT’s design. It supports incremental builds, allowing data engineers to update only the affected pieces of the data pipeline rather than reprocessing the entire dataset. This accelerates development and reduces processing time.</p><h4><em>Documentation as Code</em></h4><p>dbt advocates for documenting data models and transformations as code. Descriptions, explanations, and metadata are stored alongside the project code, making it easier for team members to understand and collaborate effectively.</p><h4><em>Data Quality, Testing and Validation</em></h4><p>DBT places a significant emphasis on data testing. It provides a testing framework that enables analysts to define data quality checks and validation rules. This includes data reliability and quality throughout the pipeline, ensuring that data meets predefined criteria and adheres to business rules.</p><h4><em>Version Control Integration</em></h4><p>Seamless integration with version control systems like Git is a fundamental aspect of dbt. This feature enables collaborative development, change tracking, and the ability to roll back changes, ensuring data pipelines remain under version control.</p><h4><em>Native Integration with Data Platforms</em></h4><p>DBT is designed to work seamlessly with popular data platforms such as Snowflake, BigQuery, and Redshift. It leverages the native capabilities of these platforms for scalability and performance.</p><h4><em>Open Source and Extensible</em></h4><p>DBT is an open-source tool with a thriving community. Users can extend its functionality by creating custom macros and packages. This extensibility allows organizations to tailor DBT to their specific data needs.</p><h4><strong><em>Separation of Transform and Load</em></strong></h4><p>DBT separates the transformation and loading steps in the data pipeline. Data is transformed within dbt and then loaded into the data platform.</p><h3>DBT Semantic Layer</h3><p>Two essential components: Semantic Models and Metrics.</p><ul><li>Semantic Models are the foundational building blocks, comprising three key elements: entities, dimensions, and measures for creating a metric. These components empower MetricFlow, the framework powering our Semantic Layer, to construct queries for defining metrics.</li><li>Metrics, on the other hand, are the tools we employ to measure and analyze our data. They operate atop the semantic models, enabling the creation of sophisticated and elaborate definitions built upon reusable components.</li><li>Entities: represent independent and identifiable objects within a specific context, usually corresponding to tables in databases. In semantic models, entities are represented using ID columns that serve as join keys, helping the semantic engine understand relationships between tables and datasets.</li><li>Dimensions: acting as categorical attributes that allow data breakdown during analysis. They describe the characteristics associated with other elements in the model, enabling users to explore and analyze data from various perspectives.</li><li>Measures: representing the metrics under examination. These measures are often subject to aggregation, and BI tools play a crucial role in aggregating them across different dimensions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f0f89d6485" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics Engineer with DBT — Part 3]]></title>
            <link>https://phoenix-analytics.medium.com/analytics-engineer-with-dbt-part-3-3db0324e7434?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3db0324e7434</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 10:35:34 GMT</pubDate>
            <atom:updated>2025-03-10T10:35:34.541Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analytics Engineer with DBT — Part 3</h3><h3>Chapter 3. SQL for Analytics</h3><h3>The resiliency of SQL</h3><p>The enduring popularity of SQL in data engineering pipelines is attributed to several factors. First and foremost is the readability of the code, with SQL’s versatile syntax allowing both imperative and declarative usage. This flexibility enables a broad range of users to understand and interpret the code, promoting effective collaboration in cross-functional teams.</p><p>Despite its longevity, SQL’s engines have evolved significantly. Traditional SQL engines have improved and distributed tools like Spark and Presto have enabled SQL to process massive datasets. DuckDB, a recent addition, empowers SQL with extremely fast parallelized analytics queries on a single machine, offering new possibilities for data engineering tasks.</p><p>The versatility of SQL is highlighted by its adaptability to various database architectures and purposes, acting as a unifying language bridging the gap between OLAP and OLTP systems. SQL’s strong data typing is particularly beneficial in data engineering, providing consistency throughout the data pipeline and mitigating challenges associated with managing data types across different languages and engines.</p><p>SQL’s compatibility with software engineering best practices is a significant advantage. Tools like DuckDB facilitate unit tests and rapid iteration of SQL code, ensuring it conforms to established technical principles. Common Table Expressions (CTEs) and features like Lambda functions enhance code modularity and testability, contributing to a more robust development process.</p><p>Additional advancements, such as full-text search, geodata functions, user-defined functions, Lambda functions, and window functions, further expand SQL’s capabilities, making it resilient and encouraging continued investment in learning and applying it in day-to-day analytics activities.</p><h3>Databases Fundamentals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ls_r8gF4V2UXei9dznoEdQ.png" /></figure><ul><li><em>Data:</em> Raw facts and figures that lack context and meaning. Data can be considered as the building blocks of information</li><li><em>Information: Organized and structured representation of data that provides context and answers specific questions</em></li><li><em>Knowledge: insights gained to make informed decisions and take appropriate actions</em></li><li><em>Wisdom: apply their knowledge and make sound judgments, leading to positive effects and transformative insights.</em></li></ul><h3>Types of databases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DCKSZgcBRIkOwZ0tlugpcg.png" /></figure><ul><li>Relational databases provide strong data integrity, transactional reliability, and support for ACID properties, ensuring that database transactions are reliable, maintain data integrity, and can recover from failures.</li><li>NoSQL manages large volumes of unstructured and semi-structured data with scalability and flexibility to prioritize high performance, horizontal scalability, and schema flexibility.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3db0324e7434" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics Engineer with DBT — Part 2]]></title>
            <link>https://phoenix-analytics.medium.com/analytics-engineer-with-dbt-part-2-09eb0d11b467?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/09eb0d11b467</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 10:33:17 GMT</pubDate>
            <atom:updated>2025-03-10T10:33:17.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analytics Engineer with DBT — Part 2</h3><h3>Chapter 2. Data Modelling for Analytics</h3><p>Data modelling is about defining the structure, relationships, and attributes of data entities within a system. An essential aspect of it is the normalization of the data. Data normalization is a technique for eliminating data redundancy and improving data integrity. It involves breaking down data into logical units and organizing them into separate tables, which reduces data duplication and improves overall database efficiency. Normalization ensures that data is stored in a structured and consistent manner, which is critical for accurate analysis and reliable results.</p><h3>The conceptual phase of modelling</h3><ul><li>Identify the purpose and goals of the database and clarify the specific problems or requirements it is planned to address</li><li>Gathering requirements by interviewing stakeholders and subject matter experts to comprehensively understand the required data elements, relationships, and constraints</li><li>Entity analysis and definition follow</li></ul><h3>The logical phase of modelling</h3><ul><li>Normalizing the data to eliminate redundancies, improve data integrity, and optimize query performance</li><li>Restructuring of the Entity-Relationship scheme, which focuses on optimizing the schema based on specific criteria</li><li>Translating the optimized ERD into a specific logical model.</li></ul><h3>The physical phase of modelling</h3><ul><li>Defining storage structures, indexing strategies, and data types to ensure efficient data storage and retrieval</li></ul><h3>Dimensional Data Modelling</h3><p>Focuses on modelling data to support analytics and reporting requirements</p><ul><li>The creation of dimensional models that consist of fact tables representing measurable data and dimension tables providing descriptive context</li><li>Simplifies complex queries and enables efficient data analysis, such as star schemas and snowflake schemas</li><li>Inmon proposes the creation of a centralized data warehouse that encompasses the entire enterprise</li><li>Kimball suggests creating multiple smaller data marts focused on specific departments, enabling department-level analysis and reporting</li><li><strong>Modelling with Star Schema</strong></li><li><strong>Modelling with Snowflake</strong></li><li><strong>Modelling with Data Vault</strong></li></ul><h3>Modular data modeling</h3><p>The core principles of modular data modeling</p><ul><li><strong>Decomposition:</strong> Breaking down the data model into smaller, more manageable components</li><li><strong>Abstraction:</strong> Hiding the implementation details of the data model behind interfaces;</li><li><strong>Reusability:</strong> Creating components that can be reused across multiple parts of the system.</li></ul><p>Using the normalization technique, the data is separated into different tables based on their characteristics and relationships, leading to a modular data model.</p><p>dbt {{ ref() }} for model referencing, {{ source() raw data from the database to employ modular</p><h3>Staging data models/Base data models</h3><p>Each staging model corresponds to a source table with a 1:1 relationship to the original data source.</p><p>→ Allows intermediate or mart models that reference the staging layer to access up-to-date data while saving space and cost</p><h3>Intermediate data models</h3><p>Combining the atomic building blocks from the staging layer to create more complex and meaningful models</p><ul><li>Advisable to store intermediate models as ephemeral models</li><li>Cases where materializing them as views is more suitable</li></ul><h3>Mart models</h3><p>Integrating and presenting business-defined entities to end users via dashboards or applications.</p><ul><li>Typically materialized as tables.</li><li>In cases where the creation time or cost of materializing a table is an issue, configuration as an incremental model can be considered, allowing for efficient updates as new data is included.</li></ul><h3>Testing your data models</h3><p>Two main types of tests</p><ul><li>Singular tests are specific and targeted tests written as SQL statements and stored in separate SQL files.</li><li>Generic tests, on the other hand, are more versatile and can be applied to multiple models or data sources</li></ul><h3>Data model optimization and debugging</h3><ul><li>Analyze and optimize the queries themselves carefully</li><li>Deconstructing complex queries by breaking them into smaller components, such as Common Table Expressions (CTEs)</li><li>Selectively using an appropriate materialization technique</li></ul><h3><strong>Medallion Architecture Pattern</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7UOcH731HxxpkvJ4EE5eg.png" /><figcaption>Medallion Framework</figcaption></figure><ul><li><strong><em>Bronze layer</em></strong><em>:</em> Serves as the initial destination for data from external source systems. The tables in this layer mirror the structures of the source system tables as they are, including any extra metadata columns to capture information like load date/time and process ID. This layer prioritizes efficient Change Data Capture, maintaining a historical archive of the source data, ensuring data lineage, facilitating audits, and enabling reprocessing without rereading data from the source system.</li><li><strong><em>Silver layer:</em></strong> this layer plays an essential function in consolidating and refining data sourced from the Bronze one. The Silver layer creates a “Holistic view” that encompasses key business entities, concepts, and transactions through processes such as matching, merging, conforming, and cleansing. This includes master customers, stores, non-duplicated transactions, and cross-reference tables. The Silver layer serves as a comprehensive source for self-service analytics, empowering users with ad-hoc reporting, advanced analytics, and machine learning capabilities. It is often observed that this silver layer can take the form of a 3NF data model, a star schema, a data vault, or even a snowflake. This is a valuable resource for anyone who leverages data to undertake projects and analyses aimed at solving business problems — Just like a traditional data warehouse would.</li><li><strong><em>Gold Layer:</em></strong> This layer delivers valuable insights that address business questions. It aggregates data from the Silver layer and serves it to BI ad-hoc reporting tools and Machine Learning applications. This layer ensures reliability, improved performance, and ACID transactions for data lakes while also unifying streaming and batch transactions on top of cloud data stores.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09eb0d11b467" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics Engineer with DBT — Part 1]]></title>
            <link>https://phoenix-analytics.medium.com/analytics-engineer-with-dbt-part-1-71ecec5afbc5?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/71ecec5afbc5</guid>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 10:28:58 GMT</pubDate>
            <atom:updated>2025-03-10T10:28:58.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analytics Engineer with DBT — Part 1</h3><h3>Chapter 1. Analytics Engineering</h3><p><strong>Databases and their impact on Analytics Engineering</strong></p><p>Data becomes more diverse and prevalent, and effective management and analysis become crucial, necessitating strong methods to ensure accuracy.</p><p>Data volumes and analytics complexity grow, and connecting business intelligence tools directly to operational databases may lead to performance issues. This is where analytics engineering becomes crucial, optimizing data workflows, designing ETL processes, and bridging the gap between raw data and actionable insights. Analytics engineers ensure that organizations can efficiently analyze large, complex datasets, overcoming the limitations of direct connections to operational databases.</p><p><strong>Cloud Computing and its impact on Analytics Engineering</strong></p><p>Cloud computing is a core component of modern data platforms and is contributing to the continuous growth of cloud-based analytics and artificial intelligence platforms, disrupting the industry.</p><p><strong>The data analytics lifecycle</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5n6hcLuYgSrordgrk-AlpA.png" /><figcaption>Data Lifecycle</figcaption></figure><p>The data analytics cycle is a systematic process that transforms raw data into valuable and easily consumable data products, such as well-managed datasets, dashboards, reports, APIs, or web applications</p><ul><li><em>Problem Definition</em></li></ul><p>The first phase of the analytics cycle is about understanding the problem that needs to be solved. This includes identifying the business objectives, the available data, and the resources required to solve the problem.</p><ul><li><strong><em>Data Modeling</em></strong></li></ul><p>Modelling your data according to the modelling technique that best meets your needs. (diamond strategy, a star schema, a data vault, or even a fully denormalized technique)</p><ul><li><strong><em>Data Ingestion and Transformation</em></strong></li></ul><p>The next phase is to ingest and prepare the data from the source systems to match the models created.</p><ul><li><strong><em>Data storage and structuring</em></strong></li></ul><p>Once the data pipelines are designed and potentially implemented</p><ul><li><strong><em>Data Visualization and Analysis</em></strong></li></ul><p>Explore it, visualize it, or create dashboards that directly support decision-making or enable business process monitoring.</p><ul><li><strong><em>Data Quality Monitoring, Testing, and Documentation</em></strong></li></ul><p>It involves implementing all quality controls, and proper testing along the pipelines as the data continues to flow.</p><p><strong>Enabling analytics in a data mesh</strong></p><p>A data mesh is a modern approach to a data strategy that shifts ownership to business domain teams rather than relying solely on a central data team. It decomposes monolithic data architecture into independent, autonomous data services, offering finer scaling, more autonomy, and improved data management</p><p>𝐂𝐨𝐦𝐦𝐨𝐧 𝐀𝐧𝐚𝐥𝐲𝐭𝐢𝐜𝐚𝐥 𝐏𝐚𝐭𝐭𝐞𝐫𝐧𝐬:</p><p>𝐀𝐠𝐠𝐫𝐞𝐠𝐚𝐭𝐢𝐨𝐧-𝐁𝐚𝐬𝐞𝐝:</p><ul><li>Perform group-by operations to calculate counts, sums, and averages across dimensions like country, age, or gender.</li><li>Use for trend identification, root cause analysis, and storytelling (e.g., Why did sales drop in a specific region?).</li></ul><p>𝐂𝐮𝐦𝐮𝐥𝐚𝐭𝐢𝐨𝐧-𝐁𝐚𝐬𝐞𝐝:</p><ul><li>Analyze state transitions, such as retention or churn, to understand behavior shifts over time.</li><li>Recognize the importance of “no data” as a signal of inactivity (e.g., a user who didn’t engage yesterday).</li></ul><p>𝐖𝐢𝐧𝐝𝐨𝐰-𝐁𝐚𝐬𝐞𝐝:</p><ul><li>Focus on rolling time metrics to capture changes dynamically.</li></ul><p>Examples:</p><p>Day-over-Day (DoD): Compare daily performance.</p><p>Week-over-Week (WoW): Measure weekly trends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71ecec5afbc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[dbt— Foundations for transformation]]></title>
            <link>https://phoenix-analytics.medium.com/dbt-foundations-for-transformation-0d66ddc9e8bc?source=rss-2785565b1dc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d66ddc9e8bc</guid>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Thành Phương]]></dc:creator>
            <pubDate>Wed, 31 Jul 2024 08:24:54 GMT</pubDate>
            <atom:updated>2024-07-31T08:24:54.315Z</atom:updated>
            <content:encoded><![CDATA[<p>At my current company, data is a crucial component of our decision-making process. Many teams interact with our data platform in one way or another throughout their day, via various types of data products and for a wide range of use cases. For this reason, our data platform needs to be scalable and versatile to serve different usage patterns.</p><p>two central ones maintain the core data platform:</p><ul><li><strong>Engineering</strong>: owns the data lake, which contains all of our product data.</li><li><strong>ED&amp;A</strong>: owns the data warehouse, which contains a subset of product data and all of our SaaS applications’ data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*y9mbljbnd0IYmC3Y" /></figure><h3>Part I: Data transformation</h3><p>The data engineering team would ingest the different source datasets into the warehouse and maintain the business-critical pipelines, while other teams would build their own data pipelines to support various use cases.</p><p>To achieve this pattern, we had to make two decisions that defined a significant portion of our data platform:</p><ul><li><strong>Heavily customizing our Airflow instance</strong>: We’re currently using a heavily customised Airflow instance that adds a layer of abstraction on top of Airflow. This additional layer allowed us to hide most of the complexity of the different operations triggered and managed via Airflow DAGs, but it also meant maintaining more than 100 custom Airflow operators.</li><li><strong>Building data pipeline abstractions</strong>: The ED&amp;A platform team built several frameworks throughout the past few years to streamline turning SQL queries into data pipelines or Airflow DAGs. With these abstractions, users only need to provide a YAML file containing a SQL query and certain config parameters to generate an end-to-end data pipeline.</li></ul><h3>dbt — one standard to rule them all</h3><p>When we started exploring the data transformation space to find a tool that meets the above requirements, picking DBT was a straightforward decision for quite a few reasons:</p><ul><li><strong>We know (and like) SQL</strong>: As mentioned above, most of our existing data transformation codebase was written in SQL (with Airflow-related components written in Python). dbt takes things further by making SQL the cornerstone of the framework.</li><li><strong>Built-in data quality tests</strong>: We were big fans of <a href="https://docs.getdbt.com/docs/build/tests">dbt tests</a> since they simplify our data quality testing process and minimize the effort to enforce data quality standards for all foundational data assets.</li><li><strong>Built-in capabilities to apply Don’t-Repeat-Yourself (DRY)</strong>: One of the hard lessons we learned with our legacy pattern was the importance of doing things once instead of hard-coding the same bits of business logic and transformations in different queries. dbt comes with the concept of <a href="https://docs.getdbt.com/docs/build/jinja-macros#macros">macros</a>, which allows us to apply the DRY principle across all of our data assets.</li><li><strong>Rich ecosystem</strong>: the ever-growing list of high-quality <a href="https://hub.getdbt.com/">dbt packages</a> meant that we’d be able to build upon prior community work instead of reinventing the wheel ourselves.</li></ul><p>The diagram below details the different steps of our current data transformation development and execution process, with the actual implementation of the different principles discussed above (like the separation between orchestration and transformation, developer-specific sandboxes, and automated CI checks).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Qqs4hrRvqs9jyvqG" /></figure><h3>Benefits of migrated data pipelines over legacy</h3><p><strong>Data Lineage: </strong>dbt provides data lineage, which makes it easier to perform impact analysis for any new/existing change. It also made it easier to share knowledge and hand over when compared with complex processes to build legacy data pipelines. Adding new features to our legacy data pipelines took a lot of work due to high levels of complexity. Having data lineage made it easier to understand and implement changes at a rapid pace</p><p><strong>Data Quality: </strong>Our refactoring process made sure that we are not only simply moving our pipelines as-is but also improving our data quality. We fixed existing logic wherever required, and we used dbt tests to make sure that the grains were correct. This also helped us earn the trust of our end users</p><p><strong>Performance improvements and cost reduction: </strong>We improved performance with dbt by scanning fewer data, accessing only required partitions, and parallelizing model execution where possible. This also resulted in solutions being cost-efficient</p><p><strong>Reliability and Scalability: </strong>Since the migration, the number of incidents has been reduced dramatically compared to legacy days, and end users are getting the latest data with minimum delays. In terms of new pipelines or changes in existing pipelines, dbt docs can be used to perform impact analysis. This allows us to implement additional features quickly in existing data pipelines at scale</p><p><strong>Best practices and standards:</strong> New pipelines follow best practices and dbt standards along with SQLFluff lint rules, meaning all our code base has the same format. This makes it easier for existing and new users to come on board and start working with it</p><h3><strong>Part II: Orchestrating dbt with Airflow</strong></h3><ol><li><strong>dbt Project Scheduling</strong>: We aim to schedule our dbt projects in a cron job fashion, specifying specific time intervals</li><li><strong>Task Granularity</strong>: Each dbt entity (including models, tests, seeds, and snapshots) should be treated independently, allowing it to be triggered individually if necessary</li><li><strong>Maintain dbt Dependencies</strong>: Additionally, we must preserve the dependencies between dbt entities. For instance, if we have model A, which includes tests, acting as an upstream dependency for another model B, the execution sequence should be maintained</li></ol><pre>[dbt run A] -&gt; [dbt test A] -&gt; [dbt run B]</pre><p>4. <strong>Triggering Other Workflows</strong>: Certain workflows should be initiated upon the successful completion of specific dbt entities, without the necessity of waiting for the entire dbt project to finish. Moreover, there may be instances where certain workflows need to be triggered in between the execution of two dbt entities</p><pre>[dbt run A] -&gt; [execute a non-dbt related workflow] -&gt; [dbt run B]</pre><p>5. <strong>Alerting</strong>: When something goes wrong, we need to get notified on Slack</p><p>6. <strong>Running Containerised dbt Projects</strong>: Each of our dbt projects should possess its own Docker image, allowing for the flexibility to run on different dbt versions when necessary</p><p>7. <strong>Triggering Subset of Models</strong>: dbt entities can be filtered based on dbt tags, enabling the execution of specific groups of models as needed.</p><p>8. <strong>Creating Multiple Schedules</strong>: We might require running the same projects on different schedules, which is closely linked to the need for triggering a subset of models. For example, we may tag models as hourly, daily, and weekly to execute them accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*pcUFhWSPqYuSGBxw.png" /></figure><pre>import functools<br>from datetime import datetime <br>from datetime import timedelta<br>from operators.dbt_operators import get_dbt_operator<br>from utils.logger import init_logger<br>from utils.configs import (<br>    DBTProfile<br>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from dbt_airflow.core.config import DbtAirflowConfig<br>from dbt_airflow.core.config import DbtProfileConfig<br>from dbt_airflow.core.config import DbtProjectConfig<br>from dbt_airflow.core.task_group import DbtTaskGroup<br>from dbt_airflow.operators.execution import ExecutionOperator<br><br>from airflow.operators.dagrun_operator import (<br>    TriggerDagRunOperator<br><br>dag_configs = [<br>    # PostgreSQL DWH<br>    {<br>        &quot;dag_id&quot;: &quot;data_warehouse_fact_bookings&quot;,<br>        &quot;schedule_interval&quot;: &#39;*/2 * * * *&#39;,<br>        &quot;model_path&quot;: &quot;data_warehouse.fact_bookings&quot;,<br>        &quot;tags&quot;: [&quot;global&quot;, &quot;data_warehouse&quot;]<br>    },<br>]<br><br>for dag_config in dag_configs:<br><br>    dag_id = dag_config[&quot;dag_id&quot;]<br>    logger = init_logger(dag_id)<br><br>    with DAG(<br>        dag_id,<br>        default_args={<br>                &quot;owner&quot;: &quot;phuong.do@deliveree.com&quot;,<br>                &quot;depends_on_past&quot;: False,<br>                &quot;email_on_failure&quot;: False,<br>                &quot;email_on_retry&quot;: False,<br>                &quot;retries&quot;: dag_config.get(&quot;retries&quot;, 2),<br>                &quot;retry_delay&quot;: timedelta(minutes=1),<br>        },<br>        start_date=datetime(2021, 1, 1),<br>        catchup=False,<br>        tags=dag_config[&quot;tags&quot;],<br>        default_args={<br>            &#39;owner&#39;: &#39;airflow&#39;,<br>            &#39;retries&#39;: 1,<br>            &#39;retry_delay&#39;: timedelta(minutes=2),<br>        },<br>        &#39;on_failure_callback&#39;: functools.partial(<br>            our_callback_function_to_send_slack_alerts<br>        ),<br>    ) as dag:<br>    operator = get_dbt_operator(<br>            dag=dag,<br>            logger=logger,<br>            **dag_config<br>        )<br>    if &quot;trigger_dag&quot; in dag_config:<br>            trigger = TriggerDagRunOperator(<br>                task_id=f&quot;trigger_{dag_config[&#39;trigger_dag&#39;]}&quot;,<br>                trigger_dag_id=dag_config[&#39;trigger_dag&#39;],<br>                conf={},<br>            )<br>            operator.set_downstream(trigger) # noqa<br>        else:<br>            operator<br>   </pre><p>Whenever a new CI/CD pipeline is triggered, the Docker Image containing the dbt project is now built and pushed to the <a href="https://cloud.google.com/artifact-registry">Artifact Registry</a> on Google Cloud. However, since dbt-airflow still relies on the manifest.json file to render the DAG, only the manifest file needs to be copied to the Cloud Composer <a href="https://cloud.google.com/storage">GCS bucket</a> instead of the entire dbt project.</p><h3>Part III: Data Testing with Elementary</h3><p>Elementary integrates robust data quality checks and validations directly into the DBT workflow, allowing users to identify anomalies, inconsistencies, and errors in real-time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*fEV40zEoNRpnZo-Z.png" /></figure><h4>Setup</h4><p>Run the dbt deps command to install it.</p><pre>packages:<br>  - package: elementary-data/elementary<br>    version: 0.15.1</pre><p>Add the following snippet to Add to our dbt_project.yml.</p><pre>models:<br>  elementary:<br>    +schema: &quot;elementary&quot;</pre><p>Run the dbt run --select elementary command to create elementary tables and views that ingest dbt’s run results and dbt artefacts in the elementary schema.</p><p><strong>How it works</strong></p><p>Elementary Data uses historical data volumes to establish baseline metrics and monitor current data loads. An alert is triggered if the volume deviates significantly from the expected range.</p><pre>version: 2<br>models:<br>  - name: stg_address<br>    description: This model represents the stage address table for the dim address.<br><br>    data_tests:<br>      - elementary.freshness_anomalies:<br>          timestamp_column: &quot;updated_at&quot;<br>          # optional - use tags to run elementary data_tests on a dedicated run<br>          tags: [&quot;elementary&quot;]<br>          config:<br>            # optional - change severity<br>            severity: warn<br>      - elementary.schema_changes_from_baseline:<br>          tags: [&quot;elementary&quot;]<br>      - elementary.schema_changes:<br>          tags: [&quot;elementary&quot;]<br>          config:<br>            severity: warn</pre><h3>Part IV: Multiple Databases with dbt-trino</h3><p>Trino(formerly known as PrestoSQL) is fast distributed SQL query engine for big data analytics that combines and analyzes data from various sources</p><p>trino connects to multiple data sources through a single connection and processes SQL queries at scale and speed.</p><p><a href="https://github.com/starburstdata/dbt-trino"><strong>dbt-trino</strong></a></p><blockquote><em>dbt-trino adapter uses </em><a href="https://trino.io/"><em>Trino</em></a><em> as a underlying query engine to perform query federation across disperse data sources. Trino connects to multiple and diverse data sources (</em><a href="https://trino.io/docs/current/connector.html"><em>available connectors</em></a><em>) via one dbt connection and process SQL queries at scale. Transformations defined in dbt are passed to Trino which handles these SQL transformation queries and translates them to queries specific to the systems it connects to create tables or views and manipulate data.</em></blockquote><h3>Installing trino with dbt</h3><p>1-Run Trino in a Docker Container :</p><pre>docker run --name trino -d -p 8080:8080 trinodb/trino</pre><p>2-Access the Trino CLI :</p><pre>docker exec -it trino trino</pre><p>3-Create Configuration Files: Develop postgres.properties and mysql.properties for PostgreSQL and MySQL connections.</p><p>Contents of postgres.properties:</p><pre>connector.name=postgresql<br>connection-url=jdbc:postgresql://example.net:5432/database<br>connection-user=root<br>connection-password=secret<br>allow-drop-table=true</pre><p>And for MySQL mysql.properties :</p><pre>connector.name=mysql<br>connection-url=jdbc:mysql://example.net:3306/database<br>connection-user=root<br>connection-password=secret</pre><p>4- Moving the Configuration File:</p><ul><li>Access the Container: First, access the Trino container’s shell:</li></ul><pre>docker exec -it trino /bin/bash</pre><ul><li>Copy the File: Use the docker cp command to move the postgres.properties file into the Trino container’s etc/trino/catalog directory:</li></ul><pre>docker cp &lt;path_to_file&gt;/postgres.properties   trino:/etc/trino/catalog/<br>  docker cp &lt;path_to_file&gt;/mysql.properties   trino:/etc/trino/catalog/</pre><p>After finishing our steps start trino container:</p><pre>docker restart trino</pre><h3>Let’s test our connections in trino :</h3><pre>docker exec -it trino trino show catalogs;</pre><p>you should see the names of our connections postgres and mysql</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d66ddc9e8bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>