<?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 is2ac on Medium]]></title>
        <description><![CDATA[Stories by is2ac on Medium]]></description>
        <link>https://medium.com/@nisaacemmanuel?source=rss-5fdee2b4e407------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*N7VWlNP9Lv7NXGVs</url>
            <title>Stories by is2ac on Medium</title>
            <link>https://medium.com/@nisaacemmanuel?source=rss-5fdee2b4e407------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:44:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nisaacemmanuel/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[End to End Bank Datawarehousing Datapipeline using MS FABRIC.]]></title>
            <link>https://medium.com/@nisaacemmanuel/end-to-end-bank-datawarehousing-datapipeline-using-ms-fabric-1d6342dde044?source=rss-5fdee2b4e407------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6342dde044</guid>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[data-warehousing]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[msfabric]]></category>
            <category><![CDATA[dataengineeringconsulting]]></category>
            <dc:creator><![CDATA[is2ac]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 18:54:15 GMT</pubDate>
            <atom:updated>2025-04-25T13:24:40.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>End to End Fake Bank Data Warehousing Modeling using MICROSOFT FABRIC (1st Part).</h3><p>Building a data warehouse is one of those pivotal challenges that nearly every Data Engineer — whether junior or seasoned — will face at some point in their career. This is especially true when working with organizations that are in the midst of adopting data-driven processes and transforming their operational culture. In such a transformation, the data warehouse plays a foundational role. It breaks down data silos, centralizes information into a single source of truth, and enables data consumers across departments to speak the same language. This shared understanding of business data not only enhances collaboration but also supports clearer, more strategic decision-making at every level of the company. In this project, we’ll step into the shoes of a Data Engineer working in the finance industry more precisely, within a banking environment. The mission: to architect and implement a modern data warehouse using only <strong>Microsoft Fabric Tools</strong>. It’s a challenge that goes beyond just technical execution it’s about building a reliable data backbone that can scale with the organization’s ambitions.</p><p>With the business team having already outlined its expectations for this data source, we can now introduce the end-to-end architecture we’ve designed — fully powered by Microsoft Fabric.</p><h4>Prerequistes :</h4><ul><li>Just have a MS FABRIC ACCOUNT.</li></ul><p>NB : For have MS FABRIC ACCOUNT, you just need to have a professional email account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-tTYY_9SRosJCTGvAqV6A.png" /></figure><p>We opted for a modern approach known as the <strong>medallion architecture</strong>, which unfolds across three main layers:</p><ul><li><strong>BRONZE</strong>: This is the raw data ingestion layer. At this stage, data is collected as-is from the available sources, without any transformation or cleaning. In our project context, this includes data from the <strong>Customer Relationship Management (CRM)</strong> system, partitioned by country to reflect the bank’s subsidiaries, as well as transactional data from the <strong>Core Banking</strong> system.</li><li><strong>SILVER</strong>: This is where data starts to take shape. It’s cleaned, standardized, and transformed into a structured format, ready for analytical use. The goal here is to prepare a consistent, business-friendly dataset that serves as a solid foundation for analysis.</li><li><strong>GOLD</strong>: The final layer is all about usability and performance. Data is modeled and optimized to support high-performance analytics and reporting. This layer is tailored to meet specific business needs, providing curated datasets to analysts, decision-makers, and BI tools.</li></ul><p>Let’s now take a clear look at the project’s end-to-end data architecture by walking through each step of the data migration process — from initial storage to the applied transformations — while highlighting the specific implementations at each stage, presented as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*hP1CTO0SzRpLG0_3zaqMSQ.png" /></figure><p>As we can observe, <strong>Delta tables</strong> are adopted as the primary data source format right from the initial stages of building our data warehouse. Serving as the <strong>Bronze layer</strong>, they store raw data while offering key features such as <strong>versioning, ACID compliance</strong>, and <strong>time travel</strong>, which are essential for scalable and reliable data engineering workflows.</p><p>In the <strong>Silver layer</strong>, data from disparate sources is <strong>cleaned, standardized, and consolidated</strong> into curated tables within the data warehouse. This step ensures consistency across datasets and prepares them for analytical modeling.</p><p>The final <strong>Gold layer</strong> is built on top of this foundation through the creation of <strong>views</strong> that reflect a <strong>star schema</strong> — comprising fact and dimension tables — designed for consumption by <strong>Business Intelligence (BI)</strong> tools. The decision to use <strong>views instead of physical tables</strong> is intentional: views are <strong>lighter, more flexible</strong>, and offer <strong>faster query access</strong>, making them ideal for analytics workloads where performance and agility are key.</p><p>Moreover, by relying on views, we <strong>avoid writing additional scripts</strong> for data movement between layers. This not only <strong>simplifies the pipeline architecture</strong>, but also <strong>reduces data duplication</strong>, improves <strong>maintainability</strong>, and provides <strong>better traceability</strong> of data transformations — without compromising on performance.</p><p>Based on this modeling framework, we apply a concrete approach commonly referred to as <strong>data integration</strong>. This step, which takes place just before actual data modeling, involves building a <strong>comprehensive view of the available data</strong>. Depending on the business context and BI expectations, it helps define the <strong>processes for constructing the various dimensions</strong> of the data model. Ultimately, by aligning with the <strong>target KPIs</strong>, this phase allows us to design an architecture that matches both the business use cases and the nature of the available data sources.<br>More concretely, this involves <strong>identifying existing (or missing) connections between the different data sources</strong>, and — depending on the analytical needs — determining <strong>how to construct the analytical axes (dimensions)</strong> and define the <strong>key KPIs (i.e., measures within the fact table)</strong>. This strategic step ensures that the data model is both <strong>business-driven</strong> and <strong>technically feasible</strong>, setting a strong foundation for future insights and decision-making. Our small data integration look like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*9bcPBsye4HshtodYqmHoXg.png" /></figure><p>At the end of modeling, the Complete DataFlow of our project look like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wsgsXSrKH3e4CvkeyYEU5w.png" /></figure><p>At this stage of the project, we have all the <strong>theoretical and organizational foundations</strong> in place to design our data warehouse. Although this phase can often be seen as <strong>time-consuming</strong> by teams, it’s important to remember that <strong>nearly 50% of data warehouse projects fail</strong>. This is precisely why a <strong>thorough, well-structured, and meticulously planned modeling of the entire data warehouse pipeline</strong> is critical. It not only helps anticipate technical and business risks, but also ensures <strong>SLA compliance</strong> and significantly increases the likelihood of a successful and sustainable implementation.<br>Let’s pratice on MS Fabric conception.</p><p>For start wee need data, in our case data will be produce by our pyspark script. Using we’ll produce 1000 client’s information (Data from CRM). After about 70k of transactions observations(Data from CORE BANKING), which can imitate clients transaction on core banking system. Don’t forget that acccording to real banking modelisation, we’re talking about BIG DATA so we need to use scalable script tool’s like “PYSPARK”. And it’s exactly what we decide to use to produce data on our end to end data pipeline. Pyspark script look like :</p><pre>#!/usr/bin/env python<br># coding: utf-8<br><br># ## Generate_bronze_data<br># <br># New notebook<br><br># In[2]:<br><br><br>get_ipython().system(&#39;pip install faker&#39;)<br><br><br># In[3]:<br><br><br>import requests<br>from faker import Faker<br>import pandas as pd<br>import random<br>from datetime import datetime, timedelta<br>import random<br>from pyspark.sql import SparkSession<br>from pyspark.sql import Row<br>from datetime import date, timedelta<br><br><br># ## **GENERATE CRM SOURCE USING FAKER DEPENDANCES**<br><br># In[4]:<br><br><br># Initialiser Faker<br>fake = Faker(&#39;fr_FR&#39;)<br><br># Liste des codes pays fictifs<br>country_code = [&#39;CI&#39;, &#39;SN&#39;, &#39;ML&#39;, &#39;TG&#39;, &#39;BJ&#39;, &#39;BF&#39;, &#39;GN&#39;, &#39;NE&#39;, &#39;CM&#39;, &#39;GA&#39;]<br># Devise associée à chaque pays<br>devise = [&#39;XOF&#39;, &#39;XOF&#39;, &#39;XOF&#39;, &#39;XOF&#39;, &#39;XOF&#39;, &#39;XOF&#39;, &#39;GNF&#39;, &#39;XOF&#39;, &#39;XAF&#39;, &#39;XAF&#39;]<br><br># Fonction de génération de client<br>def generate_client(id_clt):<br>    return {<br>        &quot;id_clt&quot;: id_clt,  # identifiant du client<br>        &quot;num_compt&quot;: fake.bban(),  # Numéro de compte bancaire fictif<br>        &quot;nom&quot;: fake.last_name(),  # Nom du client<br>        &quot;prenom&quot;: fake.first_name(),  # Prénom du client<br>        &quot;tel&quot;: fake.phone_number(),  # Numéro de téléphone<br>        &quot;code_pays&quot;: random.choices(country_code)[0],  # pays d&#39;origine du client<br>        &quot;date_inscription&quot;: fake.date_between(start_date=&#39;-5y&#39;, end_date=&#39;today&#39;).isoformat(),  # date d&#39;inscription<br>        &quot;agence_id_inscription&quot;: random.randint(1, 15),  # ID agence<br>        &quot;type_personne&quot;: random.choice([&quot;physique&quot;, &quot;morale&quot;]),  # type de client<br>        &quot;score_kyc&quot;: random.randint(0, 100),  # score KYC<br>        &quot;nombre_produit_souscrit&quot;: random.randint(1, 5),  # produits souscrits<br>        &quot;type_compt&quot;: random.choice([&quot;premium-plus&quot;, &quot;premium&quot;, &quot;normal&quot;])  # type de compte<br>    }<br><br><br># In[5]:<br><br><br># Create a SparkSession<br>spark = SparkSession.builder \<br>    .appName(&quot;CreateDataFrame&quot;) \<br>    .getOrCreate()<br><br><br># In[6]:<br><br><br># Génération des 2000 clients<br>clients = [generate_client(i) for i in range(1, 2001)]<br><br># Transformation en Spark DataFrame<br>df = spark.createDataFrame([Row(**client) for client in clients])<br><br><br># In[7]:<br><br><br>display(df)<br><br><br># ## **GENERATE CORE-BANKING DATA**<br><br># In[8]:<br><br><br># Quelques constantes<br>type_trx_list = [&#39;TRANSFERT&#39;, &#39;DEPOT&#39;, &#39;RETRAIT&#39;]<br>status_trx_list = [&#39;SUCCES&#39;, &#39;ECHEC&#39;]<br>bank_devices =  [&#39;MOBILE&#39;, &#39;ATM&#39;, &#39;AGENCE&#39;, &#39;WEB&#39;]<br>bban_list = df.select(&#39;num_compt&#39;).rdd.flatMap(lambda x: x).collect()<br>dict_devises =  dict(zip(country_code, devise))<br>number_agence = 10<br>limit_table_core_banking =  2000<br><br><br># In[9]:<br><br><br>def generate_transactions_between(type_transaction, list_bban =  bban_list):<br>    if type_transaction == &#39;TRANSFERT&#39;:<br>        num_compt_init = random.choice(bban_list)<br>        num_compt_dest = random.choice(bban_list)<br>    elif type_transaction == &#39;DEPOT&#39;:<br>        compte = random.choice(bban_list)<br>        num_compt_init = compte<br>        num_compt_dest = compte<br>    elif type_transaction == &#39;RETRAIT&#39;:<br>        num_compt_init = None<br>        num_compt_dest = random.choice(bban_list)<br>    else:<br>        raise ValueError(&quot;Type de transaction non reconnu&quot;)<br><br>    return {&#39;init&#39;: num_compt_init, &#39;dest&#39;:num_compt_dest}<br><br><br># Génération des 500 transactions<br>def generate_transaction(id):<br><br>    date_trx = fake.date_time_between(start_date=&#39;-2y&#39;, end_date=&#39;now&#39;)<br>    type_trx = random.choice(type_trx_list)<br>    between = generate_transactions_between(type_transaction = type_trx, list_bban = bban_list)<br>    montant_trx = round(random.uniform(1000, 500000), 2)<br>    num_compt_init = between[&#39;init&#39;]<br>    num_compt_dest = between[&#39;dest&#39;]<br>    agence_id = random.randint(1, number_agence)<br>    agence_nom = f&quot;AGENCE-XX{agence_id}&quot;<br>    status_trx = random.choice(status_trx_list)<br>    code_pays = random.choice(country_code)<br>    devise = dict_devises[f&#39;{code_pays}&#39;]<br>    device_of_trx = random.choice(bank_devices)<br><br>    return {<br>        &#39;id_trx&#39;: f&quot;TRX-{id}&quot;,<br>        &#39;date_trx&#39;: date_trx.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;),<br>        &#39;type_trx&#39;: type_trx,<br>        &#39;montant_trx&#39;: montant_trx,<br>        &#39;num_compt_init&#39;: num_compt_init,<br>        &#39;num_compt_dest&#39;: num_compt_dest,<br>        &#39;agence_id&#39;: agence_id,<br>        &#39;agence_nom&#39;: agence_nom,<br>        &#39;status_trx&#39;: status_trx,<br>        &#39;code_pays&#39;: code_pays,<br>        &#39;devise&#39;: devise,<br>        &#39;device_of_trx&#39;: device_of_trx<br>    }<br><br><br># In[10]:<br><br><br># Création du dataset<br>data = [generate_transaction(i+1) for i in range(limit_table_core_banking)]<br>core_banking =  spark.createDataFrame([Row(**trx) for trx in data])<br><br><br># In[11]:<br><br><br>display(core_banking)<br><br><br># ## **LOAD DATA ON LAKEHOUSE SPACE**<br><br># In[25]:<br><br><br>uniques_countries_crm =  df.select(&#39;code_pays&#39;).distinct().collect()<br>uniques_countries_crm = [row[&#39;code_pays&#39;] for row in uniques_countries_crm ]<br>uniques_countries_crm<br><br><br># In[29]:<br><br><br>for country in uniques_countries_crm:<br>    dt =  df.filter(df.code_pays == f&quot;{country}&quot;)<br>    # create table  associate to country<br>    dt.write.mode(&#39;overwrite&#39;).saveAsTable(f&#39;source_crm_{country}&#39;)<br>    print(f&#39;=========== TABLE DELTA - SOURCE CRM --{country}-- CREATED WITH SUCCESS ===========&#39;)<br><br><br># In[12]:<br><br>#crm<br># df.write.mode(&#39;overwrite&#39;).saveAsTable(&#39;source_crm_bronze&#39;)<br><br># In[34]:<br><br>unique_type_trx =  core_banking.select(&#39;type_trx&#39;).distinct().collect()<br>unique_type_trx =  [row[&#39;type_trx&#39;] for row in unique_type_trx]<br>unique_type_trx<br><br># In[36]:<br><br><br>for trx in unique_type_trx: <br>    dtrx =  core_banking.filter(core_banking.type_trx == f&quot;{trx}&quot;)<br>    # create table to type_trx<br>    dtrx.write.mode(&#39;overwrite&#39;).saveAsTable(f&#39;source_core_banking_{trx}&#39;)<br>    print(f&#39;=========== TABLE DELTA - SOURCE CORE BANKING --{trx}-- CREATED WITH SUCCESS ===========&#39;)<br><br><br># In[18]:<br><br><br>#core_baknking<br># core_banking.write.mode(&#39;overwrite&#39;).saveAsTable(&#39;source_core_banking_bronze&#39;)</pre><p>If you’re more familiarize with notebook you can see, notebook’s details on the github repository associated to this project. But to sum up it’s this principal code we’ll developp on our fabric to generate data precisely in our datalakehouse.<em> But concretly how to create a notebook on fabric ?</em> Create notebook in fabric it too easy just click on your the wokspace associated to your project like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*79WM8jjCpe3Qc__9iEaZig.png" /></figure><p>Once our PySpark code is executed, several Delta tables are generated and appear in the “Tables” tab of our datalakehouse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55GzG16NWmXMV8KBQ8Qc-A.png" /></figure><p>The Bronze stage of our pipeline was successfully completed.<br>The next step, the Silver stage, will involve:</p><p><strong><em>(1) Merging disparate data sources</em><br><em>(2) Performing various transformations in order to produce higher-quality data, ready to support a consistent semantic model suitable for BI projects.</em></strong></p><p>To make this, we’ll you use a powerful the 2nd generation dataflow tools of MS Fabric call : <strong>Dataflow gen2</strong></p><p>This tool is based on power query and will really data engineer to make easy transformation over with low-code. Let’s Launch this tool to make our transformations :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*en30GFFBS6jqnDn5i-Xfog.png" /></figure><ul><li><strong>In purple</strong>: If you’re familiar with <strong>Power Query</strong>, this is the main workspace for performing all types of data transformations. (If not, it’s worth getting familiar with Power Query!)</li><li><strong>In red</strong>: A <strong>directed acyclic diagram</strong> that visually represents the sequence of transformation steps applied from a data source to a destination.</li><li><strong>In black</strong>: The <strong>queries</strong>, which in Power BI can be seen as tables containing various records — either from existing sources in the datalakehouse or created through transformations.</li><li><strong>In green</strong>: The <strong>transformation steps</strong> applied to the source data, which can be freely modified using <strong>M code</strong>.</li><li><strong>In orange</strong>: A <strong>tabular view</strong> of the currently selected table.</li><li><strong>In blue</strong>: The <strong>delivery point</strong> for the transformed data — representing a Silver-level data source.</li></ul><p>Once the data has been transformed, it’s important to ensure that all operations were successfully executed. To do this, we’ll perform data quality checks using a dedicated notebook for evaluation tests. Data quality test notebook look like :</p><pre>#!/usr/bin/env python<br># coding: utf-8<br><br># ## Qod-Process<br># <br># New notebook<br><br># # DATA QUALITY CHECKS OVER SILVER TABLE<br><br># In[30]:<br><br><br>from datetime import datetime <br>import com.microsoft.spark.fabric<br>from com.microsoft.spark.fabric.Constants import Constants<br><br><br># In[38]:<br><br><br>class SilverDataModels: pass<br><br>class SilverCoreBankModels(SilverDataModels):<br>    num_compt_init: str<br>    num_compt_dest: str<br>    status_trx : str<br>    agence_id : int<br>    montant_trx: float <br>    devise :  str <br>    agence_nom : str <br>    type_trx :  str <br>    date_trx : datetime <br>    code_pays : str <br>    id_trx : str<br>    device_of_trx :  str<br><br>class SilverCrmModels(SilverDataModels):<br>    score_kyc: int <br>    nombre_produit_souscrit : int <br>    tel : str <br>    id_clt : int <br>    type_compt : str <br>    num_compt :  str <br>    agence_id_inscription : int <br>    nom : str <br>    type_personne : str <br>    prenom : str <br>    code_pays :  str<br>    date_inscription: str<br><br><br># In[32]:<br><br><br># read silver_core_bank and silver <br>silver_crm =  spark.read.synapsesql(&#39;bank-dwh.schema_silver.silver_crm&#39;)<br>silver_core_bank =  spark.read.synapsesql(&#39;bank-dwh.schema_silver.silver_core_bank&#39;)<br><br><br># In[41]:<br><br><br>class DataQualityChecks: <br>    @staticmethod<br>    def schema_check(data_model: SilverDataModels, colums_dataframe: list , table_name =  None):<br><br>        list_models =  data_model.__annotations__.keys()<br>        # number of columns<br>        assert len(list_models) == len(colums_dataframe)<br><br>        # set of columns  <br>        assert set(list_models) == set(colums_dataframe)<br><br>        print(f&quot; &gt;&gt;&gt; SCHEMA CHECK REALIZE WITH SUCCESS OVER {table_name} &gt;&gt;&gt;&quot;)<br><br>    # add functions associate to what you want !<br><br><br># ### CHECKING ...<br><br># In[44]:<br><br><br># check over crm silver_crm<br>DataQualityChecks.schema_check(data_model=SilverCrmModels, colums_dataframe = silver_crm.columns , table_name=&#39;SILVER_CRM&#39;)<br><br><br># In[45]:<br><br><br># check over core_bank <br>DataQualityChecks.schema_check(data_model=SilverCoreBankModels, colums_dataframe = silver_core_bank.columns, table_name= &#39;SILVER_CORE_BANK&#39; )<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hd00R_sqDhsBnM-M5qajlA.png" /></figure><p>The tests were successfully executed, and the data meets expectations — the <strong>Silver stage</strong> of our data pipeline is now complete.</p><p>We now move on to the <strong>Gold stage</strong>, where the data is prepared for end-use.<br> Based on our data architecture, it is important to note that, given the context, we have chosen to primarily use <strong>views</strong> for the reasons mentioned earlier.</p><p>This stage involves writing <strong>T-SQL scripts</strong> to define <strong>dimension tables</strong> and <strong>fact tables</strong>. These views are designed to point to a database operating in <strong>full-load mode</strong>.</p><p>Below is an overview of the various scripts used to construct the dimension and fact tables, in alignment with the data model presented above.</p><pre>-- CREATE DIMENSION_DEVISE<br>IF OBJECT_ID(&#39;schema_gold.DIMENSION_DEVISE&#39;, &#39;V&#39;) IS NOT NULL <br>    DROP VIEW [schema_gold].[DIMENSION_DEVISE]<br><br>CREATE VIEW schema_gold.DIMENSION_DEVISE AS<br>SELECT <br>    ROW_NUMBER() OVER (ORDER BY devise) AS id_devise,<br>    devise<br>FROM (<br>    SELECT DISTINCT devise<br>    FROM schema_silver.silver_core_bank<br>) AS DIMENSION_DEVISE;<br><br>-- CREATE DIMENSION_PAYS<br>IF OBJECT_ID(&#39;schema_gold.DIMENSION_PAYS&#39;, &#39;V&#39;) IS NOT NULL <br>    DROP VIEW [schema_gold].[DIMENSION_PAYS]<br><br>CREATE VIEW schema_gold.DIMENSION_PAYS AS<br>SELECT <br>    ROW_NUMBER() OVER (ORDER BY code_pays) AS id_pays,<br>    code_pays<br>FROM (<br>    SELECT DISTINCT code_pays<br>    FROM schema_silver.silver_core_bank<br>) AS DIMENSION_PAYS;<br><br>-- CREATE DIMENSION TERMINAL<br>IF OBJECT_ID(&#39;schema_gold.DIMENSION_TERMINAL&#39;, &#39;V&#39;) IS NOT NULL <br>    DROP VIEW [schema_gold].[DIMENSION_TERMINAL]<br><br><br>CREATE VIEW schema_gold.DIMENSION_TERMINAL AS<br>SELECT <br>    ROW_NUMBER() OVER (ORDER BY device_of_trx) AS id_terminal,<br>    device_of_trx as terminal<br>FROM (<br>    SELECT DISTINCT device_of_trx<br>    FROM schema_silver.silver_core_bank<br>) AS DIMENSION_TERMINAL;<br><br><br>-- CREATE DIMENSION_AGENCE<br>IF OBJECT_ID(&#39;schema_gold.DIMENSION_AGENCE&#39;, &#39;V&#39;) IS NOT NULL<br>    DROP VIEW schema_gold.DIMENSION_AGENCE;<br><br>CREATE VIEW schema_gold.DIMENSION_AGENCE AS<br>SELECT DISTINCT agence_id, agence_nom<br>FROM schema_silver.silver_core_bank;<br><br><br>-- CREATE DIMENSION_TYPE_TRX<br>IF OBJECT_ID(&#39;schema_gold.DIMENSION_TYPE_TRX&#39;, &#39;V&#39;) IS NOT NULL<br>    DROP VIEW schema_gold.DIMENSION_TYPE_TRX;<br><br>CREATE VIEW schema_gold.DIMENSION_TYPE_TRX AS<br>SELECT <br>    ROW_NUMBER() OVER (ORDER BY type_trx) AS id_type_trx, <br>    type_trx<br>FROM (<br>    SELECT DISTINCT type_trx<br>    FROM schema_silver.silver_core_bank<br>) AS t<br><br>--CREATE DIMENSION_DATE<br>IF OBJECT_ID(&#39;schema_gold.DIMENSION_DATE&#39;, &#39;U&#39;) IS NOT NULL<br>    DROP VIEW schema_gold.DIMENSION_DATE;<br><br>CREATE VIEW schema_gold.DIMENSION_DATE AS<br>SELECT <br>    ROW_NUMBER() OVER (ORDER BY date_trx) as id_date,<br>    date_trx,<br>    MONTH(date_trx) AS mois, <br>    DAY(date_trx) AS jours, <br>    YEAR(date_trx) as annee<br>FROM (<br>    SELECT <br>        DISTINCT CONVERT(DATE, date_trx, 120) as date_trx<br>    FROM schema_silver.silver_core_bank<br><br>) AS t<br><br><br>-- CREATE DIMENSION_CLIENT<br>IF OBJECT_ID(&#39;schema_gold.DIMENSION_CLIENT&#39;, &#39;V&#39;) IS NOT NULL<br>    DROP VIEW schema_gold.DIMENSION_CLIENT<br><br>CREATE  VIEW schema_gold.DIMENSION_CLIENT AS<br>SELECT *<br>FROM schema_silver.silver_crm;<br><br><br>-- CREATE FACTTABLE<br>IF OBJECT_ID(&#39;schema_gold.FACTTABLE&#39;, &#39;V&#39;) IS NOT NULL<br>    DROP VIEW schema_gold.FACTTABLE;<br><br><br>CREATE VIEW schema_gold.FACTTABLE AS <br>SELECT <br>    CONVERT(DATE, t.date_trx, 120) as date, <br>    t.num_compt_init,<br>    t.num_compt_dest,<br>    t.montant_trx,<br>    dim_agence.agence_id, <br>    dim_devise.id_devise, <br>    dim_type_trx.id_type_trx,<br>    dim_terminal.id_terminal,<br>    dim_pays.id_pays<br>FROM schema_silver.silver_core_bank as t<br>LEFT JOIN (SELECT * FROM schema_gold.DIMENSION_AGENCE) as dim_agence<br>ON t.agence_id = dim_agence.agence_id<br>LEFT JOIN (SELECT * FROM schema_gold.DIMENSION_DEVISE) as dim_devise<br>ON t.devise =  dim_devise.devise<br>LEFT JOIN (SELECT * FROM schema_gold.DIMENSION_TYPE_TRX) as dim_type_trx<br>ON t.type_trx = dim_type_trx.type_trx<br>LEFT JOIN (SELECT * FROM schema_gold.DIMENSION_TERMINAL) as dim_terminal<br>ON t.device_of_trx = dim_terminal.terminal<br>LEFT JOIN (select * from schema_gold.DIMENSION_PAYS) as dim_pays<br>ON t.code_pays =  dim_pays.code_pays</pre><p>Now let’s check our datawarehouse with gold layer views:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*ua06Ne3kiMQjVGRZOt1Q1A.png" /></figure><p>Let’s look over one dimension, for example <strong>DIMENSION_CLIENT </strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iYbYSo7zEwxfK3yuERIlw.png" /></figure><p>Once these scripts are executed, we can see the various <strong>views</strong> created in the <strong>Gold layer</strong> of our data pipeline.<br> With that, the <strong>Gold stage is complete — congratulations!</strong></p><p>However, a truly complete data flow is one that is <strong>automated</strong>. That’s where a powerful tool comes in — <strong>a data pipeline orchestrator</strong> — designed to link the different tasks into a visual diagram of processes.</p><p>It also handles full <strong>workflow automation</strong>, making it a favorite tool among data engineers. Naturally, it accelerates the delivery of data through the pipeline.</p><p>Once configured and fine-tuned, the pipeline looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkjd3iw2vVjlDIF6zlY56Q.png" /></figure><p>At the end of this project — which was more theoretical than technical — it’s important to remember that setting up a <strong>data warehouse</strong> requires a carefully thought-out methodology. In fact, studies show that nearly <strong>50% of data warehouse projects fail</strong>, often due to poor planning or misalignment with business needs. A <strong>successful data warehouse</strong> is one that is <strong>well-modeled</strong> and effectively aligned with the expectations of <strong>end users</strong>. We also observed that <strong>Microsoft Fabric</strong> is a fairly <strong>mature and robust platform</strong>, offering a wide range of tools that truly make <strong>data engineering</strong>, <strong>data science</strong>, and other data workflows both easier and — dare I say — even fun to work with. On the secondepisode, get ready because we’ll talk abouts something like : <strong>Data Monitoring, Documentation, Security &amp; Viz.</strong></p><p>Feel free to reach out to me via email at <strong>nisaacemmanuel@gmail.com</strong> for any questions or further discussions. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6342dde044" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mini Project : Own Cluster Spark using Docker | Docker-Compose]]></title>
            <link>https://blog.devgenius.io/mini-project-own-cluster-spark-using-docker-docker-compose-f648e2e439ec?source=rss-5fdee2b4e407------2</link>
            <guid isPermaLink="false">https://medium.com/p/f648e2e439ec</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[hadoop]]></category>
            <dc:creator><![CDATA[is2ac]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 10:47:19 GMT</pubDate>
            <atom:updated>2025-04-09T17:45:21.182Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mini Project : Own Cluster Spark using only Docker &amp; Docker-Compose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpMdofatK7DF4JNgpF-PnA.png" /></figure><p>The role of a Data Engineer is often perceived as complex due to the ever-evolving tech landscape. Every week, new technologies emerge, with experts and tech advocates predicting their rise as the next big industry standard. In this highly competitive environment, one technology has remained a cornerstone for nearly 16 years: <strong>Apache Spark</strong>. Designed to tackle challenges related to data volume, velocity, and value, Spark stands out for its distributed processing capabilities, making it a game-changer in the world of data. However, getting started with this type of technology is not always easy. Why? Because despite having the motivation, setting up a ready-to-use infrastructure for hands-on learning can be quite challenging.</p><p>In this mini-tutorial, I’ll show you how to leverage <a href="https://github.com/codespaces"><strong>GitHub Codespaces</strong></a><strong> </strong>and <strong>Docker</strong> to deploy your own Spark cluster and start mastering this powerful technology. Just three months ago, I had no idea what<a href="https://github.com/codespaces"> <strong>GitHub Codespaces</strong></a> was. For those in the same situation, it’s a free service from GitHub that can be thought of as <strong>“vscode-as-a-Service.”</strong> Essentially, it’s a Docker-based instance of a fully managed machine that GitHub provides to the community. Today, I truly believe that not having a powerful computer is no longer a valid excuse for not learning to code. With all these accessible solutions, anyone can start coding regardless of their hardware.</p><p>Two years ago, I didn’t have a machine powerful enough to run Docker. If you’re in the same boat, <a href="https://github.com/codespaces"><strong>GitHub Codespaces</strong></a> is a great alternative. But even with a standard computer, this project is completely doable.</p><h3>Prerequisites for this mini-project:</h3><p>✅ <strong>Docker &amp; Docker Compose</strong> installed and running<br> 💡 <em>Good news: On GitHub Codespaces, Docker and Docker Compose come preinstalled by default.</em><br> ✅ the python library <strong>make</strong>, to simplify long command executions.</p><p><strong>Let’s go! 🚀</strong></p><p><strong>Firstly</strong> In the main space of your project we’ll firstly create the spark configuration repertory call : /conf/<strong>spark-defaults.conf</strong></p><pre>spark.master                           spark://spark-master:7077<br>spark.eventLog.enabled                 true<br>spark.eventLog.dir                     /opt/spark/spark-events<br>spark.history.fs.logDirectory          /opt/spark/spark-events</pre><ul><li><strong>You have a standalone Spark cluster</strong> at spark://spark-master:7077.</li><li><strong>Event logging is enabled</strong> for tracking job execution.</li><li><strong>Logs are stored in </strong><strong>/opt/spark/spark-events</strong>.</li><li><strong>The Spark History Server reads these logs</strong> to show past job executions.</li></ul><p><strong>Secondly</strong> on the main space you create a shell file call : <strong>.env.spark</strong></p><pre>SPARK_NO_DAEMONIZE=true</pre><p>The environment variable <strong>SPARK_NO_DAEMONIZE=true</strong> is used when starting Spark services (such as the master, worker, or history server). Here’s what it does:</p><h3>Effect of SPARK_NO_DAEMONIZE=true</h3><ul><li>Normally, when you start a Spark service (e.g., start-master.sh, start-worker.sh), it <strong>runs in the background as a daemon</strong>.</li><li>Setting <strong>SPARK_NO_DAEMONIZE=true</strong> forces the service <strong>to run in the foreground</strong> instead of as a background process.</li></ul><h3>Why use it?</h3><ul><li><strong>Useful in Docker containers</strong>:</li><li>In Docker, processes running in the foreground are required for the container to stay alive.</li><li>Running Spark services in daemon mode would make the container exit immediately after startup.</li></ul><p><strong>Thirdly</strong> create a shell file call : <strong>entrypoint.sh</strong></p><pre>#!/bin/bash<br><br>SPARK_WORKLOAD=$1<br><br>echo &quot;SPARK_WORKLOAD: $SPARK_WORKLOAD&quot;<br><br>if [ &quot;$SPARK_WORKLOAD&quot; == &quot;master&quot; ];<br>then<br>  start-master.sh -p 7077<br>elif [ &quot;$SPARK_WORKLOAD&quot; == &quot;worker&quot; ];<br>then<br>  start-worker.sh spark://spark-master:7077<br>elif [ &quot;$SPARK_WORKLOAD&quot; == &quot;history&quot; ]<br>then<br>  start-history-server.sh<br>fi</pre><p>This Bash script starts a Spark service based on the first argument passed ($1).</p><h3>How It Works:</h3><ol><li><strong>Retrieves the type of Spark service</strong> to start (SPARK_WORKLOAD=$1).</li><li><strong>Displays the value of </strong><strong>SPARK_WORKLOAD</strong> for information.</li><li><strong>Conditionally:</strong></li></ol><ul><li>If SPARK_WORKLOAD is &quot;master&quot;, it starts the <strong>Spark Master</strong> on port 7077.</li><li>If SPARK_WORKLOAD is &quot;worker&quot;, it starts a <strong>Worker</strong> that connects to the master at spark://spark-master:7077.</li><li>If SPARK_WORKLOAD is &quot;history&quot;, it starts the <strong>Spark History Server</strong>.</li></ul><p>Now that we have all the essentials, it’s time to set up the infrastructure. It will consist of <strong>Docker containers</strong> organized into <strong>services</strong> and connected within the same network, effectively forming a <strong>cluster</strong>, as defined by <strong>Docker &amp;</strong> <strong>Docker Compose</strong>.</p><ul><li>Dockerfile look like :</li></ul><pre># Use a lightweight Python 3.11 image based on Debian Bullseye as the base image<br>FROM python:3.11-slim-bullseye as spark-base<br><br># Define an argument to specify the Spark version<br># ⚠️ Ensure that a valid Spark version is provided; otherwise, the download will fail!<br>ARG SPARK_VERSION=3.5.5<br><br># Install required system dependencies for Spark and Hadoop<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y --no-install-recommends \<br>    sudo \                # Administrative privileges<br>    curl \                # File download utility<br>    vim \                 # Text editor (useful for debugging)<br>    unzip \               # Extract compressed files<br>    rsync \               # File synchronization tool<br>    openjdk-11-jdk \      # Java required for Spark<br>    build-essential \     # Compilation tools (gcc, make, etc.)<br>    software-properties-common \ # System utilities<br>    ssh &amp;&amp; \              # SSH required for communication between Spark nodes<br>    apt-get clean &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*  # Clean up to reduce image size<br><br># Set environment variables for Spark and Hadoop<br>ENV SPARK_HOME=${SPARK_HOME:-&quot;/opt/spark&quot;}<br>ENV HADOOP_HOME=${HADOOP_HOME:-&quot;/opt/hadoop&quot;}<br><br># Create necessary directories for Spark and Hadoop<br>RUN mkdir -p ${HADOOP_HOME} &amp;&amp; mkdir -p ${SPARK_HOME}<br>WORKDIR ${SPARK_HOME}<br><br># Download and install Spark using the specified SPARK_VERSION<br># ⚠️ Make sure that the version specified in SPARK_VERSION exists on the Apache server!<br>RUN curl https://dlcdn.apache.org/spark/spark-${SPARK_VERSION}/spark-${SPARK_VERSION}-bin-hadoop3.tgz -o spark-${SPARK_VERSION}-bin-hadoop3.tgz \<br> &amp;&amp; tar xvzf spark-${SPARK_VERSION}-bin-hadoop3.tgz --directory /opt/spark --strip-components 1 \<br> &amp;&amp; rm -rf spark-${SPARK_VERSION}-bin-hadoop3.tgz  # Remove the archive to save space<br><br># Install required Python dependencies<br>COPY requirements.txt .<br>RUN pip3 install -r requirements.txt<br><br># Add Spark paths to the environment variables<br>ENV PATH=&quot;/opt/spark/sbin:/opt/spark/bin:${PATH}&quot;<br>ENV SPARK_HOME=&quot;/opt/spark&quot;<br>ENV SPARK_MASTER=&quot;spark://spark-master:7077&quot;<br>ENV SPARK_MASTER_HOST=spark-master<br>ENV SPARK_MASTER_PORT=7077<br>ENV PYSPARK_PYTHON=python3  # Set Python 3 as the default for PySpark<br><br># Copy Spark configuration file<br>COPY conf/spark-defaults.conf &quot;$SPARK_HOME/conf&quot;<br><br># Grant execution permissions to Spark scripts<br>RUN chmod u+x /opt/spark/sbin/* &amp;&amp; \<br>    chmod u+x /opt/spark/bin/*<br><br># Add PySpark to PYTHONPATH to allow Spark module imports in Python<br>ENV PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH<br><br># Copy the entrypoint script that will start the required services<br>COPY entrypoint.sh .<br><br># Define the container entrypoint<br>ENTRYPOINT [&quot;./entrypoint.sh&quot;]</pre><ul><li>docker-compose.yml look like :</li></ul><pre>version: &#39;3.8&#39;<br><br>services:<br>  spark-master:<br>    container_name: da-spark-master<br>    build: .<br>    image: da-spark-image<br>    entrypoint: [&#39;./entrypoint.sh&#39;, &#39;master&#39;]<br>    healthcheck:<br>      test: [ &quot;CMD&quot;, &quot;curl&quot;, &quot;-f&quot;, &quot;http://localhost:8080&quot; ]<br>      interval: 5s<br>      timeout: 3s<br>      retries: 3<br>    volumes:<br>      - ./book_data:/opt/spark/data<br>      - ./spark_apps:/opt/spark/apps<br>      - spark-logs:/opt/spark/spark-events<br>    env_file:<br>      - .env.spark<br>    ports:<br>      - &#39;9090:8080&#39;<br>      - &#39;7077:7077&#39;<br><br><br>  spark-history-server:<br>    container_name: da-spark-history<br>    image: da-spark-image<br>    entrypoint: [&#39;./entrypoint.sh&#39;, &#39;history&#39;]<br>    depends_on:<br>      - spark-master<br>    env_file:<br>      - .env.spark<br>    volumes:<br>      - spark-logs:/opt/spark/spark-events<br>    ports:<br>      - &#39;18080:18080&#39;<br><br>  spark-worker:<br>#    container_name: da-spark-worker<br>    image: da-spark-image<br>    entrypoint: [&#39;./entrypoint.sh&#39;, &#39;worker&#39;]<br>    depends_on:<br>      - spark-master<br>    env_file:<br>      - .env.spark<br>    volumes:<br>      - ./book_data:/opt/spark/data<br>      - ./spark_apps:/opt/spark/apps<br>      - spark-logs:/opt/spark/spark-events<br><br>volumes:<br>  spark-logs:</pre><p>Finally the Makefile on the project space look like :</p><pre>WORKERS ?= 3 # number of workers for scaling<br><br>build:<br> docker compose build  <br><br>build-nc:<br> docker compose build --no-cache<br><br>build-progress:<br> docker compose build --no-cache --progress=plain<br><br>down:<br> docker compose down --volumes<br><br>run:<br> make down &amp;&amp; docker compose up<br><br>run-scaled:<br> make down &amp;&amp; docker compose up --scale spark-worker=$(WORKERS)<br><br>run-d:<br> make down &amp;&amp; docker compose up -d<br><br>stop:<br> docker compose stop<br><br>submit:<br> docker exec da-spark-master spark-submit --master spark://spark-master:7077 --deploy-mode client ./apps/$(app)<br><br>log-master:<br> docker logs -f da-spark-master<br><br>log-master:<br> docker logs -f da-spark-master</pre><p>We need also to add some dependencies on requirements.txt file :</p><pre>ipython<br>pandas<br>pyarrow<br>numpy<br>pyspark</pre><p>So at the end of this your project space look like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*iWCNej4bs1dO6H5kQxcw3w.png" /></figure><p>The first command to launch for making a build of your main spark image:</p><pre>make build</pre><p>if all things are be done, you can verify on your docker image space by launching:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Q32Cfmt03ulSuXCuFXwHw.png" /></figure><p>Your image are now on your docker image’s space let’s launch the cluster with for example 4 instances (1 master + 4 workers), with this command :</p><pre>make run-scaled WORKERS=4</pre><p>like he look on the Makefile check on it this command.</p><p>At the first launching you can have some error like that :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNmgmsqWpUR7hSMAz7bTTw.png" /></figure><p>The problem is just about authorization on entrypoint.sh, just using chmod command you can fix it :</p><pre>sudo chmod x+ entrypoint.sh</pre><p>And now re-build your image by launch your image :</p><pre># firstly <br>make build<br># secondly <br>make run-scaled WORKERS=4</pre><p>When you see something like that on your terminal :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98JYQogt-KjkhF7YPE97hA.png" /></figure><p>Congratulations, you’ve now create your own cluster spark for free.</p><p>On your the url <strong>port 9090</strong> you’ll see something like that :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJMNq-aYJSyybdkWTQBmnw.png" /></figure><p>your spark cluster your 4 worker ready to execute your future pyspark or scala job. And the endpoint with url <strong>port 18080 </strong>you’ll see the spark history UI, which look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmOFkT1DdSBvhLzyfmNmMA.png" /></figure><p><strong>BONUS : Let’s launch a python job on our cluster.</strong></p><p>firstly pyspark code look like.</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql import Row<br><br># Initialiser une session Spark<br>spark = SparkSession.builder.appName(&quot;SimpleDataFrame&quot;).getOrCreate()<br><br># Créer des données sous forme de liste de dictionnaires<br>data = [<br>    Row(id=1, name=&quot;Alice&quot;, age=25),<br>    Row(id=2, name=&quot;Bob&quot;, age=30),<br>    Row(id=3, name=&quot;Charlie&quot;, age=35)<br>]<br><br># Créer un DataFrame à partir des données<br>df = spark.createDataFrame(data)<br><br># Afficher le DataFrame<br>df.show()<br><br># Arrêter la session Spark<br>spark.stop()</pre><p>For launching this job pyspark, we firstly create a python file on the volume <strong>spark_apps/ </strong>call job_pyspark.py .If you have a problem of permission don’t forget to do this command:</p><pre>sudo chmod 777 spark_apps/</pre><p>After launch this comand :</p><pre>make connec-spark-master<br>spark-submit --master spark://spark-master:7077 apps/job_pyspark.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_nRn7eCGLAK5x9TM_u8HA.png" /></figure><p>🎯🎯 Finish, Mission Completed</p><p>It’s done! Nowadays, gaining expertise in complex technologies like Spark is much more accessible thanks to Docker. Feel free to clone my project on <a href="https://github.com/IS2aC/docker-cluster-spark-learning">GitHub</a> or reach out to me directly via email at <strong>nisaacemmanuel@gmail.com.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f648e2e439ec" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mini-project-own-cluster-spark-using-docker-docker-compose-f648e2e439ec">Mini Project : Own Cluster Spark using Docker | Docker-Compose</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End to end Batch Data quality pipeline with Astronomer, Airbyte, Snowflake & SODA]]></title>
            <link>https://medium.com/@nisaacemmanuel/end-to-end-batch-data-quality-pipeline-with-astronomer-airbyte-snowflake-soda-ca7a70f15300?source=rss-5fdee2b4e407------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca7a70f15300</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[soda]]></category>
            <dc:creator><![CDATA[is2ac]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 20:31:26 GMT</pubDate>
            <atom:updated>2025-02-06T13:20:05.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>End to End Batch Data Quality Pipeline with Astronomer, Airbyte, Snowflake &amp; SODA</h3><p>In a world where data plays a central role in strategic decision-making, companies — particularly global giants like the GAFAM — have made data management the cornerstone of their success. However, the famous saying <strong>“garbage in, garbage out”</strong> (erroneous inputs produce erroneous outputs) sharply highlights the significant risk any organization faces: basing decisions on poor-quality data. Thus, in the design of a data pipeline, the rigorous evaluation of data quality and the establishment of dedicated processes become absolute imperatives. These efforts must not only meet technical requirements but also align with the company’s business objectives, as reliable data forms the foundation of robust decision intelligence. In this context, the proposed project aims to develop a batch data pipeline that integrates quality checks at every key stage of the process. To achieve this, the cloud-based solution <strong>Soda</strong> will be implemented to automate data quality assessments, ensure data integrity, and prevent deviations that could compromise downstream analyses or decision-making models.</p><p><em>With the context now established, let us move on to the architecture of the data pipeline that we will design as part of this tutorial.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnOaiXVXxjWl1eF-8bEKpg.png" /></figure><p>In line with the architecture outlined above, here is a detailed and comprehensive list of its components:</p><ul><li><strong>Google Sheets</strong>: used as the primary data source.</li><li><strong>Airbyte</strong>: a tool dedicated to ELT (Extract &amp; Load) operations.</li><li><strong>Airflow and Astronomer</strong>: a combined solution for deploying data pipelines, integrating the open-source orchestration framework Airflow.</li><li><strong>Snowflake</strong>: a storage platform used to store data at each critical stage of the pipeline.</li><li><strong>Soda Core and Soda Cloud</strong>: solutions employed to conduct tests and monitor data quality throughout the pipeline.</li><li><strong>Power BI</strong>: a data visualization tool for effectively representing insights in a clear and meaningful way.</li></ul><p>In the design of a data pipeline, just as with the analysis of requirements, evaluation of the technical stack, and infrastructure sizing, it is essential to consider the expectations regarding data quality. This is crucial for minimizing unforeseen issues that could compromise the reliability of our analyses.</p><p>To this end, I propose the implementation of a detailed checklist aligned with the expected standards at each key stage of the data pipeline. Naturally, this checklist should be adaptable, as the requirements for data quality may evolve over time. This adaptability emphasizes the importance of considering a data pipeline as a comprehensive and flexible solution, capable of naturally evolving to meet new needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKaEhEhqyYilHp37X2Nt0w.png" /></figure><p>Now that we’ve covered the essentials, let’s get down to business:</p><h3>Prerequisites:</h3><p>To successfully complete this project, it’s necessary to install the following tools in advance:</p><ul><li><strong>DOCKER</strong> → <a href="https://docs.docker.com/engine/install/">Download link</a></li><li><strong>ASTRO CLI</strong> → <a href="https://www.astronomer.io/docs/astro/cli/install-cli/">Download link</a></li><li><strong>AIRBYTE CLOUD ACCOUNT</strong> (Free 14 days) → <a href="https://airbyte.com/">Link to Airbyte</a></li><li><strong>SODA CLOUD ACCOUNT</strong> (Free 30 days) → <a href="https://www.soda.io/">Link to Soda</a></li><li><strong>SNOWFLAKE ACCOUNT</strong> → <a href="https://www.snowflake.com/en/">Link to Snowflake</a></li></ul><p>And of course, <strong>Python 3.X</strong> because the code won’t write itself.</p><p>Naturally if main component of our architecture are installed on your computer you can make something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEEowGiw-ncVs3tA5ne_0Q.png" /></figure><p>Let’s start by creating our project space :</p><pre>mkdir project_space &amp;&amp; cd project_space<br>astro dev init</pre><p>After this two commands, we can the astro base project structure create on your project_space/ with some repertory like :</p><ul><li><strong>include/</strong>: Directory for additional files or resources needed by Airflow pipelines (e.g., scripts or templates).</li><li><strong>dags/</strong>: Main directory to define DAGs (Airflow workflow logic written in Python).</li><li><strong>tests/</strong>: Directory for unit or functional tests related to DAGs and tasks.</li><li><strong>Dockerfile</strong>: File to configure the Docker image used to run Airflow locally.</li><li><strong>.env</strong>: File to store environment variables required for Airflow configuration.</li></ul><p>According to that, let’s start by our databases for data ingestion and migration, on our spaces snowflake by executing this query:</p><pre># DATABASE CREATION <br>CREATE DATABASE NYC;<br># SCHEMA CREATION<br>CREATE SCHEMA NYC.NYC_SCHEMA;</pre><p>We can see database and schema created on our snowflake space like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*wk3YhZGrCq1Avvqd3WrFCg.png" /></figure><h3><strong>STEP ONE : BRONZE</strong></h3><p>Now let’s manual launch our first step data pipeline on airbyte.</p><p>Airbyte is a very interesting for operation of ELT(Extract and Load Operation), according to this project we juste decide to free cloud version available for 14 days since the day of your first synchronization. In airbyte there is two principal component to choice : source (where data are ? ) and destination (where data will be save ?) after it’s possible to check policy about the data ingestion but in our case we juste decide to make an overwrite with a scheduled manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*_c-j17PAggafZdsdYRfoEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4fA07iH86A_uXqqTxtUeg.png" /></figure><p>According to google we just need to be authenticate, put the sheet link and it’s good, but for snowflake some information should enter like :</p><ul><li><strong>Host</strong>: The cloud host associated with your Snowflake instance connection.</li><li><strong>Role</strong>: Typically set to ACCOUNTADMIN.</li><li><strong>Warehouse</strong>: The virtual warehouse, e.g., COMPUTE_WH.</li><li><strong>Database</strong>: The name of your database.</li><li><strong>Schema</strong>: The schema associated with your database.</li><li><strong>Username and Password</strong>: Your Snowflake account credentials for authentication.</li></ul><p>After just launch the synchronisation with some parameters according to what kind od ingestion, you want and it’s good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-e65F6GTbfeI_AnHcuXokA.png" /></figure><p>Ok. The step of our pipeline is validated, congratulations if you are here. Data wihout transformation has been load on the bronze schema’s tables.</p><h4><em>STEP ONE * : DATA QUALITY PROCESS FOR BRONZE STEP</em></h4><p>At the step Bronze data has been load our snowflake data space without transformation but we need to make some data quality checks in order to avoid probably future problems. Pay attention :</p><ul><li>On the create a repertory <em>include/soda </em>for all needed for data quality checks with soda<em>, </em>create a file call <em>configuration.yml</em> which look like that:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*E8D7YH4AOMlT4CCY9PvEfg.png" /></figure><ul><li>Create on <em>include/soda/checks : bronze_checks.yml, silver_checks.yml, gold_chcecks.yml </em>files for all soda’s data quality checks of all data pipeline’s steps.</li><li>bronze_checks.yml look like that according to stack of test the head of data engineering define on the elaboration of this data pipeline:</li></ul><pre>#check over bronze&#39;s table<br>for each dataset T:<br>  datasets:<br>    - green<br>    - yellow<br>  checks:<br>    - schema:<br>        fail:<br>          when required column missing: [DATE, TAXI, EXTRA, MTA_TAX, VENDORID, RATECODEID, TIP_AMOUNT, AIRPORT_FEE, FARE_AMOUNT, DOLOCATIONID, PULOCATIONID, PAYMENT_TYPE, TOLLS_AMOUNT, TRIP_DISTANCE, PASSENGER_COUNT, <br>          STORE_AND_FWD_FLAG, CONGESTION_SURCHARGE, TPEP_PICKUP_DATETIME, IMPROVEMENT_SURCHARGE, TPEP_DROPOFF_DATETIME]<br>    - missing_percent(DATE) &lt; 10:<br>        name: Check rate of null values in DATE<br>    - missing_percent(TAXI) &lt; 10:<br>        name: Check rate of null values in TAXI<br>    - missing_percent(EXTRA) &lt; 10:<br>        name: Check rate of null values in EXTRA<br>    - missing_percent(MTA_TAX) &lt; 10:<br>        name: Check rate of null values in MTA_TAX<br>    - missing_percent(VENDORID) &lt; 10:<br>        name: Check rate of null values in VENDORID<br>    - missing_percent(RATECODEID) &lt; 10:<br>        name: Check rate of null values in RATECODEID<br>    - missing_percent(TIP_AMOUNT) &lt; 10:<br>        name: Check rate of null values in TIP_AMOUNT<br>    - missing_percent(AIRPORT_FEE) &lt; 10:<br>        name: Check rate of null values in AIRPORT_FEE<br>    - missing_percent(FARE_AMOUNT) &lt; 10:<br>        name: Check rate of null values in FARE_AMOUNT<br>    - missing_percent(DOLOCATIONID) &lt; 10:<br>        name: Check rate of null values in DOLOCATIONID<br>    - missing_percent(PULOCATIONID) &lt; 10:<br>        name: Check rate of null values in PULOCATIONID<br>    - missing_percent(PAYMENT_TYPE) &lt; 10:<br>        name: Check rate of null values in PAYMENT_TYPE<br>    - missing_percent(TOLLS_AMOUNT) &lt; 10:<br>        name: Check rate of null values in TOLLS_AMOUNT<br>    - missing_percent(TRIP_DISTANCE) &lt; 10:<br>        name: Check rate of null values in TRIP_DISTANCE<br>    - missing_percent(PASSENGER_COUNT) &lt; 10:<br>        name: Check rate of null values in PASSENGER_COUNT<br>    - missing_percent(STORE_AND_FWD_FLAG) &lt; 10:<br>        name: Check rate of null values in STORE_AND_FWD_FLAG<br>    - missing_percent(CONGESTION_SURCHARGE) &lt; 10:<br>        name: Check rate of null values in CONGESTION_SURCHARGE<br>    - missing_percent(TPEP_PICKUP_DATETIME) &lt; 10:<br>        name: Check rate of null values in TPEP_PICKUP_DATETIME<br>    - missing_percent(IMPROVEMENT_SURCHARGE) &lt; 10:<br>        name: Check rate of null values in IMPROVEMENT_SURCHARGE<br>    - missing_percent(TPEP_DROPOFF_DATETIME) &lt; 10:<br>        name: Check rate of null values in TPEP_DROPOFF_DATETIME</pre><ul><li>According to our pipeline we’ll going to make data quality test using external python3 depences for bypass conflict between astro depences and soda dependences<em>(it’s some good pratice to make on datapipeline creation). </em>Our python on a file call <em>check_function.py </em>look like:</li></ul><pre>def check(scan_name, file_checks_yml, configuration_file_yml, data_source, project_root=&#39;/usr/local/airflow/include&#39;):<br>    from soda.scan import Scan<br>    print(&quot;Running Soda Scan ...&quot;)<br>    config_file = f&quot;{project_root}/soda/{configuration_file_yml}&quot;<br>    checks_path = f&quot;{project_root}/soda/checks&quot;<br>    <br>    scan = Scan()<br>    scan.set_verbose()<br>    scan.add_configuration_yaml_file(config_file)<br>    scan.set_data_source_name(data_source)<br>    <br>    if &#39;.yml&#39; in file_checks_yml:<br>        scan.add_sodacl_yaml_file(f&quot;{checks_path}/{file_checks_yml}&quot;)<br>    else:<br>        scan.add_sodacl_yaml_files(checks_path)<br>    <br>    scan.set_scan_definition_name(scan_name)<br>    <br>    result = scan.execute()<br>    print(scan.get_logs_text())<br>    <br>    if result != 0:<br>        print(f&quot;Soda Scan failed with exit code: {result}&quot;)<br>        return {&quot;test&quot;: scan_name, &quot;status&quot;: &quot;failed&quot;, &quot;result&quot;: result}<br>    else:<br>        print(&quot;Soda Scan completed successfully&quot;)<br>        return {&quot;test&quot;: scan_name, &quot;status&quot;: &quot;success&quot;, &quot;result&quot;: result}</pre><p>Accoording to all this steps, this two files will be the base in all about making data quality checks over data ingest on our snowflake base.</p><h3><strong>STEP TWO : SILVER</strong></h3><p>Silver’s schema table will store data modeling architecture. In a datapipeline oriented for analytics needed, the step of data modeling it ‘s too important. Data store in OLTP architecture are not too optimized for Analytics needed. According to this OLAP architecture is the solution. There is a lot of OLAP architecture concepts, but in this case project we’ll use <strong>STAR MODELS</strong> and store it. The plan will be:</p><ul><li>First collect data ingest on bronze table(YELLOW &amp; GREEN)</li><li>Unify data in one big table with some columns</li><li>create dimensions with this new table create by unifying data from these main’s bronze table.</li><li>Construct our fact table, with all kind of KPI.</li></ul><p>Let’s check our data quality file checks call <em>silver_checks.yml</em></p><pre>#check over silver&#39;s table<br>checks for silver_dim_taxi:<br>  - missing_percent(TAXI_ID) = 0:<br>      name: Check rate of null values in dim_taxi<br>  - missing_percent(TAXI) = 0:<br>      name: Check rate of null values in dim_taxi<br><br>checks for silver_dim_passenger_count:<br>  - missing_percent(PASSENGER_COUNT_ID) = 0:<br>      name: Check rate of null values in dim_passenger_count<br>  - missing_percent(PASSENGER_COUNT) = 0:<br>      name: Check rate of null values in dim_passenger_count<br><br>checks for silver_dim_date:<br>  - missing_percent(DATE_ID) = 0:<br>      name: Check rate of null values in dim_date<br>  - missing_percent(FULL_DATE) = 0:<br>      name: Check rate of null values in dim_date<br>  - invalid_percent(MONTH) = 0:<br>      valid values : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]<br>      name: Ensure month values are valid in dim_date<br>  - invalid_percent(DAY) = 0:<br>      valid values :  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]<br>      name: Ensure day values are valid in dim_date<br><br>checks for silver_dim_payment_type:<br>  - missing_percent(PAYMENT_TYPE) = 0:<br>      name: Check rate of null values in dim_payment_type<br>  - missing_percent(NAME) = 0:<br>      name: Check rate of null values in dim_payment_type<br><br>checks for silver_dim_location:<br>  - missing_percent(LOCATIONID) = 0:<br>      name: Check rate of null values in dim_location<br>  - missing_percent(ZONENAME) = 0:<br>      name: Check rate of null values in dim_location<br>  - missing_percent(BOROUGH) = 0:<br>      name: Check rate of null values in dim_location<br>  - missing_percent(SERVICEZONE) = 0:<br>      name: Check rate of null values in dim_location<br>  - missing_percent(AFFLUENCERATING) = 0:<br>      name: Check rate of null values in dim_location</pre><h3>STEP THREE : GOLD</h3><p>Gold step is the last step before data vizualization. In this step data are ready to be use for analytics or machine learning needed. According to our dashboard we just decide to display from gold.</p><h3>DATAPIPELINE CODE</h3><p>On our repertory <em>include/ ; </em>We create python module for data transformation and loading during datapipeline execution using precisley the astro function decorator. they look like that:</p><pre>## silver tranformation code ...<br>from astro import sql as aql<br>from astro.sql.table import Table<br><br><br>&quot;&quot;&quot; All these functions we&#39;ll use astro.sql methods for create silver&#39;s table on our data storage space &quot;&quot;&quot;<br>&quot;&quot;&quot; SILVER&#39;S TABLES ARE  : silver_tableName &quot;&quot;&quot;<br><br>##################################### DIMENSIONS #####################################<br>@aql.transform()<br>def dim_passenger_count(yellow_table: Table, green_table :  Table):<br><br>    return &quot;&quot;&quot;<br>    SELECT <br>        ROW_NUMBER() OVER (ORDER BY passenger_count) AS passenger_count_id,<br>        passenger_count<br>    FROM (<br>        SELECT DISTINCT passenger_count<br>        FROM {{ yellow_table }}<br>        WHERE passenger_count IS NOT NULL<br>        UNION<br>        SELECT DISTINCT passenger_count<br>        FROM {{ green_table }}<br>        WHERE passenger_count IS NOT NULL<br>    ) AS combined_table<br>    ORDER BY passenger_count<br>    &quot;&quot;&quot;<br><br>@aql.transform()<br>def dim_taxi(yellow_table: Table, green_table :  Table):<br><br>    return &quot;&quot;&quot;<br>    SELECT <br>        ROW_NUMBER() OVER (ORDER BY taxi) AS taxi_id, <br>        taxi<br>    FROM (<br>        SELECT DISTINCT taxi<br>        FROM  {{ yellow_table }}<br>        UNION<br>        SELECT DISTINCT taxi<br>        FROM {{ green_table }}<br>    ) AS combined_table<br>    ORDER BY taxi<br>    &quot;&quot;&quot;<br><br>@aql.transform()<br>def dim_date(yellow_table: Table, green_table :  Table):<br>    return &quot;&quot;&quot;<br>    SELECT <br>        ROW_NUMBER() OVER (ORDER BY CAST(date AS DATE)) AS date_id,  -- Unique ID for each row<br>        CAST(date AS DATE) AS full_date,                            -- Convert the date column to DATE type<br>        EXTRACT(MONTH FROM CAST(date AS DATE)) AS month,            -- Extract the month from the date<br>        EXTRACT(DAY FROM CAST(date AS DATE)) AS day,                -- Extract the day of the month from the date<br>        CASE <br>            WHEN EXTRACT(DOW FROM CAST(date AS DATE)) = 0 THEN &#39;Sunday&#39;<br>            WHEN EXTRACT(DOW FROM CAST(date AS DATE)) = 1 THEN &#39;Monday&#39;<br>            WHEN EXTRACT(DOW FROM CAST(date AS DATE)) = 2 THEN &#39;Tuesday&#39;<br>            WHEN EXTRACT(DOW FROM CAST(date AS DATE)) = 3 THEN &#39;Wednesday&#39;<br>            WHEN EXTRACT(DOW FROM CAST(date AS DATE)) = 4 THEN &#39;Thursday&#39;<br>            WHEN EXTRACT(DOW FROM CAST(date AS DATE)) = 5 THEN &#39;Friday&#39;<br>            WHEN EXTRACT(DOW FROM CAST(date AS DATE)) = 6 THEN &#39;Saturday&#39;<br>        END AS dayofweek                                           -- Assign day names based on the day of the week<br>    FROM (<br>        SELECT DISTINCT date <br>        FROM (<br>            SELECT DISTINCT date<br>            FROM {{ yellow_table }}<br>            WHERE date IS NOT NULL<br>            UNION<br>            SELECT DISTINCT date<br>            FROM {{ green_table }}<br>            WHERE date IS NOT NULL<br>        ) AS date_table<br>    ) AS final_table<br>    WHERE date IS NOT NULL;<br>    &quot;&quot;&quot;<br><br>@aql.transform()<br>def dim_payment_type(yellow_table: Table, green_table :  Table):<br>    return &quot;&quot;&quot;<br>    SELECT DISTINCT payment_type,<br>        CASE <br>            WHEN payment_type = 1 THEN &#39;Credit card&#39;<br>            WHEN payment_type = 2 THEN &#39;Cash&#39;<br>            WHEN payment_type = 3 THEN &#39;No charge (free ride)&#39;<br>            WHEN payment_type = 4 THEN &#39;Dispute (payment issue)&#39;<br>            WHEN payment_type = 5 THEN &#39;Account&#39;<br>            WHEN payment_type = 6 THEN &#39;Prepaid&#39;<br>            WHEN payment_type = 0 THEN &#39;Unknown or Fraud&#39;<br>            ELSE &#39;Unknown&#39;<br>        END AS name<br>    FROM (<br>        SELECT DISTINCT payment_type FROM {{yellow_table}}<br>        UNION <br>        SELECT DISTINCT payment_type FROM {{green_table}}<br>    ) AS p<br>    WHERE payment_type IS NOT NULL<br>    ORDER BY payment_type;<br>    &quot;&quot;&quot;<br><br><br>@aql.transform()<br>def dim_location(yellow_table: Table, green_table :  Table):<br>    return &quot;&quot;&quot;<br>    WITH all_locations AS (<br>        SELECT DOLOCATIONID AS LocationID FROM {{yellow_table}} WHERE DOLOCATIONID IS NOT NULL<br>        UNION <br>        SELECT DOLOCATIONID FROM {{green_table}} WHERE DOLOCATIONID IS NOT NULL<br>        UNION <br>        SELECT PULOCATIONID FROM {{yellow_table}} WHERE PULOCATIONID IS NOT NULL<br>        UNION <br>        SELECT PULOCATIONID FROM {{green_table}} WHERE PULOCATIONID IS NOT NULL<br>    )<br>    <br>    SELECT DISTINCT LocationID,<br>        -- Ajouter des noms descriptifs pour les zones<br>        CASE <br>            WHEN LocationID BETWEEN 1 AND 100 THEN &#39;Downtown Manhattan&#39;<br>            WHEN LocationID BETWEEN 101 AND 200 THEN &#39;Brooklyn Residential&#39;<br>            WHEN LocationID BETWEEN 201 AND 250 THEN &#39;Queens Commercial&#39;<br>            WHEN LocationID BETWEEN 251 AND 300 THEN &#39;Bronx Suburban&#39;<br>            ELSE &#39;Other Zone&#39;<br>        END AS ZoneName,<br>        -- Identifier les arrondissements<br>        CASE <br>            WHEN LocationID BETWEEN 1 AND 100 THEN &#39;Manhattan&#39;<br>            WHEN LocationID BETWEEN 101 AND 200 THEN &#39;Brooklyn&#39;<br>            WHEN LocationID BETWEEN 201 AND 250 THEN &#39;Queens&#39;<br>            WHEN LocationID BETWEEN 251 AND 300 THEN &#39;Bronx&#39;<br>            ELSE &#39;Unknown&#39;<br>        END AS Borough,<br>        -- Définir les types de zones (ServiceZone)<br>        CASE <br>            WHEN LocationID IN (1, 50, 100) THEN &#39;Airport&#39;<br>            WHEN LocationID BETWEEN 1 AND 100 THEN &#39;Business&#39;<br>            WHEN LocationID BETWEEN 101 AND 200 THEN &#39;Residential&#39;<br>            WHEN LocationID BETWEEN 201 AND 250 THEN &#39;Commercial&#39;<br>            ELSE &#39;Other&#39;<br>        END AS ServiceZone,<br>        -- Ajouter une note d&#39;affluence basée sur des cas arbitraires<br>        CASE <br>            WHEN LocationID BETWEEN 1 AND 50 THEN &#39;High&#39;<br>            WHEN LocationID BETWEEN 51 AND 150 THEN &#39;Medium&#39;<br>            WHEN LocationID BETWEEN 151 AND 250 THEN &#39;Low&#39;<br>            ELSE &#39;Unknown&#39;<br>        END AS AffluenceRating<br>    FROM all_locations<br>    ORDER BY LocationID;<br>    &quot;&quot;&quot;<br><br>@aql.transform()<br>def fact_table_taxi_trips(yellow_table: Table, green_table: Table, dim_date: Table, dim_taxi: Table, <br>                    dim_location: Table, dim_payment_type: Table, dim_passenger_count: Table):<br>    return &quot;&quot;&quot;<br>    WITH combined_taxi_data AS (<br>        SELECT <br>            DATE, TAXI, <br>            REPLACE(FARE_AMOUNT, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS FARE_AMOUNT, <br>            REPLACE(EXTRA, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS EXTRA, <br>            REPLACE(MTA_TAX, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS MTA_TAX, <br>            REPLACE(TIP_AMOUNT, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS TIP_AMOUNT, <br>            REPLACE(TOLLS_AMOUNT, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS TOLLS_AMOUNT, <br>            REPLACE(CONGESTION_SURCHARGE, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS CONGESTION_SURCHARGE, <br>            REPLACE(IMPROVEMENT_SURCHARGE, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS IMPROVEMENT_SURCHARGE, <br>            REPLACE(AIRPORT_FEE, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS AIRPORT_FEE, <br>            VENDORID, RATECODEID, DOLOCATIONID, PULOCATIONID, PAYMENT_TYPE, <br>            TRIP_DISTANCE, PASSENGER_COUNT, STORE_AND_FWD_FLAG, <br>            TPEP_PICKUP_DATETIME, TPEP_DROPOFF_DATETIME<br>        FROM {{ yellow_table }}<br>        UNION ALL<br>        SELECT <br>            DATE, TAXI, <br>            REPLACE(FARE_AMOUNT, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS FARE_AMOUNT,<br>            REPLACE(EXTRA, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS EXTRA,<br>            REPLACE(MTA_TAX, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS MTA_TAX,<br>            REPLACE(TIP_AMOUNT, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS TIP_AMOUNT,<br>            REPLACE(TOLLS_AMOUNT, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS TOLLS_AMOUNT,<br>            REPLACE(CONGESTION_SURCHARGE, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS CONGESTION_SURCHARGE,<br>            REPLACE(IMPROVEMENT_SURCHARGE, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS IMPROVEMENT_SURCHARGE,<br>            REPLACE(AIRPORT_FEE, &#39;,&#39;, &#39;.&#39;)::NUMERIC AS AIRPORT_FEE,<br>            VENDORID, RATECODEID, DOLOCATIONID, PULOCATIONID, PAYMENT_TYPE, <br>            TRIP_DISTANCE, PASSENGER_COUNT, STORE_AND_FWD_FLAG, <br>            TPEP_PICKUP_DATETIME, TPEP_DROPOFF_DATETIME<br>        FROM {{ green_table }}<br>    )<br>    SELECT <br>        c.VENDORID AS vendor_id,<br>        c.RATECODEID AS ratecode_id,<br>        c.STORE_AND_FWD_FLAG,<br>        <br>        -- Clé étrangère vers la dimension date<br>        d.date_id, <br><br>        -- Clé étrangère vers la dimension taxi<br>        t.taxi_id, <br><br>        -- Clé étrangère vers la dimension location (pickup et dropoff)<br>        l1.locationid AS pickup_location_id,<br>        l2.locationid AS dropoff_location_id,<br><br>        -- Clé étrangère vers la dimension payment_type<br>        p.payment_type,<br><br>        -- Clé étrangère vers la dimension passenger_count<br>        pc.passenger_count_id,<br><br>        -- Mesures Fact Table<br>        c.TRIP_DISTANCE,<br>        c.TPEP_PICKUP_DATETIME AS pickup_datetime,<br>        c.TPEP_DROPOFF_DATETIME AS dropoff_datetime,<br>        c.FARE_AMOUNT,<br>        c.EXTRA,<br>        c.MTA_TAX,<br>        c.TIP_AMOUNT,<br>        c.TOLLS_AMOUNT,<br>        c.CONGESTION_SURCHARGE,<br>        c.IMPROVEMENT_SURCHARGE,<br>        c.AIRPORT_FEE,<br>        (c.FARE_AMOUNT + c.EXTRA + c.MTA_TAX + c.TIP_AMOUNT + c.TOLLS_AMOUNT + c.CONGESTION_SURCHARGE + c.IMPROVEMENT_SURCHARGE + c.AIRPORT_FEE) AS total_amount<br>    FROM combined_taxi_data AS c<br>    LEFT JOIN {{ dim_date }} d ON c.DATE = d.full_date<br>    LEFT JOIN {{ dim_taxi }} t ON c.TAXI = t.taxi<br>    LEFT JOIN {{ dim_location }} l1 ON c.PULOCATIONID = l1.locationid<br>    LEFT JOIN {{ dim_location }} l2 ON c.DOLOCATIONID = l2.locationid<br>    LEFT JOIN {{ dim_payment_type }} p ON c.PAYMENT_TYPE = p.payment_type<br>    LEFT JOIN {{ dim_passenger_count }} pc ON c.PASSENGER_COUNT = pc.passenger_count<br>    WHERE c.VENDORID IS NOT NULL<br>    AND c.RATECODEID IS NOT NULL<br>    AND c.STORE_AND_FWD_FLAG IS NOT NULL<br>    AND c.TRIP_DISTANCE IS NOT NULL<br>    AND c.TPEP_PICKUP_DATETIME IS NOT NULL<br>    AND c.TPEP_DROPOFF_DATETIME IS NOT NULL<br>    AND c.FARE_AMOUNT IS NOT NULL<br>    AND c.EXTRA IS NOT NULL<br>    AND c.MTA_TAX IS NOT NULL<br>    AND c.TIP_AMOUNT IS NOT NULL<br>    AND c.TOLLS_AMOUNT IS NOT NULL<br>    AND c.CONGESTION_SURCHARGE IS NOT NULL<br>    AND c.IMPROVEMENT_SURCHARGE IS NOT NULL<br>    AND c.AIRPORT_FEE IS NOT NULL<br>    AND d.date_id IS NOT NULL<br>    AND t.taxi_id IS NOT NULL<br>    AND l1.locationid IS NOT NULL<br>    AND l2.locationid IS NOT NULL<br>    AND p.payment_type IS NOT NULL<br>    AND pc.passenger_count_id IS NOT NULL;<br>    &quot;&quot;&quot;</pre><pre>##gold transformation code ...<br><br>from astro import sql as aql<br>from astro.sql.table import Table<br><br><br>&quot;&quot;&quot; GOLD&#39;S TABLES ARE  : silver_tableName &quot;&quot;&quot;<br><br>@aql.transform()<br>def gold_general_kpi(fact_table: Table, dim_taxi: Table, dim_date: Table):<br>    return &quot;&quot;&quot;<br>    SELECT dim_date.full_date,  dim_taxi.taxi, ft.fare_amount, ft.total_amount, ft.trip_distance, ft.congestion_surcharge, ft.improvement_surcharge<br>    FROM {{fact_table}} as ft, {{dim_taxi}} as dim_taxi, {{dim_date}} as dim_date<br>    WHERE ft.date_id = dim_date.date_id and ft.taxi_id = dim_taxi.taxi_id<br>    &quot;&quot;&quot;<br><br><br>@aql.transform()<br>def gold_map_analysis(fact_table: Table, dim_taxi: Table, dim_date: Table, dim_location: Table):<br>    return &quot;&quot;&quot;<br>    SELECT dt.full_date,  dim_taxi.taxi, ft.trip_distance, ft.pickup_location_id, ft.dropoff_location_id, dl.zonename, dl.borough, dl.affluencerating<br>    FROM {{fact_table}} as ft , {{dim_date}} as dt, {{dim_location}} as dl, {{dim_taxi}} as dim_taxi<br>    WHERE ft.date_id = dt.date_id and ft.pickup_location_id = dl.locationid<br>    &quot;&quot;&quot;</pre><p>Let’s code our data pipeline flow on the repertory <em>dag/</em></p><pre>from airflow.decorators import dag, task<br>from airflow.operators.empty import EmptyOperator<br>from airflow.operators.python import BranchPythonOperator<br>from astro import sql as aql<br>from astro.sql.table import Table<br>from include.transformation.silver_transformation_function import (dim_passenger_count, dim_taxi, dim_date, <br>                                                                   dim_payment_type, dim_location)<br>from include.transformation.silver_transformation_function import fact_table_taxi_trips<br><br>from include.transformation.gold_transformation_functions import gold_general_kpi, gold_map_analysis<br>from datetime import datetime<br><br><br>@dag(<br>    start_date=datetime(2025, 1, 21),<br>    schedule_interval=None,<br>    catchup=False,<br>    tags=[&quot;data_pipeline&quot;],<br>)<br>def pipeline():<br>    <br>    # Task for verification over bronze layer of our data pipeline<br>    @task.external_python(python=&#39;/usr/local/airflow/soda_venv/bin/python3.11&#39;)<br>    def check_over_bronze(scan_name=&#39;check_bronze&#39;):<br>        from include.soda.check_function import check<br><br>        test = check(<br>            scan_name,<br>            file_checks_yml=&#39;bronze_checks.yml&#39;,<br>            configuration_file_yml=&#39;configuration.yml&#39;,<br>            data_source=&#39;snowflake&#39;,<br>            project_root=&#39;/usr/local/airflow/include&#39;,<br>        )<br>        return test<br><br>    # Routing logic for bronze check result<br>    def routing_bronze_logic(**kwargs):<br>        check_result = kwargs[&#39;ti&#39;].xcom_pull(task_ids=&#39;check_over_bronze&#39;)<br>        if check_result.get(&quot;status&quot;) == &quot;success&quot;:<br>            return &quot;continue_silver&quot;<br>        else:<br>            return &quot;failed_bronze&quot;<br><br>    routing_bronze = BranchPythonOperator(<br>        task_id=&quot;routing_bronze&quot;,<br>        python_callable=routing_bronze_logic,<br>        provide_context=True,  # Enable context passing<br>    )<br><br>    # Continue to silver task ##################################################################<br>    @task<br>    def continue_silver():<br>        print(&quot;Continue to silver --&gt; let&#39;s start operation of transformation with astro sql.&quot;)<br><br>    # Task for failure case (empty operator for alerting)<br>    failed_bronze = EmptyOperator(task_id=&quot;failed_bronze&quot;)<br><br>    # Silver task for passenger count<br>    table_passenger_count = dim_passenger_count(<br>        yellow_table= Table( name  =  &quot;YELLOW&quot;, conn_id =  &quot;snowflake&quot;),<br>        green_table= Table( name  =  &quot;GREEN&quot;, conn_id =  &quot;snowflake&quot;),<br>        output_table = Table( name  =  &quot;SILVER_DIM_PASSENGER_COUNT&quot;, conn_id =  &quot;snowflake&quot;)<br>    )<br><br>    table_dim_taxi = dim_taxi(<br>        yellow_table= Table( name  =  &quot;YELLOW&quot;, conn_id =  &quot;snowflake&quot;),<br>        green_table = Table( name  =  &quot;GREEN&quot;, conn_id =  &quot;snowflake&quot;),<br>        output_table = Table( name  =  &quot;SILVER_DIM_TAXI&quot;, conn_id =  &quot;snowflake&quot;)<br>    )<br><br>    table_dim_date =  dim_date(<br>        yellow_table= Table( name  =  &quot;YELLOW&quot;, conn_id =  &quot;snowflake&quot;),<br>        green_table = Table( name  =  &quot;GREEN&quot;, conn_id =  &quot;snowflake&quot;),<br>        output_table=Table(name = &#39;SILVER_DIM_DATE&#39;, conn_id = &quot;snowflake&quot;),<br>    )<br><br>    table_dim_payment_type =  dim_payment_type(<br>        yellow_table= Table( name  =  &quot;YELLOW&quot;, conn_id =  &quot;snowflake&quot;),<br>        green_table = Table( name  =  &quot;GREEN&quot;, conn_id =  &quot;snowflake&quot;),<br>        output_table=Table(name = &#39;SILVER_DIM_PAYMENT_TYPE&#39;, conn_id = &quot;snowflake&quot;),<br>    )<br><br>    table_dim_location =  dim_location(<br>        yellow_table= Table( name  =  &quot;YELLOW&quot;, conn_id =  &quot;snowflake&quot;),<br>        green_table = Table( name  =  &quot;GREEN&quot;, conn_id =  &quot;snowflake&quot;),<br>        output_table=Table(name = &#39;SILVER_DIM_LOCATION&#39;, conn_id = &quot;snowflake&quot;),<br>    )<br><br><br>    table_facttable = fact_table_taxi_trips(<br>        yellow_table = Table( name  =  &quot;YELLOW&quot;, conn_id =  &quot;snowflake&quot;),<br>        green_table = Table( name  =  &quot;GREEN&quot;, conn_id =  &quot;snowflake&quot;),<br>        dim_date = Table(name = &#39;SILVER_DIM_DATE&#39;, conn_id = &quot;snowflake&quot;),<br>        dim_taxi = Table( name  =  &quot;SILVER_DIM_TAXI&quot;, conn_id =  &quot;snowflake&quot;),<br>        dim_location = Table(name = &#39;SILVER_DIM_LOCATION&#39;, conn_id = &quot;snowflake&quot;),<br>        dim_passenger_count = Table( name  =  &quot;SILVER_DIM_PASSENGER_COUNT&quot;, conn_id =  &quot;snowflake&quot;),<br>        dim_payment_type = Table(name = &#39;SILVER_DIM_PAYMENT_TYPE&#39;, conn_id = &quot;snowflake&quot;),<br>        output_table=Table(name = &#39;SILVER_FACT_TABLE&#39;, conn_id = &quot;snowflake&quot;),<br>    )<br><br>    # TEST OVER SILVERS TABLE #########################<br>    # Task for verification over bronze layer of our data pipeline<br>    @task.external_python(python=&#39;/usr/local/airflow/soda_venv/bin/python3.11&#39;)<br>    def check_over_silver(scan_name = &#39;check_silver&#39;):<br>        from include.soda.check_function import check<br>        test = check(<br>            scan_name,<br>            file_checks_yml=&#39;silver_checks.yml&#39;,<br>            configuration_file_yml=&#39;configuration.yml&#39;,<br>            data_source=&#39;snowflake&#39;,<br>            project_root=&#39;/usr/local/airflow/include&#39;,<br>        )<br>        return test<br>    <br>    # Routing logic for bronze check result<br>    def routing_silver_logic(**kwargs):<br>        check_result = kwargs[&#39;ti&#39;].xcom_pull(task_ids=&#39;check_over_silver&#39;)<br>        if check_result.get(&quot;status&quot;) == &quot;success&quot;:<br>            return &quot;continue_gold&quot;<br>        else:<br>            return &quot;failed_silver&quot;<br>        <br>    routing_silver = BranchPythonOperator(<br>        task_id=&quot;routing_silver&quot;,<br>        python_callable=routing_silver_logic,<br>        provide_context=True,  # Enable context passing<br>    )<br>        <br>    @task<br>    def continue_gold():<br>        print(&quot;Continue to silver --&gt; let&#39;s start operation of transformation with astro sql.&quot;)<br><br>    # Task for failure case (empty operator for alerting)<br>    failed_silver = EmptyOperator(task_id=&quot;failed_silver&quot;)<br><br>    # Continue to gold task ##################################################################<br>    ## task over gold table<br>    gold_general_kpi_task = gold_general_kpi(<br>        fact_table = Table(name = &#39;SILVER_FACT_TABLE&#39;, conn_id = &#39;snowflake&#39;),<br>        dim_taxi = Table(name = &#39;SILVER_DIM_TAXI&#39;, conn_id = &#39;snowflake&#39;),<br>        dim_date = Table(name = &#39;SILVER_DIM_DATE&#39;, conn_id = &#39;snowflake&#39;),<br>        output_table = Table(name = &#39;GOLD_GENERAL_KPI&#39;, conn_id = &#39;snowflake&#39;)<br>    )<br><br>        ## task over gold table<br>    map_analysis_task = gold_map_analysis(<br>        fact_table = Table(name = &#39;SILVER_FACT_TABLE&#39;, conn_id = &#39;snowflake&#39;),<br>        dim_taxi = Table(name = &#39;SILVER_DIM_TAXI&#39;, conn_id = &#39;snowflake&#39;),<br>        dim_date = Table(name = &#39;SILVER_DIM_DATE&#39;, conn_id = &#39;snowflake&#39;),<br>        dim_location = Table(name = &#39;SILVER_DIM_LOCATION&#39;, conn_id = &#39;snowflake&#39;),<br>        output_table = Table(name = &#39;GOLD_MAP_ANALYSIS&#39;, conn_id = &#39;snowflake&#39;)<br>    )<br><br><br>    ################################ INSTANCIATION SPACE ##################################<br>    # Define the first part dependencies of our pipeline<br>    check_result = check_over_bronze()<br>    check_result_silver =  check_over_silver()<br>    <br>    # Routing logic follows check result<br>    routing_bronze.set_upstream(check_result)<br>    routing_silver.set_upstream(check_result_silver)<br>    <br>    # Continue to silver or handle failure case<br>    continue_silver_task = continue_silver()<br>    continue_gold_task =  continue_gold()<br>    routing_bronze &gt;&gt; [continue_silver_task, failed_bronze]<br>    routing_silver &gt;&gt; [continue_gold_task, failed_silver]<br>    <br>    # After silver step, move to table passenger count task<br>    continue_silver_task &gt;&gt; [table_passenger_count, table_dim_payment_type, <br>                             table_dim_taxi, table_dim_date, table_dim_location] &gt;&gt; table_facttable<br>    <br>    table_facttable &gt;&gt; check_result_silver<br><br>    continue_gold_task &gt;&gt; [gold_general_kpi_task, map_analysis_task]<br><br><br>pipeline()</pre><p>Here is on airflow the visuel on our process of data engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ci3LlNuWI9wkhJYherwz0w.png" /></figure><p>Soda cloud instance provides a UI to monitor your data quality tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e83oTY8D_wHIfXYuDmORHw.png" /></figure><h3>DATA VISUALISATION</h3><p>Here is the result of this data processing, ready to be visualize by business analyst:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueA2QFuPn7Vxa7GCgRKVtg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iv0Qlnm_iVo83tjXppFMXw.png" /></figure><h3>Conclusion</h3><p>In conclusion don’t forget that, a data pipeline without a robust data quality process is merely a waste of time, energy, and computing resources. The fundamental requirement for any data processing workflow is simply accurate and reliable data.</p><p>I acknowledge that some aspects of my article may be somewhat unclear. Feel free to contact me on mail : <em>nisaacemmanuel@gmail.com</em>, explore my project on GitHub for a deeper understanding of its implementation.</p><p>github project link: <a href="https://github.com/IS2aC/end-to-end-data-quality-soda-astronomer.git">https://github.com/IS2aC/end-to-end-data-quality-soda-astronomer.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca7a70f15300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End to End Streaming Datapipeline with APACHE AIRFLOW, KAFKA, SPARK, CASSANDRA from data source to…]]></title>
            <link>https://medium.com/@nisaacemmanuel/end-to-end-streaming-datapipeline-with-apache-airflow-kafka-spark-cassandra-from-data-source-to-ac61a313fecf?source=rss-5fdee2b4e407------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac61a313fecf</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[datapipelinemonitoring]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cassandra]]></category>
            <category><![CDATA[dataviz]]></category>
            <dc:creator><![CDATA[is2ac]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 13:48:34 GMT</pubDate>
            <atom:updated>2024-11-02T10:53:41.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>End to End Streaming Datapipeline with APACHE AIRFLOW, KAFKA, SPARK, CASSANDRA from data source to application.</h3><p><em>“In God we trust, but for everything else, we demand data.” </em>This famous quote by <strong>W. Edwards Deming</strong> highlights how data plays a central role in everyday decision-making. With the rise of <strong>Big Data</strong>, characterized by the <strong>3Vs or 5Vs</strong> (depending on the school of thought), this fact-based approach has become even more prominent. Data, generated at high velocity from various sources such as <strong>IoT sensors</strong> and other connected devices, has transformed the analytics landscape. To efficiently handle these continuous streams of real-time data, tools that can <strong>scale effectively</strong> are essential for processing, analyzing, and acting quickly. In this project, we will simulate, using open-source solutions, a <strong>resilient, scalable, and robust pipeline</strong> to meet the needs of real-time analytics and enable informed decision-making that aligns with modern-day requirements.</p><h3>I- Overview of the global architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*lWUT2C1SbEUx8XF5vgujSQ.gif" /></figure><p>Our architecture is primarily based on Docker containers managed by Docker Compose. The components of this architecture include:</p><ul><li><strong>Airflow</strong>: for orchestrating data collection scripts from the Random User API, which is the main source of our solution.</li><li><strong>PostgreSQL</strong>: for storing metadata and logs associated with Airflow’s DAGs, tasks, and other components.</li><li><strong>Zookeeper</strong>: for managing configurations and coordinating distributed services.</li><li><strong>Kafka</strong>: for streaming operations within our data pipeline.</li><li><strong>Control Center</strong>: for monitoring and tracking real-time ingestions.</li><li><strong>Schema Registry</strong>: for validating data before it is emitted to producers.</li><li><strong>Spark Cluster</strong>: for processing information and final formatting of data using Spark Streaming, which is essential for “gold” formatting of data in the pipeline.</li><li><strong>Cassandra</strong>: a column-oriented database system optimized for aggregation operations.</li></ul><h3>II- Advantages of the architecture</h3><ul><li><strong>Scalability:</strong> With Kafka, Cassandra, and Spark, this architecture can easily scale to handle increasing volumes of data.</li><li><strong>Real-Time Processing:</strong> Using Kafka and Socket.IO, the system can stream data in real time to client applications.</li><li><strong>Reliability:</strong> Airflow manages workflows, and Kafka ensures reliable message delivery, which enhances resilience.</li><li><strong>Flexibility:</strong> Docker containers make it easy to add or replace services without impacting the entire system.</li></ul><h3>III- Tutorial</h3><p><strong>Step 0: </strong>Ensure that you have the following installed: Docker, Docker Compose, Python, Java, and PySpark.</p><p><strong>Step 1: </strong>Create directories name <strong>./dags/</strong>, <strong>./script/</strong>, <strong>./logs/ </strong>on the main directory of your project.</p><p><strong>Step 2: </strong>Create a file entrypoint.sh on ./script/</p><pre>#!/bin/bash<br>set -e<br><br>if [ -e &quot;/opt/airflow/requirements.txt&quot; ]; then<br>  $(command python) pip install --upgrade pip<br>  $(command -v pip) install --user -r requirements.txt<br>fi<br><br>if [ ! -f &quot;/opt/airflow/airflow.db&quot; ]; then<br>  airflow db init &amp;&amp; \<br>  airflow users create \<br>    --username admin \<br>    --firstname admin \<br>    --lastname admin \<br>    --role Admin \<br>    --email admin@example.com \<br>    --password admin<br>fi<br><br>$(command -v airflow) db upgrade<br><br>exec airflow webserver</pre><p><strong>Step 3</strong>: Copy and paste the following YAML configuration into a file named docker-compose.yml in your project&#39;s main directory.</p><pre>version: &#39;3&#39;<br>services:<br>  zookeeper:<br>    image: confluentinc/cp-zookeeper:7.4.0<br>    hostname: zookeeper<br>    container_name: zookeeper<br>    ports:<br>      - &quot;2181:2181&quot;<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>    healthcheck:<br>      test: [&#39;CMD&#39;, &#39;bash&#39;, &#39;-c&#39;, &quot;echo &#39;ruok&#39; | nc localhost 2181&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 5<br>    networks:<br>      - confluent<br><br>  broker:<br>    image: confluentinc/cp-server:7.4.0<br>    hostname: broker<br>    container_name: broker<br>    depends_on:<br>      zookeeper:<br>        condition: service_healthy<br>    ports:<br>      - &quot;9092:9092&quot;<br>      - &quot;9101:9101&quot;<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: &#39;zookeeper:2181&#39;<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0<br>      KAFKA_JMX_PORT: 9101<br>      KAFKA_JMX_HOSTNAME: localhost<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;bash&quot;, &quot;-c&quot;, &quot;nc -z localhost 9092&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 5<br>    networks:<br>      - confluent<br><br>  schema-registry:<br>    image: confluentinc/cp-schema-registry:7.4.0<br>    hostname: schema-registry<br>    container_name: schema-registry<br>    depends_on:<br>      broker:<br>        condition: service_healthy<br>    ports:<br>      - &quot;8081:8081&quot;<br>    environment:<br>      SCHEMA_REGISTRY_HOST_NAME: schema-registry<br>      SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: &#39;broker:29092&#39;<br>      SCHEMA_REGISTRY_LISTENERS: http://0.0.0.0:8081<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;-f&quot;, &quot;http://localhost:8081/&quot;]<br>      interval: 30s<br>      timeout: 10s<br>      retries: 5<br>    networks:<br>      - confluent<br><br>  control-center:<br>    image: confluentinc/cp-enterprise-control-center:7.4.0<br>    hostname: control-center<br>    container_name: control-center<br>    depends_on:<br>      broker:<br>        condition: service_healthy<br>      schema-registry:<br>        condition: service_healthy<br>    ports:<br>      - &quot;9021:9021&quot;<br>    environment:<br>      CONTROL_CENTER_BOOTSTRAP_SERVERS: &#39;broker:29092&#39;<br>      CONTROL_CENTER_SCHEMA_REGISTRY_URL: &quot;http://schema-registry:8081&quot;<br>      CONTROL_CENTER_REPLICATION_FACTOR: 1<br>      CONTROL_CENTER_INTERNAL_TOPICS_PARTITIONS: 1<br>      CONTROL_CENTER_MONITORING_INTERCEPTOR_TOPIC_PARTITIONS: 1<br>      CONFLUENT_METRICS_TOPIC_REPLICATION: 1<br>      CONFLUENT_METRICS_ENABLE: &#39;false&#39;<br>      PORT: 9021<br>    networks:<br>      - confluent<br><br><br>  webserver:<br>    image: apache/airflow:2.6.0-python3.10<br>    command: webserver<br>    entrypoint: [&#39;bash&#39;,&#39;/opt/airflow/script/entrypoint.sh&#39;]<br>    depends_on:<br>      - postgres<br>    environment:<br>      - LOAD_EX=n<br>      - EXECUTOR=Sequential<br>      - AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@postgres:5432/airflow<br>      - AIRFLOW_WEBSERVER_SECRET_KEY=this_is_a_very_secured_key<br>    logging:<br>      options:<br>        max-size: 10m<br>        max-file: &quot;3&quot;<br>    volumes:<br>      - ./dags:/opt/airflow/dags<br>      - ./script/entrypoint.sh:/opt/airflow/script/entrypoint.sh<br>      - ./requirements.txt:/opt/airflow/requirements.txt<br>    ports:<br>      - &quot;8080:8080&quot;<br>    healthcheck:<br>      test: [&#39;CMD-SHELL&#39;, &quot;[ -f /opt/airflow/airflow-webserver.pid ]&quot;]<br>      interval: 30s<br>      timeout: 30s<br>      retries: 3<br>    networks:<br>      - confluent<br><br>  scheduler:<br>    image: apache/airflow:2.6.0-python3.10<br>    depends_on:<br>      webserver:<br>        condition: service_healthy<br>    volumes:<br>      - ./dags:/opt/airflow/dags<br>      - ./script/entrypoint.sh:/opt/airflow/script/entrypoint.sh<br>      - ./requirements.txt:/opt/airflow/requirements.txt<br>    environment:<br>      - LOAD_EX=n<br>      - EXECUTOR=Sequential<br>      - AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@postgres:5432/airflow<br>      - AIRFLOW_WEBSERVER_SECRET_KEY=this_is_a_very_secured_key<br>    command: bash -c &quot;pip install -r ./requirements.txt &amp;&amp; airflow db upgrade &amp;&amp; airflow scheduler&quot;<br>    networks:<br>      - confluent<br><br>  postgres:<br>    image: postgres:14.0<br>    environment:<br>      - POSTGRES_USER=airflow<br>      - POSTGRES_PASSWORD=airflow<br>      - POSTGRES_DB=airflow<br>    logging:<br>      options:<br>        max-size: 10m<br>        max-file: &quot;3&quot;<br>    networks:<br>      - confluent<br><br>  spark-master:<br>    image: bitnami/spark:latest<br>    command: bin/spark-class org.apache.spark.deploy.master.Master<br>    ports:<br>      - &quot;9090:8080&quot;<br>      - &quot;7077:7077&quot;<br>    networks:<br>      - confluent<br>  spark-worker:<br>    image: bitnami/spark:latest<br>    command: bin/spark-class org.apache.spark.deploy.worker.Worker spark://spark-master:7077<br>    depends_on:<br>      - spark-master<br>    environment:<br>      SPARK_MODE: worker<br>      SPARK_WORKER_CORES: 2<br>      SPARK_WORKER_MEMORY: 1g<br>      SPARK_MASTER_URL: spark://spark-master:7077<br>    networks:<br>      - confluent<br><br>  cassandra_db:<br>    image: cassandra:latest<br>    container_name: cassandra<br>    hostname: cassandra<br>    ports:<br>      - &quot;9042:9042&quot;<br>    environment:<br>      - MAX_HEAP_SIZE=512M<br>      - HEAP_NEWSIZE=100M<br>      - CASSANDRA_USERNAME=cassandra<br>      - CASSANDRA_PASSWORD=cassandra<br>    networks:<br>      - confluent<br><br>networks:<br>  confluent:<br>    driver: bridge</pre><p><strong>Step 4: </strong>Launch this command on the main repertory of your project to launch or pull docker images associated at all services describe on our docker-compose.yml file</p><pre>docker compose up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*cPYXX7O73Di8wssWqQCi9g.png" /></figure><p>On the dags repertory let’s code our python script for data collection from random-user-api. create a file kafka_stream.py with this code :</p><pre>import uuid<br>from datetime import datetime<br>import time<br>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br><br># define default args for our airflow dag<br>default_args = {<br>    &quot;owner&quot; : &#39;is2ac&#39;,<br>    &#39;start_date&#39; : datetime(2024, 10, 24, 9, 00)<br>}<br><br>def get_data() -&gt; dict:<br>    &quot;&quot;&quot;<br>    data collection function<br><br>    Returns:<br>        dict: random user result as dictionnary instance<br>    &quot;&quot;&quot;<br><br>    import requests<br><br>    res =  requests.get(&#39;https://randomuser.me/api/&#39;)<br>    res = res.json()[&#39;results&#39;][0]<br>    return res<br><br>def format_data(res:dict) -&gt; dict :<br>    &quot;&quot;&quot;<br>    data transform function, <br>    select important informations and dele useless informations.<br><br>    Args:<br>        res (_dict_): random user response of the api request<br><br>    Returns:<br>        dict: random user with important informations extracted.<br>    &quot;&quot;&quot;<br>    <br>    data = {}<br>    location = res[&#39;location&#39;]<br>    data[&#39;id&#39;] = str(uuid.uuid4())<br>    data[&#39;first_name&#39;] = res[&#39;name&#39;][&#39;first&#39;]<br>    data[&#39;last_name&#39;] = res[&#39;name&#39;][&#39;last&#39;]<br>    data[&#39;gender&#39;] = res[&#39;gender&#39;]<br>    data[&#39;address&#39;] = f&quot;{str(location[&#39;street&#39;][&#39;number&#39;])} {location[&#39;street&#39;][&#39;name&#39;]}, &quot; \<br>                      f&quot;{location[&#39;city&#39;]}, {location[&#39;state&#39;]}, {location[&#39;country&#39;]}&quot;<br>    data[&#39;post_code&#39;] = location[&#39;postcode&#39;]<br>    data[&#39;email&#39;] = res[&#39;email&#39;]<br>    data[&#39;username&#39;] = res[&#39;login&#39;][&#39;username&#39;]<br>    data[&#39;dob&#39;] = res[&#39;dob&#39;][&#39;date&#39;]<br>    data[&#39;registered_date&#39;] = res[&#39;registered&#39;][&#39;date&#39;]<br>    data[&#39;phone&#39;] = res[&#39;phone&#39;]<br>    data[&#39;picture&#39;] = res[&#39;picture&#39;][&#39;medium&#39;]<br><br>    return data<br><br>def stream_data() -&gt; None:<br>    &quot;&quot;&quot;<br>    Streaming flow&#39;s function pushing data <br>    to kafka broker associated to the topic defined : users_created<br><br>    &quot;&quot;&quot;<br><br>    import json<br>    from kafka import KafkaProducer<br>    import logging<br>    res =  get_data()<br>    res =  format_data(res)<br><br>    # feel free to play with parameters <br>    time_limit =  600<br><br><br>    producer =  KafkaProducer(bootstrap_servers =  [&#39;broker:29092&#39;], max_block_ms = 5000)<br>    topic_name =  &#39;users_created&#39;<br>    curr_time = time.time()<br>    while True:<br>        if time.time() &gt; curr_time + time_limit : #10 minutes<br>            break<br>        try:<br>            res = get_data()<br>            res = format_data(res)<br>            producer.send(topic_name, json.dumps(res).encode(&#39;utf-8&#39;))<br>        except Exception as e:<br>            logging.error(f&#39;An error occurred : {e}&#39;)<br>            continue<br><br><br>#dag<br>with DAG(&#39;user_automation&#39;,<br>         default_args=default_args,<br>         schedule_interval=&#39;@daily&#39;, <br>         catchup=False) as dag:<br><br>    streaming_task = PythonOperator(<br>        task_id=&#39;stream_data_from_api&#39;,<br>        python_callable=stream_data<br>    )<br><br>    # only one task which first part of our data pipeline.<br>    streaming_task</pre><p>Normaly on <em>localhost:8080 </em>you should look the dag create on airflow UI.</p><p>Step : Let’s test a manual excution with trigger dag. After that you can obserse something like that correct execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AcCTnxcKaGk8B-B4jX-HA.png" /></figure><p>Step : Check if data has been push to kafka broker on Kafka control center UI on url <em>localhost:9021. </em>And on it you can see something like that :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cY__XLS9wOTzNiaUaRx7sQ.png" /></figure><p>According to this visual, we can say first all the data ingestion to kafka broker has been done correctly. the next will be to use a tool to listen over kafka to collect data produce on it. The best tool for that on Big Data universe is SPARK.</p><p>Step : Code script for data streaming collection to kafka producer and data ingestion in our cassandra database.</p><pre>import logging<br><br>from cassandra.cluster import Cluster<br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import from_json, col<br>from pyspark.sql.types import StructType, StructField, StringType<br><br><br>def create_keyspace(session) -&gt; None:<br>    &quot;&quot;&quot;<br>    Create keyspace on cassandra database. <br><br>    #? Don&#39;t forget that keyspace can be defined like database on OLTP database like (postgres, mysql, etc...)<br>    <br>    &quot;&quot;&quot;<br>    session.execute(&quot;&quot;&quot;<br>        CREATE KEYSPACE IF NOT EXISTS spark_streams<br>        WITH replication = {&#39;class&#39;: &#39;SimpleStrategy&#39;, &#39;replication_factor&#39;: &#39;1&#39;};<br>    &quot;&quot;&quot;)<br><br>    print(&quot;Keyspace created successfully!&quot;)<br><br><br>def create_table(session) -&gt; None:<br>    &quot;&quot;&quot;<br>    Create table in cassandra database. <br><br>    &quot;&quot;&quot;<br>    session.execute(&quot;&quot;&quot;<br>    CREATE TABLE IF NOT EXISTS spark_streams.created_users (<br>        id UUID PRIMARY KEY,<br>        first_name TEXT,<br>        last_name TEXT,<br>        gender TEXT,<br>        address TEXT,<br>        post_code TEXT,<br>        email TEXT,<br>        username TEXT,<br>        registered_date TEXT,<br>        phone TEXT,<br>        picture TEXT);<br>    &quot;&quot;&quot;)<br><br>    print(&quot;Table created successfully!&quot;)<br><br><br>def insert_data(session, **kwargs) -&gt; None:<br>    &quot;&quot;&quot;<br>    Function for ingestion into a Cassandra database.<br>    &quot;&quot;&quot;<br><br>    # Print a message indicating the start of the data insertion process.<br>    print(&quot;inserting data...&quot;)<br><br>    # Extract user information from the keyword arguments.<br>    user_id = kwargs.get(&#39;id&#39;)<br>    first_name = kwargs.get(&#39;first_name&#39;)<br>    last_name = kwargs.get(&#39;last_name&#39;)<br>    gender = kwargs.get(&#39;gender&#39;)<br>    address = kwargs.get(&#39;address&#39;)<br>    postcode = kwargs.get(&#39;post_code&#39;)  # Note: retrieving postcode using &#39;post_code&#39; key<br>    email = kwargs.get(&#39;email&#39;)<br>    username = kwargs.get(&#39;username&#39;)<br>    dob = kwargs.get(&#39;dob&#39;)  # Date of birth<br>    registered_date = kwargs.get(&#39;registered_date&#39;)<br>    phone = kwargs.get(&#39;phone&#39;)<br>    picture = kwargs.get(&#39;picture&#39;)<br><br>    try:<br>        # Execute an INSERT statement to add the user data to the &#39;created_users&#39; table.<br>        session.execute(&quot;&quot;&quot;<br>            INSERT INTO spark_streams.created_users(<br>                id, first_name, last_name, gender, address, <br>                post_code, email, username, dob, registered_date, phone, picture<br>            )<br>            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)<br>        &quot;&quot;&quot;, (user_id, first_name, last_name, gender, address,<br>              postcode, email, username, dob, registered_date, phone, picture))<br><br>        # Log an informational message upon successful data insertion.<br>        logging.info(f&quot;Data inserted for {first_name} {last_name}&quot;)<br><br>    except Exception as e:<br>        # Log an error message if data insertion fails.<br>        logging.error(f&#39;could not insert data due to {e}&#39;)<br><br><br>def create_spark_connection():<br><br>    &quot;&quot;&quot;<br>    Function to create a Spark session for data streaming.<br><br>    &quot;&quot;&quot;<br>    s_conn = None<br><br>    try:<br>        s_conn = SparkSession.builder \<br>                .appName(&#39;SparkDataStreaming&#39;) \<br>                .config(&#39;spark.jars.packages&#39;, <br>                        &quot;org.apache.spark:spark-sql-kafka-0-10_2.12:3.5.1,&quot;<br>                        &quot;com.datastax.spark:spark-cassandra-connector_2.12:3.5.0&quot;) \<br>                .config(&#39;spark.cassandra.connection.host&#39;, &#39;localhost&#39;) \<br>                .getOrCreate()<br><br><br>        s_conn.sparkContext.setLogLevel(&quot;ERROR&quot;)<br>        logging.info(&quot;Spark connection created successfully!&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;Couldn&#39;t create the spark session due to exception {e}&quot;)<br><br>    return s_conn<br><br><br>def connect_to_kafka(spark_conn):<br>    &quot;&quot;&quot;<br>    Function to connect to Kafka and read data into a Spark DataFrame as a streaming source.<br><br>    &quot;&quot;&quot;<br>    spark_df = None<br>    try:<br>        spark_df = spark_conn.readStream \<br>            .format(&#39;kafka&#39;) \<br>            .option(&#39;kafka.bootstrap.servers&#39;, &#39;localhost:9092&#39;) \<br>            .option(&#39;subscribe&#39;, &#39;users_created&#39;) \<br>            .option(&#39;startingOffsets&#39;, &#39;earliest&#39;) \<br>            .load()<br>        logging.info(&quot;kafka dataframe created successfully&quot;)<br>    except Exception as e:<br>        logging.warning(f&quot;kafka dataframe could not be created because: {e}&quot;)<br><br>    return spark_df<br><br><br>def create_cassandra_connection():<br>    &quot;&quot;&quot;<br>    Function to create a connection to a Cassandra cluster.<br>    &quot;&quot;&quot;<br><br>    try:<br>        # Connect to the Cassandra cluster by specifying the host address.<br>        cluster = Cluster([&#39;localhost&#39;])<br><br>        # Create a session to interact with the Cassandra cluster.<br>        cas_session = cluster.connect()<br><br>        # Return the Cassandra session for further operations.<br>        return cas_session<br>    except Exception as e:<br>        # Log an error message if the connection to Cassandra fails.<br>        logging.error(f&quot;Could not create Cassandra connection due to: {e}&quot;)<br>        return None  # Return None to indicate the failure to establish a connection.<br><br><br>def create_selection_df_from_kafka(spark_df):<br>    &quot;&quot;&quot;<br>    Function to create a structured DataFrame from a Kafka DataFrame by parsing the JSON data.<br>    &quot;&quot;&quot;<br><br>    # Define the schema for the DataFrame that matches the expected structure of the data.<br>    schema = StructType([<br>        StructField(&quot;id&quot;, StringType(), False),<br>        StructField(&quot;first_name&quot;, StringType(), False),<br>        StructField(&quot;last_name&quot;, StringType(), False),<br>        StructField(&quot;gender&quot;, StringType(), False),<br>        StructField(&quot;address&quot;, StringType(), False),<br>        StructField(&quot;post_code&quot;, StringType(), False),<br>        StructField(&quot;email&quot;, StringType(), False),<br>        StructField(&quot;username&quot;, StringType(), False),<br>        StructField(&quot;registered_date&quot;, StringType(), False),<br>        StructField(&quot;phone&quot;, StringType(), False),<br>        StructField(&quot;picture&quot;, StringType(), False)<br>    ])<br><br>    # Convert the &#39;value&#39; column from the Kafka DataFrame from bytes to string.<br>    # Parse the JSON data from the &#39;value&#39; column into a structured DataFrame using the defined schema.<br>    sel = spark_df.selectExpr(&quot;CAST(value AS STRING)&quot;) \<br>        .select(from_json(col(&#39;value&#39;), schema).alias(&#39;data&#39;)).select(&quot;data.*&quot;)<br><br>    # Print the resulting structured DataFrame for verification.<br>    print(sel)<br><br>    # Return the structured DataFrame containing the parsed data.<br>    return sel<br><br><br><br>if __name__ == &quot;__main__&quot;:<br>    # create spark connection<br>    spark_conn = create_spark_connection()<br><br>    if spark_conn is not None:<br>        # connect to kafka with spark connection<br>        spark_df = connect_to_kafka(spark_conn)<br>        selection_df = create_selection_df_from_kafka(spark_df)<br>        session = create_cassandra_connection()<br><br>        if session is not None:<br>            create_keyspace(session)<br>            create_table(session)<br><br>            logging.info(&quot;Streaming is being started...&quot;)<br><br>            streaming_query = (selection_df.writeStream.format(&quot;org.apache.spark.sql.cassandra&quot;)<br>                               .option(&#39;checkpointLocation&#39;, &#39;/tmp/checkpoint&#39;)<br>                               .option(&#39;keyspace&#39;, &#39;spark_streams&#39;)<br>                               .option(&#39;table&#39;, &#39;created_users&#39;)<br>                               .start())<br><br>            streaming_query.awaitTermination()</pre><p>Step : Launch spark streaming to consume data from producer kafka and load streaming dataset on cassandra database.</p><pre>python3 spark_stream.py</pre><p>We can see on terminal keyspace and table created succesfully.</p><p>Let’s check on cassandra container to see data ingest on it :</p><pre>docker exec -it cassandra cqlsh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBEHynktTSdz8wVJKwL-PA.png" /></figure><p>Great ! Data has been load correctly. Our data pipeline work correctly.</p><p>Let’s monitor data on our database in realtime with our web application using the micro framework flask assisted to flask-socketio.</p><p>Step : Easy monitoring of our data ingestion.<br>According to this part, we’ve decide just to display table with some statistics collect on our database cassandra. First of all, I’m a beginner on cassandra database using and don’t forget that cassandra is a NOSQL database so the paradigms is really differents to SQL database you know for example : “I<em>n cassandra before making filter over a columns you should first of all create a index over this columns”.</em></p><p>Check our code for kpi analysis over cassandra instance, on a file call eda.py:</p><pre>from cassandra.cluster import Cluster<br>from cassandra.auth import PlainTextAuthProvider<br>import pandas as pd<br>from datetime import datetime<br><br># Configuration de l&#39;authentification<br>auth_provider = PlainTextAuthProvider(username=&#39;cassandra&#39;, password=&#39;cassandra&#39;)<br># Connexion au cluster Cassandra via Docker<br>cluster = Cluster([&#39;localhost&#39;], port=9042, auth_provider=auth_provider)<br>session = cluster.connect()<br># Sélectionner le keyspace à utiliser<br>session.set_keyspace(&#39;spark_streams&#39;)<br><br>class KpiOnMyCassandraDataBase:<br><br>    @staticmethod<br>    def get_numbers_of_rows():<br>        query = &quot;SELECT count(*) FROM created_users;&quot;<br>        rows = session.execute(query)<br><br>        # get data as manipulable objects<br>        list_rows =  [row._asdict() for row in rows]<br><br>        # dataframe with list<br>        dataf =  pd.DataFrame(list_rows)<br>        kpi_value = dataf.values[0][0]<br>        return kpi_value<br>    <br>    @staticmethod<br>    def get_numbers_of_gender(gender):<br>        query = f&quot;SELECT count(*) as nbre_of_male FROM created_users WHERE gender = &#39;{gender}&#39;;&quot;<br>        rows = session.execute(query)<br><br>        # get data as manipulable objects<br>        list_rows =  [row._asdict() for row in rows]<br><br>        # dataframe with list<br>        dataf =  pd.DataFrame(list_rows)<br>        kpi_value = dataf.values[0][0]<br>        return str(kpi_value)<br>    <br>    @staticmethod<br>    def get_max_age_registration():<br>        query = &quot;SELECT MIN(registered_date) as min_age FROM created_users;&quot;<br>        rows = session.execute(query)<br><br>        # get data as manipulable objects<br>        list_rows =  [row._asdict() for row in rows]<br><br>        # dataframe with list<br>        dataf =  pd.DataFrame(list_rows)<br>        date_ = str(dataf.values[0][0])<br>        # convert date<br>        date_ = datetime.strptime(date_, &quot;%Y-%m-%dT%H:%M:%S.%fZ&quot;)<br><br>        kpi_value =  (datetime.now() - date_).days<br>        return str(kpi_value)<br>    <br>    @staticmethod<br>    def get_min_age_registration():<br>        query = &quot;SELECT MAX(registered_date) as max_age FROM created_users;&quot;<br>        rows = session.execute(query)<br><br>        # get data as manipulable objects<br>        list_rows =  [row._asdict() for row in rows]<br><br>        # dataframe with list<br>        dataf =  pd.DataFrame(list_rows)<br>        date_ = str(dataf.values[0][0])<br>        # convert date<br>        date_ = datetime.strptime(date_, &quot;%Y-%m-%dT%H:%M:%S.%fZ&quot;)<br><br>        kpi_value =  (datetime.now() - date_).days<br>        return kpi_value<br>    <br>    @staticmethod<br>    def get_number_of_nationality(country):<br>        query = &quot;SELECT address FROM created_users;&quot;<br>        rows = session.execute(query)<br><br>        # get data as manipulable objects --- nationality other last 500 persons<br>        list_rows =  [row._asdict() for row in rows]<br><br>        # dataframe with list<br>        dataf =  pd.DataFrame(list_rows)[&#39;address&#39;].tolist()<br>        <br>        # count over nationality<br>        count = sum(f&#39;{country}&#39; in address.lower() for address in dataf)<br>        return count<br><br></pre><p>Check our code flask on a file call main.py , which display data from socket instance:</p><pre>from flask import Flask, render_template<br>from flask_socketio import SocketIO<br>from cassandra.cluster import Cluster<br>from cassandra.auth import PlainTextAuthProvider<br>import time<br>import threading<br>import uuid<br>from datetime import datetime<br>from eda import KpiOnMyCassandraDataBase as kpi<br><br># Configuration of the Flask application<br>app = Flask(__name__)<br>app.config[&#39;SECRET_KEY&#39;] = &#39;your_secret_key&#39;  # Change this with a secure secret key<br>socketio = SocketIO(app)<br><br># Configuration of the authentication<br>auth_provider = PlainTextAuthProvider(username=&#39;cassandra&#39;, password=&#39;cassandra&#39;)<br><br># Connect to the Cassandra cluster<br>cluster = Cluster([&#39;localhost&#39;], port=9042, auth_provider=auth_provider)<br>session = cluster.connect()<br>session.set_keyspace(&#39;spark_streams&#39;)<br><br>def serialize_row(row):<br>    &quot;&quot;&quot;Convert non-serializable values to serializable types.&quot;&quot;&quot;<br>    serialized_row = {}<br>    for key, value in row.items():<br>        if isinstance(value, (list, dict)):<br>            serialized_row[key] = value  # Keep lists and dictionaries<br>        elif isinstance(value, (str, int, float)):<br>            serialized_row[key] = value  # Base types are already serializable<br>        elif isinstance(value, uuid.UUID):  # If it&#39;s a UUID<br>            serialized_row[key] = str(value)  # Convert to string<br>        else:<br>            serialized_row[key] = str(value)  # Convert any other type to string<br>    return serialized_row<br><br>def fetch_data():<br>    &quot;&quot;&quot;Function to continuously fetch data from Cassandra.&quot;&quot;&quot;<br>    while True:<br>        # Get the current date and time<br>        current_time = datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br><br>        # Query to count rows in the created_users table<br>        count_query = &quot;SELECT COUNT(*) FROM created_users;&quot;<br>        count_result = session.execute(count_query)<br>        row_count = count_result.one()[0]  # Get the count from the result<br><br>        # Query to count the number of male<br>        male_count =  kpi.get_numbers_of_gender(gender = &#39;male&#39;)<br><br>        # Query to count the number of female<br>        female_count =  kpi.get_numbers_of_gender(gender=&#39;female&#39;)<br><br>        # canadian count<br>        canadian_count =  kpi.get_number_of_nationality(country =  &#39;canada&#39;)<br>        <br>        # indian count<br>        indian_count =  kpi.get_number_of_nationality(country =  &#39;india&#39;)<br><br>        # french count<br>        french_count =  kpi.get_number_of_nationality(country =  &#39;france&#39;)<br><br>        # Emit the current time and row count<br>        socketio.emit(&#39;row_count&#39;, {&#39;time&#39;: current_time, &#39;count&#39;: row_count, <br>                                    &#39;male_count&#39;: male_count, &#39;female_count&#39;: female_count,<br>                                    &#39;canadian_count&#39;: canadian_count, &#39;indian_count&#39;: indian_count, <br>                                    &#39;french_count&#39;: french_count})<br><br>        time.sleep(3)  # Wait for 3 seconds before checking again<br><br>@app.route(&#39;/&#39;)<br>def index():<br>    return render_template(&#39;home.html&#39;)<br><br>if __name__ == &#39;__main__&#39;:<br>    # Start the thread for fetching data<br>    threading.Thread(target=fetch_data, daemon=True).start()<br>    socketio.run(app, host=&#39;0.0.0.0&#39;, port=5000)</pre><p>The method render_template of flask search html file on the repertory templates/ exclusively, so on a repertory templates/ create by me let’s put this html, css, java script vanilla code:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Real-time Data from Cassandra&lt;/title&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js&quot;&gt;&lt;/script&gt;<br>    &lt;style&gt;<br>        /* General style for the body */<br>        body {<br>            font-family: Arial, sans-serif;<br>            display: flex;<br>            flex-direction: column;<br>            align-items: center;<br>            background-color: #f5f5f5;<br>            margin: 0;<br>            padding: 20px;<br>        }<br><br>        h1 {<br>            color: #333;<br>            margin-bottom: 20px;<br>        }<br><br>        /* Styles for the table */<br>        table {<br>            width: 80%;<br>            border-collapse: collapse;<br>            border-radius: 8px;<br>            overflow: hidden;<br>            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);<br>            background-color: #ffffff;<br>        }<br><br>        th, td {<br>            padding: 12px 15px;<br>            text-align: center;<br>        }<br><br>        th {<br>            background-color: #4CAF50;<br>            color: white;<br>            font-weight: bold;<br>        }<br><br>        tr:nth-child(even) {<br>            background-color: #f2f2f2;<br>        }<br><br>        tr:hover {<br>            background-color: #e0f7fa;<br>        }<br><br>        td {<br>            color: #333;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Real-time Data from Cassandra&lt;/h1&gt;<br><br>    &lt;table&gt;<br>        &lt;thead&gt;<br>            &lt;tr&gt;<br>                &lt;th&gt;Date&lt;/th&gt;<br>                &lt;th&gt;Number of Records&lt;/th&gt;<br>                &lt;th&gt;Number of Males&lt;/th&gt;<br>                &lt;th&gt;Number of Females&lt;/th&gt;<br>                &lt;th&gt;Number of Canadians&lt;/th&gt;<br>                &lt;th&gt;Number of Indians&lt;/th&gt;<br>                &lt;th&gt;Number of French&lt;/th&gt;<br>            &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody id=&quot;row-count-table&quot;&gt;<br>            &lt;!-- New rows will be added here --&gt;<br>        &lt;/tbody&gt;<br>    &lt;/table&gt;<br><br>    &lt;script&gt;<br>        const socket = io();<br><br>        socket.on(&#39;row_count&#39;, function(msg) {<br>            // Create a new row for the table<br>            const row = document.createElement(&#39;tr&#39;);<br><br>            // Create a cell for the date<br>            const dateCell = document.createElement(&#39;td&#39;);<br>            dateCell.textContent = msg.time;<br><br>            // Create a cell for the number of records<br>            const countCell = document.createElement(&#39;td&#39;);<br>            countCell.textContent = msg.count;<br><br>            // Create a cell for the number of males<br>            const countMale = document.createElement(&#39;td&#39;);<br>            countMale.textContent = msg.male_count;<br><br>            // Create a cell for the number of females<br>            const countFemale = document.createElement(&#39;td&#39;);<br>            countFemale.textContent = msg.female_count;<br><br>            // Create a cell for the number of Canadians<br>            const countCanadian = document.createElement(&#39;td&#39;);<br>            countCanadian.textContent = msg.canadian_count;<br><br>            // Create a cell for the number of Indians<br>            const countIndian = document.createElement(&#39;td&#39;);<br>            countIndian.textContent = msg.indian_count;<br><br>            // Create a cell for the number of French<br>            const countFrench = document.createElement(&#39;td&#39;);<br>            countFrench.textContent = msg.french_count;<br><br>            // Append the cells to the row<br>            row.appendChild(dateCell);<br>            row.appendChild(countCell);<br>            row.appendChild(countMale);<br>            row.appendChild(countFemale);<br>            row.appendChild(countCanadian);<br>            row.appendChild(countIndian);<br>            row.appendChild(countFrench);<br><br>            // Append the row to the table<br>            document.getElementById(&#39;row-count-table&#39;).appendChild(row);<br>        });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>python3 main.py </pre><p>Depend on your version and let’s check something like that :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPd30MoL3QsuJMQq_VMNXw.png" /></figure><p><em>Fell free to clone my github project on master branch : </em><a href="https://github.com/IS2aC/end-to-end-datapipeline-1-streaming.git">https://github.com/IS2aC/end-to-end-datapipeline-1-streaming.git</a></p><h3>IV- Conclusion</h3><p>In conclusion, this project demonstrates a robust architecture capable of handling real-time data processing and scalability through tools like Kafka, Spark, Cassandra, and Docker. While this design brings numerous advantages in terms of performance and flexibility, it also introduces certain complexities and challenges. The high resource demands, potential latency, and operational overhead require careful management and expertise. Additionally, balancing data consistency between SQL and NoSQL databases and troubleshooting in a distributed environnent can be challenging.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac61a313fecf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Les Atouts Indispensables d’un Datapipeline de Qualité.]]></title>
            <link>https://medium.com/@nisaacemmanuel/les-atouts-indispensables-dun-datapipeline-de-qualit%C3%A9-291d63d82f29?source=rss-5fdee2b4e407------2</link>
            <guid isPermaLink="false">https://medium.com/p/291d63d82f29</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[is2ac]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 13:51:35 GMT</pubDate>
            <atom:updated>2024-01-05T13:51:35.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LovdnMfrYO8AcwuM16PiEQ.jpeg" /></figure><p>Le Data Engineer joue un rôle central dans la fourniture de données aux utilisateurs finaux. Ce processus implique principalement des opérations de collecte, de stockage et de mise en forme des données. L’objectif principal de ces opérations est de rendre les données provenant de sources identifiées accessibles et exploitables. Dans la création de ces processus, le Data Engineer conceptualisera ce que l’on appelle communément dans le jargon des données un “Datapipeline”. Cet article s’articulera principalement autour de trois questions fondamentales liées aux Datapipelines.</p><h3>C’est quoi concrètement un Datapipeline ?</h3><p>Ce terme fait référence à une <strong>séquence organisée d’opérations</strong> permettant le déplacement, la transformation et la gestion efficace des données tout au long de leur cycle de vie dans le système d’information. Pour illustrer de manière concrète un Datapipeline, prenons un exemple simple définit par l’architecture ci-dessous:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*kG3fxAaXIeO8kxGEfOMFQQ.png" /></figure><h3>A quoi sert un Datapipeline ?</h3><p>La conception d’un Datapipeline revêt des enjeux cruciaux dans le contexte actuel de gestion des données au sein des organisations. Ces enjeux sont multiples et revêtent une importance significative pour garantir une exploitation optimale des données.</p><h4>1. Optimisation de l’efficacité opérationnelle:</h4><p>L’architecture de conception d’un Datapipeline <em>(from scratch ou avec un logiciel)</em> intègre très souvent un orchestrateur. Celui-ci a principalement pour objectif d’automatiser le processus de rationalisation et de mise à disposition des données dans leur ensemble. Cette automatisation optimise de manière significative l’ensemble des processus liés à l’utilisation des données, réduisant drastiquement les délais et les erreurs associées à la manipulation manuelle des données.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*AfskSDEsE2K3eLaliCVfRQ.png" /></figure><h4>2. Qualité et cohérence des données :</h4><p>Un Datapipeline bien conçu intègre des mécanismes multiples de nettoyage, de validation et de normalisation des données. Cela garantit la qualité et la cohérence des informations, éléments essentiels pour prendre des décisions éclairées et fiables.</p><h4>3. Gestion en amont de la complexité des données :</h4><p>Le contexte du Big Data a engendré l’émergence de systèmes de stockage de données diversifiées et variées. Dans ce contexte, un Datapipeline aura principalement pour objectif de mener à bien les opérations de prétraitement des données et de gérer la complexité des informations en amont. Ceci vise à mettre à disposition des utilisateurs finaux, tels que les professionnels en Business Intelligence et les Data Scientists, des données simplifiées et facilement utilisables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sU77YldSQ5Ks36tnV-dhoQ.jpeg" /></figure><h3>C’est quoi un bon Datapipeline ?</h3><p>Les principales caractéristiques du bon Datapipeline peuvent se décrire au travers de ce sigle : <strong>RIST</strong>(Résilience Idempotence Scalabilité Transparence)</p><blockquote><strong><em>Résilience : </em></strong><em>Se définit par </em><strong><em>la capacité à gérer les échecs courants et à effectuer une reprise automatique en cas de défaillance</em></strong></blockquote><p>En gérant les échecs courants de manière proactive, un data pipeline résilient assure <strong>une robustesse opérationnelle</strong>. Cela signifie qu’il est capable de fonctionner de manière fiable même dans des conditions difficiles, minimisant ainsi les interruptions de service et assurant une disponibilité continue des données. De plus, en reprenant automatiquement en cas d’échecs, le data pipeline <strong>limite les interruptions dans le flux de traitement des données</strong>. Cela garantit une continuité opérationnelle, particulièrement cruciale dans des environnements où la disponibilité des données en temps réel est essentielle.</p><blockquote><strong><em>Idempotence :</em></strong><em> </em><strong><em>Datapipeline exécuté plusieurs fois avec un résultat constant.</em></strong></blockquote><p>L’idempotence garantit que l’exécution d’un datapipeline à plusieurs reprises générera toujours le même résultat. Cela est particulièrement crucial pour assurer <strong>la reproductibilité des analyses et des traitements de données</strong>, offrant ainsi une cohérence dans les résultats obtenus. En permettant une exécution multiple sans altérer le résultat, un Datapipeline idempotent facilite la gestion des erreurs. En cas d’interruption ou d’échec lors d’une exécution précédente, il est possible de relancer le pipeline sans craindre d’effets indésirables sur les données déjà traitées.</p><blockquote><strong><em>Scalabilité : </em></strong><em>Se définit par </em><strong><em>la capacité à gérer la montée en charge.</em></strong></blockquote><p>Un datapipeline scalable peut gérer efficacement des quantités massives de données, ce qui est crucial dans un contexte où les organisations génèrent et traitent constamment d’énormes ensembles d’informations. Cela garantit que le pipeline peut évoluer pour répondre aux besoins croissants en capacité de traitement des données.La haute fréquence d’invocations associée à la scalabilité signifie que le datapipeline peut répondre de manière réactive aux variations de charge. Il peut ajuster ses capacités pour faire face à des périodes d’activité intense sans sacrifier les performances, assurant ainsi une réponse rapide aux demandes.</p><blockquote><strong><em>Transparence :</em></strong><em> Se définit par </em><strong><em>l’absence de transformations en boîte noire, la présence d’une documentation claire et bien élaborée</em></strong><em>.</em></blockquote><p>Un Datapipeline transparent est un Datapipeline qui évite <strong>l’utilisation de fonctions transformations opaques</strong>, assurant ainsi une visibilité claire sur chaque étape du traitement des données. De plus, il est rigoureusement testé et accompagné d’une documentation exhaustive. Cette transparence garantit une compréhension approfondie du flux de données, favorise la confiance dans les résultats produits et simplifie la maintenance du pipeline.</p><h3>Conclusion</h3><p>En conclusion, la création d’un Datapipeline efficace revêt une importance cruciale dans le contexte complexe de la gestion des données au sein des organisations. Le rôle central du Data Engineer dans la mise à disposition des données aux utilisateurs finaux demande une approche méticuleuse et réfléchie afin d’assurer la qualité, la cohérence et la disponibilité des informations.</p><h4>Webographie</h4><p><a href="https://www.ml4devs.com/articles/scalable-efficient-big-data-analytics-machine-learning-pipeline-architecture-on-cloud/">Scalable Efficient Big Data Pipeline Architecture</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=291d63d82f29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>