<?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 Umair Karel on Medium]]></title>
        <description><![CDATA[Stories by Umair Karel on Medium]]></description>
        <link>https://medium.com/@umairkarel?source=rss-7329c51e441b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*smxvA-K_TUEERKUN3BIgHA.jpeg</url>
            <title>Stories by Umair Karel on Medium</title>
            <link>https://medium.com/@umairkarel?source=rss-7329c51e441b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:07:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umairkarel/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[How LinkedIn Catches Fake Profiles?]]></title>
            <link>https://umairkarel.medium.com/how-linkedin-catches-fake-profiles-577a1ce030d7?source=rss-7329c51e441b------2</link>
            <guid isPermaLink="false">https://medium.com/p/577a1ce030d7</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deepfakes]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Umair Karel]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 06:57:00 GMT</pubDate>
            <atom:updated>2024-06-12T06:57:52.719Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Ever wondered how LinkedIn manages to keep its vast professional network free from <strong>fake profiles</strong>?</blockquote><p>Imagine throwing a grand networking party, and the bouncer at the door has to ensure every guest is legitimate, professional, and adds value to the event. That’s precisely the challenge LinkedIn faces daily. But how does this digital bouncer, “<strong>LinkedIn”</strong>, sift through the millions of profiles to catch the fake ones?</p><blockquote>Between January and June of 2019, LinkedIn– at the time, home to more than 645 million members–took action on 21.6 million fake accounts. And, during the first quarter of 2019, Facebook removed 2.2 billion fake profiles.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*68vFuiQmFOX5pDwL.jpg" /><figcaption><strong>AI generated v/s Real</strong> person image</figcaption></figure><p>Generative adversarial networks (GANs) have been advanced to create astonishing realistic images of people. The diffusion-based techniques have overtaken the image synthesis to the next level, Allowing users to create realistic images only by providing a text prompt. These synthetically-generated faces are being used to create more convincing fake social-media profiles.</p><h4>So, Why is it difficult to automatically detect “synthetically generated” profile photos?</h4><p>There are several reason for this.</p><ol><li>The platforms is massive: LinkedIn has more than 1 billion members</li><li>There is a significant class imbalance between synthetic and real profile photos, which makes it challenging to train an AI model with such uneven data.</li><li>The AI is evolving: there has been 3 iterations of realistic StyleGAN faces within last few years, followed by the most recent text-to-image synthesis.</li><li>This is an adversarial system where the opponent continually and rapidly adjusts to new defences.</li></ol><h3><strong>Forensic approaches to the problem</strong></h3><p>Before diving into how LinkedIn tackles this issue, let’s first explore the general approaches to this problem, along with their benefits and challenges.</p><h4><strong>1. Hypothesis-driven</strong></h4><p>These approaches try to identify specific flaws within the synthetically generated faces. For example, inconsistencies with the facial symmetry in the corneal reflections and pupil shape have been observed in fake faces. Relatedly, head pose and the spatial layout of eyes, tip of nose, corners of mouth, chin, etc. in synthetically-generated faces are distinct from real faces. The <strong>benefit</strong> of these approaches is that they learn explicit, semantic-level anomalies. The <strong>drawback</strong> is that synthesis engines are evolving to incorporate these features, by learning to respect bilateral facial symmetry.</p><h4>2. Data-driven</h4><p>In this approach, machine learning is used to differentiate between real faces from fake ones. Usually, a trained system does well with images it has seen before but struggles with new, different images. These systems are becoming better at identifying a wide range of fake images, even ones they haven’t been trained on. This improvement comes from learning the flaws introduced when images are resized during the creation process.</p><p>However, this strength can also be a weakness. If these common flaws are removed, either on purpose or by accident, the systems become ineffective. Neural networks are also at risk from attacks that slightly alter an image, making real faces look fake and fake ones look real. Despite these challenges, these techniques are good at finding subtle and hidden flaws.</p><h3><strong>How LinkedIn Uses Hybrid Method For Exposing GAN-Generated Profile Photos</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*3wmHh15AH1lsM1_y1anpCQ.png" /><figcaption>(a) StyleGAN2 generated vs Real Image (b) compact embedding of both images</figcaption></figure><p>LinkedIn uses a hybrid of both approaches in which specific and distinct geometric properties in synthetically-generated faces are indentified and then data-driven approach is used to quantify and detect these properties. This approach has significantly reduced the need for training on a large number of synthesized faces and employed a lightweight classifier that is easy and fast to train.</p><p>Note that synthetic faces are mainly created from the neck up, while real profile photos usually show more of the upper body and shoulders. It is this within-class similarity and across-class differences that LinkedIn seek to exploit.</p><p>They use two related approaches that learn compact embeddings of synthetically-generated faces that capture the structural differences then these embeddings are used to distinguish synthetically-generated from real profile photos.</p><h3>Methods LinkedIn uses to identify fake profiles along with profile photos</h3><h4>Algorithms and Behaviour Analysis</h4><ul><li><strong>Profile Completeness:</strong> Genuine profiles generally have comprehensive information. A sparse profile with minimal details, especially in professional history and skills, raises red flags.</li><li><strong>Activity Patterns:</strong> LinkedIn’s algorithms monitor user activity, such as the frequency and nature of connections, messages, and posts. Unusual spikes or unnatural patterns can signal a fake account.</li><li><strong>Content Analysis:</strong> The content from profiles, messages, and posts are scrutinized for inconsistencies or generic text which indicates use of bots or scammers.</li></ul><h4>Security Features</h4><ul><li><strong>CAPTCHA Systems:</strong> To prevent automated bots, LinkedIn uses CAPTCHA systems during the sign-up process and other critical points.</li><li><strong>Two-Factor Authentication (2FA):</strong> Encouraging users to enable 2FA adds an extra layer of security, making it harder for fake profiles to operate.</li><li><strong>User Reports and Feedbacks: </strong>The community itself plays crucial role in identifying fake profiles. Linkedin allows Users to report suspicious accounts and their support team investigates these reports. This helps LinkedIn to significant volume of fake profiles.</li></ul><p>These are some of the methods that LinkedIn employs to detect fake profiles and block them.</p><blockquote><strong>Note:</strong> I have summarized the paper published by LinkedIn on <a href="https://farid.berkeley.edu/downloads/publications/cvpr23b.pdf">Exposing AI generated profile photos</a>. please refer if you are interested in technical details.</blockquote><p><strong>Thanks!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=577a1ce030d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering with SnowFlake and Amazon Sales Data: Final Part]]></title>
            <link>https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-part-5-ee88c51f2c55?source=rss-7329c51e441b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee88c51f2c55</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Umair Karel]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 03:32:28 GMT</pubDate>
            <atom:updated>2024-06-11T11:29:53.993Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing our exploration of an end-to-end ETL (Extract, Transform, Load) data pipeline for <em>Amazon Sales</em> data using Snowpark and Snowflake. In this part we will work on final layer i.e Data Consumption</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*EZp79cykYyNqHOnjW44Eyw.png" /></figure><blockquote>Checkout <a href="https://medium.com/@umairkarel/data-engineering-with-snowflake-and-amazon-sales-data-170048a368d7"><strong>Part 1</strong></a> of this series</blockquote><h3>Where to find complete resources for the series?</h3><p>The complete resources including code and worksheets are available on my <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/"><strong>Github repo</strong></a></p><h3>Understanding the concepts</h3><p>Now that we are at final layer (consumption) we have highest level of structured data here. Generally Star Schema is used to breakdown Data in <strong>Dims</strong> and <strong>Facts</strong>.</p><p>Here we will use the same approach, We will Breakdown our data into the <strong>Dims:</strong> region, product, promo_code, customer, payment and date and <strong>Facts:</strong> sales</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*mXSV0TUVQesi55tbrzHRYQ.png" /><figcaption>Star Schema</figcaption></figure><p><strong>Star Schema:</strong> A star schema is a type of database structure that consists of a central fact table surrounded by dimension tables.</p><p><strong>Fact Table (Facts):</strong> The fact table contains key information about the business. It records each event in the business. For example, in our case, the sales table is the fact table because it contains information about product sales, which is a crucial aspect of our business.</p><p><strong>Dimension Table (Dims):</strong> Dimension tables provide additional context to the facts. For example, in our case, the product table is a dimension table that provides details about the products sold. Another example could be a region/country table, which gives information about the location of each sale event.</p><blockquote><strong><em>Note:</em></strong><em> There is also </em><strong><em>snowflake schema</em></strong><em> which is variant of star schema. The main difference is that the dims are further broken down into </em><em>sub-dimensions</em></blockquote><h3>1. Defining our schema</h3><p>Let’s now define our start schema for the consumption layer.</p><blockquote>you can find the complete worksheet for this step <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/blob/main/Snowflake%20Worksheets/8.%20Consumption%20Layer.sql"><strong>here</strong></a></blockquote><p><strong>1. Creating Dimensions</strong></p><p>We will be first breaking down our data and defining all of our dimension tables.</p><pre>-- region dimension<br>create or replace sequence region_dim_seq<br>start = 1<br>increment = 1;<br>create or replace transient table region_dim(<br>    region_id_pk number primary key,<br>    Country text,<br>    Region text,<br>    isActive text(1)<br>);<br><br>-- product dimension<br>create or replace sequence product_dim_seq<br>start = 1<br>increment = 1;<br>create or replace transient table product_dim(<br>    product_id_pk number primary key,<br>    Mobile_key text,<br>    Brand text,<br>    Model text,<br>    Color text,<br>    Memory text,<br>    isActive text(1)<br>);<br><br>-- promo_code dimension<br>create or replace sequence promo_code_dim_seq<br>start = 1<br>increment = 1;<br>create or replace transient table promo_code_dim(<br>    promo_code_id_pk number primary key,<br>    promotion_code text,<br>    country text,<br>    region text,<br>    isActive text(1)<br>);<br>-- customer dimension<br>create or replace sequence customer_dim_seq<br>start = 1<br>increment = 1;<br>create or replace transient table customer_dim(<br>    customer_id_pk number primary key,<br>    customer_name text,<br>    CONCTACT_NO text,<br>    SHIPPING_ADDRESS text,<br>    country text,<br>    region text,<br>    isActive text(1)<br>);<br><br>-- payment dimension<br>create or replace sequence payment_dim_seq<br>start = 1<br>increment = 1;<br>create or replace transient table payment_dim(<br>    payment_id_pk number primary key,<br>    PAYMENT_METHOD text,<br>    PAYMENT_PROVIDER text,<br>    country text,<br>    region text,<br>    isActive text(1)<br>);<br><br>-- date dimension<br>create or replace sequence date_dim_seq<br>start = 1<br>increment = 1;<br>create or replace transient table date_dim(<br>    date_id_pk int primary key,<br>    order_dt date,<br>    order_year int,<br>    day_counter int,<br>    oder_month int,<br>    order_quater int,<br>    order_day int,<br>    order_dayofweek int,<br>    order_dayname text,<br>    order_dayofmonth int,<br>    order_weekday text<br>);</pre><p><strong>2. Creating Facts</strong></p><p>Now let’s define our fact table which is basically the sales table. Note that the fact table consists of many Foreign Keys as for each fact/event in the table is linked to the rows within Dims table (context)</p><pre>-- sales tables<br>create or replace sequence sales_fact_seq<br>start = 1<br>increment = 1;<br><br>create or replace table sales_fact (<br> order_id_pk number(38,0),<br> order_code varchar(),<br> date_id_fk number(38,0),<br> region_id_fk number(38,0),<br> customer_id_fk number(38,0),<br> payment_id_fk number(38,0),<br> product_id_fk number(38,0),<br> promo_code_id_fk number(38,0),<br> order_quantity number(38,0),<br> local_total_order_amt number(10,2),<br> local_tax_amt number(10,2),<br> exhchange_rate number(15,7),<br> us_total_order_amt number(23,8),<br> usd_tax_amt number(23,8)<br>);</pre><p><strong>3. Defining Constraints</strong></p><p>We’ll also need to define the constraints on our tables for the Foreing Keys by referencing to dim tables.</p><pre>-- Table Constraints<br>alter table sales_fact add<br>    constraint fk_sales_region FOREIGN KEY (REGION_ID_FK) REFERENCES region_dim (REGION_ID_PK) NOT ENFORCED;<br>alter table sales_fact add<br>    constraint fk_sales_date FOREIGN KEY (DATE_ID_FK) REFERENCES date_dim (DATE_ID_PK) NOT ENFORCED;<br>alter table sales_fact add<br>    constraint fk_sales_customer FOREIGN KEY (CUSTOMER_ID_FK) REFERENCES customer_dim (CUSTOMER_ID_PK) NOT ENFORCED;<br>alter table sales_fact add<br>    constraint fk_sales_payment FOREIGN KEY (PAYMENT_ID_FK) REFERENCES payment_dim (PAYMENT_ID_PK) NOT ENFORCED;<br>alter table sales_fact add<br>    constraint fk_sales_product FOREIGN KEY (PRODUCT_ID_FK) REFERENCES product_dim (PRODUCT_ID_PK) NOT ENFORCED;<br>alter table sales_fact add<br>    constraint fk_sales_promot FOREIGN KEY (PROMO_CODE_ID_FK) REFERENCES promo_code_dim (PROMO_CODE_ID_PK) NOT ENFORCED;</pre><p><strong>3. Grant permissions</strong></p><p>Grant permissions to the defined role sysadmin</p><pre>-- GRANT PERMISSIONS<br>GRANT ALL ON ALL TABLES IN SCHEMA amazon_sales_dwh.consumption TO ROLE sysadmin;<br>GRANT ALL ON ALL SEQUENCES IN SCHEMA amazon_sales_dwh.consumption TO ROLE sysadmin;</pre><h3>2. Loading data to consumption layer</h3><p>Now we will use python script to load the data from curation layer to the final consumption layer.</p><blockquote>You can find the complete python script <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/blob/main/step_5_curated_to_consumption.py"><strong>here</strong></a></blockquote><p><strong>1. Create region dim table</strong></p><p>This function filters the data by given value provided. Here we are adding new records and in &quot;part 2 delta&quot;, we are fetching existing records and updating.</p><pre>def create_region_dim(all_sales_df: DataFrame, session: Session) -&gt; None:<br>    &quot;&quot;&quot;<br>    Creates and updates the region dim table with country and region data from the sales DataFrame.<br>    Args:<br>        all_sales_df (DataFrame): DataFrame containing sales data,<br>                                  including &#39;Country&#39; and &#39;Region&#39; cols.<br>        session (Session): The database session used to execute SQL queries.<br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    region_dim_df = all_sales_df.groupBy(col(&quot;Country&quot;), col(&quot;Region&quot;)).count()<br>    region_dim_df = region_dim_df.with_column(&quot;isActive&quot;, lit(&quot;Y&quot;))<br>    region_dim_df = region_dim_df.selectExpr(<br>        &quot;amazon_sales_dwh.consumption.region_dim_seq.nextval as region_id_pk&quot;,<br>        &quot;Country&quot;,<br>        &quot;Region&quot;,<br>        &quot;isActive&quot;,<br>    )<br>    # part 2 where delta data will be processed<br>    existing_region_dim_df = session.sql(<br>        &quot;&quot;&quot;<br>        select<br>            Country,<br>            Region<br>        from<br>            amazon_sales_dwh.consumption.region_dim<br>        &quot;&quot;&quot;<br>    )<br>    region_dim_df = region_dim_df.join(<br>        existing_region_dim_df,<br>        region_dim_df[&quot;Country&quot;] == existing_region_dim_df[&quot;Country&quot;],<br>        join_type=&quot;leftanti&quot;,<br>    )</pre><p><strong>2. Create product dim table</strong></p><pre>def create_product_dim(all_sales_df: DataFrame, session: Session) -&gt; None:<br>    &quot;&quot;&quot;<br>    Creates and updates the product dim table with product data extracted from the sales DataFrame.<br>    Args:<br>        all_sales_df (DataFrame): DataFrame containing sales data, including the &#39;MOBILE_KEY&#39; column.<br>        session (Session): The database session used to execute SQL queries.<br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    product_dim_df = (<br>        all_sales_df.with_column(&quot;Brand&quot;, split(col(&quot;MOBILE_KEY&quot;), lit(&quot;/&quot;))[0])<br>        .with_column(&quot;Model&quot;, split(col(&quot;MOBILE_KEY&quot;), lit(&quot;/&quot;))[1])<br>        .with_column(&quot;Color&quot;, split(col(&quot;MOBILE_KEY&quot;), lit(&quot;/&quot;))[2])<br>        .with_column(&quot;Memory&quot;, split(col(&quot;MOBILE_KEY&quot;), lit(&quot;/&quot;))[3])<br>        .select(<br>            col(&quot;mobile_key&quot;), col(&quot;Brand&quot;), col(&quot;Model&quot;), col(&quot;Color&quot;), col(&quot;Memory&quot;)<br>        )<br>    )<br>    product_dim_df = product_dim_df.select(<br>        col(&quot;mobile_key&quot;),<br>        cast(col(&quot;Brand&quot;), StringType()).as_(&quot;Brand&quot;),<br>        cast(col(&quot;Model&quot;), StringType()).as_(&quot;Model&quot;),<br>        cast(col(&quot;Color&quot;), StringType()).as_(&quot;Color&quot;),<br>        cast(col(&quot;Memory&quot;), StringType()).as_(&quot;Memory&quot;),<br>    )<br>    product_dim_df = product_dim_df.groupBy(<br>        col(&quot;mobile_key&quot;), col(&quot;Brand&quot;), col(&quot;Model&quot;), col(&quot;Color&quot;), col(&quot;Memory&quot;)<br>    ).count()<br>    product_dim_df = product_dim_df.with_column(&quot;isActive&quot;, lit(&quot;Y&quot;))<br>    # fetch existing product dim records.<br>    existing_product_dim_df = session.sql(<br>        &quot;&quot;&quot;<br>        select<br>            mobile_key,<br>            Brand,<br>            Model,<br>            Color,<br>            Memory<br>        from<br>            amazon_sales_dwh.consumption.product_dim<br>        &quot;&quot;&quot;<br>    )<br>    existing_product_dim_df.count()<br>    product_dim_df = product_dim_df.join(<br>        existing_product_dim_df,<br>        [&quot;mobile_key&quot;, &quot;Brand&quot;, &quot;Model&quot;, &quot;Color&quot;, &quot;Memory&quot;],<br>        join_type=&quot;leftanti&quot;,<br>    )<br>    product_dim_df = product_dim_df.selectExpr(<br>        &quot;amazon_sales_dwh.consumption.product_dim_seq.nextval as product_id_pk&quot;,<br>        &quot;mobile_key&quot;,<br>        &quot;Brand&quot;,<br>        &quot;Model&quot;,<br>        &quot;Color&quot;,<br>        &quot;Memory&quot;,<br>        &quot;isActive&quot;,<br>    )</pre><p><strong>3. Create promotion dim table</strong></p><pre>def create_promocode_dim(all_sales_df: DataFrame, session: Session) -&gt; None:<br>    &quot;&quot;&quot;<br>    Creates and updates the promo code dimension table<br>    with promo code data from the sales DataFrame.<br>    Args:<br>        all_sales_df (DataFrame): DataFrame containing sales data, including the &#39;promotion_code&#39;, &#39;country&#39;, and &#39;region&#39; columns.<br>        session (Session): The database session used to execute SQL queries.<br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    promo_code_dim_df = all_sales_df.with_column(<br>        &quot;promotion_code&quot;,<br>        expr(<br>            &quot;&quot;&quot;<br>             case<br>                when promotion_code is null then &#39;NA&#39;<br>                else promotion_code end<br>            &quot;&quot;&quot;<br>        ),<br>    )<br>    promo_code_dim_df = promo_code_dim_df.groupBy(<br>        col(&quot;promotion_code&quot;), col(&quot;country&quot;), col(&quot;region&quot;)<br>    ).count()<br>    promo_code_dim_df = promo_code_dim_df.with_column(&quot;isActive&quot;, lit(&quot;Y&quot;))<br>    # fetch existing product dim records.<br>    existing_promo_code_dim_df = session.sql(<br>        &quot;&quot;&quot;<br>        select<br>            promotion_code,<br>            country,<br>            region<br>        from<br>            amazon_sales_dwh.consumption.promo_code_dim<br>        &quot;&quot;&quot;<br>    )<br>    # Update delta<br>    promo_code_dim_df = promo_code_dim_df.join(<br>        existing_promo_code_dim_df,<br>        [&quot;promotion_code&quot;, &quot;country&quot;, &quot;region&quot;],<br>        join_type=&quot;leftanti&quot;,<br>    )<br>    promo_code_dim_df = promo_code_dim_df.selectExpr(<br>        &quot;amazon_sales_dwh.consumption.promo_code_dim_seq.nextval as promo_code_id_pk&quot;,<br>        &quot;promotion_code&quot;,<br>        &quot;country&quot;,<br>        &quot;region&quot;,<br>        &quot;isActive&quot;,<br>    )</pre><p><strong>4. Create customer dim table</strong></p><pre>def create_customer_dim(all_sales_df: DataFrame, session: Session) -&gt; None:<br>    &quot;&quot;&quot;<br>    Creates and updates the customer dimension table<br>    with customer data from the sales DataFrame.<br>    Args:<br>        all_sales_df (DataFrame): DataFrame containing sales data, including &#39;COUNTRY&#39;, &#39;REGION&#39;, &#39;CUSTOMER_NAME&#39;, &#39;CONCTACT_NO&#39;, and &#39;SHIPPING_ADDRESS&#39; columns.<br>        session (Session): The database session used to execute SQL queries.<br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    customer_dim_df = all_sales_df.groupBy(<br>        col(&quot;COUNTRY&quot;),<br>        col(&quot;REGION&quot;),<br>        col(&quot;CUSTOMER_NAME&quot;),<br>        col(&quot;CONCTACT_NO&quot;),<br>        col(&quot;SHIPPING_ADDRESS&quot;),<br>    ).count()<br>    customer_dim_df = customer_dim_df.with_column(&quot;isActive&quot;, lit(&quot;Y&quot;))<br>    customer_dim_df = customer_dim_df.selectExpr(<br>        &quot;customer_name&quot;,<br>        &quot;conctact_no&quot;,<br>        &quot;shipping_address&quot;,<br>        &quot;country&quot;,<br>        &quot;region&quot;,<br>        &quot;isactive&quot;,<br>    )<br>    # Updating delta<br>    existing_customer_dim_df = session.sql(<br>        &quot;&quot;&quot;<br>        select<br>            customer_name,<br>            conctact_no,<br>            shipping_address,<br>            country,<br>            region<br>        from<br>            amazon_sales_dwh.consumption.customer_dim<br>        &quot;&quot;&quot;<br>    )<br>    customer_dim_df = customer_dim_df.join(<br>        existing_customer_dim_df,<br>        [&quot;customer_name&quot;, &quot;conctact_no&quot;, &quot;shipping_address&quot;, &quot;country&quot;, &quot;region&quot;],<br>        join_type=&quot;leftanti&quot;,<br>    )<br>    customer_dim_df = customer_dim_df.selectExpr(<br>        &quot;amazon_sales_dwh.consumption.customer_dim_seq.nextval as customer_id_pk&quot;,<br>        &quot;customer_name&quot;,<br>        &quot;conctact_no&quot;,<br>        &quot;shipping_address&quot;,<br>        &quot;country&quot;,<br>        &quot;region&quot;,<br>        &quot;isActive&quot;,<br>    )</pre><p><strong>5. Create payment dim table</strong></p><pre>def create_payment_dim(all_sales_df: DataFrame, session: Session) -&gt; None:<br>    &quot;&quot;&quot;<br>    Creates and updates the payment dimension table<br>    with payment data from the sales DataFrame.<br>    Args:<br>        all_sales_df (DataFrame): DataFrame containing sales data, including &#39;COUNTRY&#39;, &#39;REGION&#39;, &#39;payment_method&#39;, and &#39;payment_provider&#39; columns.<br>        session (Session): The database session used to execute SQL queries.<br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    payment_dim_df = all_sales_df.groupBy(<br>        col(&quot;COUNTRY&quot;), col(&quot;REGION&quot;), col(&quot;payment_method&quot;), col(&quot;payment_provider&quot;)<br>    ).count()<br>    payment_dim_df = payment_dim_df.with_column(&quot;isActive&quot;, lit(&quot;Y&quot;))<br>    # Updating delta<br>    existing_payment_dim_df = session.sql(<br>        &quot;&quot;&quot;<br>        select<br>            payment_method,<br>            payment_provider,<br>            country,<br>            region<br>        from<br>            amazon_sales_dwh.consumption.payment_dim<br>        &quot;&quot;&quot;<br>    )<br>    payment_dim_df = payment_dim_df.join(<br>        existing_payment_dim_df,<br>        [&quot;payment_method&quot;, &quot;payment_provider&quot;, &quot;country&quot;, &quot;region&quot;],<br>        join_type=&quot;leftanti&quot;,<br>    )<br>    payment_dim_df = payment_dim_df.selectExpr(<br>        &quot;amazon_sales_dwh.consumption.payment_dim_seq.nextval as payment_id_pk&quot;,<br>        &quot;payment_method&quot;,<br>        &quot;payment_provider&quot;,<br>        &quot;country&quot;,<br>        &quot;region&quot;,<br>        &quot;isActive&quot;,<br>    )</pre><p><strong>5. Create date dim table</strong></p><pre>def create_date_dim(all_sales_df: DataFrame, session: Session) -&gt; None:<br>    &quot;&quot;&quot;<br>    Creates and updates the date dimension table<br>    with date data based on the order dates in the sales DataFrame.<br>    Args:<br>        all_sales_df (DataFrame): DataFrame containing sales data, including &#39;order_dt&#39; col.<br>        session (Session): The database session used to execute SQL queries.<br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    start_date = (<br>        all_sales_df.select(min(&quot;order_dt&quot;).alias(&quot;min_order_dt&quot;))<br>        .collect()[0]<br>        .as_dict()[&quot;MIN_ORDER_DT&quot;]<br>    )<br>    end_date = (<br>        all_sales_df.select(max(&quot;order_dt&quot;).alias(&quot;max_order_dt&quot;))<br>        .collect()[0]<br>        .as_dict()[&quot;MAX_ORDER_DT&quot;]<br>    )<br>    date_range = pd.date_range(start=start_date, end=end_date, freq=&quot;D&quot;)<br>    # print(date_range)<br>    date_dim = DataFrame()<br>    date_dim[&quot;order_dt&quot;] = date_range.date<br>    date_dim[&quot;Year&quot;] = date_range.year<br>    # Calculate day counter<br>    start_day_of_year = pd.to_datetime(start_date).dayofyear<br>    date_dim[&quot;DayCounter&quot;] = date_range.dayofyear - start_day_of_year + 1<br>    date_dim[&quot;Month&quot;] = date_range.month<br>    date_dim[&quot;Quarter&quot;] = date_range.quarter<br>    date_dim[&quot;Day&quot;] = date_range.day<br>    date_dim[&quot;DayOfWeek&quot;] = date_range.dayofweek<br>    date_dim[&quot;DayName&quot;] = date_range.strftime(&quot;%A&quot;)<br>    date_dim[&quot;DayOfMonth&quot;] = date_range.day<br>    date_dim[&quot;Weekday&quot;] = date_dim[&quot;DayOfWeek&quot;].map(<br>        {<br>            0: &quot;Weekday&quot;,<br>            1: &quot;Weekday&quot;,<br>            2: &quot;Weekday&quot;,<br>            3: &quot;Weekday&quot;,<br>            4: &quot;Weekday&quot;,<br>            5: &quot;Weekend&quot;,<br>            6: &quot;Weekend&quot;,<br>        }<br>    )<br>    date_dim_df = session.create_dataframe(date_dim)<br>    existing_date_dim_df = session.sql(<br>        &quot;&quot;&quot;<br>        select<br>            order_dt<br>        from<br>            amazon_sales_dwh.consumption.date_dim<br>        &quot;&quot;&quot;<br>    )<br>    date_dim_df = date_dim_df.join(<br>        existing_date_dim_df,<br>        existing_date_dim_df[&quot;order_dt&quot;] == date_dim_df[&#39;&quot;order_dt&quot;&#39;],<br>        join_type=&quot;leftanti&quot;,<br>    )<br>    date_dim_df = date_dim_df.selectExpr(<br>        &quot;&quot;&quot;<br>        amazon_sales_dwh.consumption.date_dim_seq.nextval,<br>        &quot;order_dt&quot; as order_dt,<br>        &quot;Year&quot; as order_year,<br>        &quot;DayCounter&quot; as day_counter<br>        &quot;Month&quot; as order_month,<br>        &quot;Quarter&quot; as order_quarter,<br>        &quot;Day&quot; as order_day,<br>        &quot;DayOfWeek&quot; as order_dayofweek,<br>        &quot;DayName&quot; as order_dayname,<br>        &quot;DayOfMonth&quot; as order_dayofmonth,<br>        &quot;Weekday&quot; as order_weekda<br>        &quot;&quot;&quot;<br>    )</pre><p>If the script outputs correctly then data curation is successful 🎉. Feel free to comment if you face any issue while running the script.</p><p><strong>Thank you!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee88c51f2c55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering with SnowFlake and Amazon Sales Data: Part 4]]></title>
            <link>https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-part-4-52f758a12774?source=rss-7329c51e441b------2</link>
            <guid isPermaLink="false">https://medium.com/p/52f758a12774</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Umair Karel]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 11:32:07 GMT</pubDate>
            <atom:updated>2024-06-26T10:36:31.688Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing our exploration of an end-to-end ETL (Extract, Transform, Load) data pipeline for <em>Amazon Sales</em> data using Snowpark and Snowflake. In this part we will focus on working on Data Curation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*VR0M9XuuY2zaKnacD03H1Q.png" /></figure><blockquote>Checkout <a href="https://medium.com/@umairkarel/data-engineering-with-snowflake-and-amazon-sales-data-170048a368d7"><strong>Part 1</strong></a> of this series</blockquote><h3>Where to find complete resources for the series?</h3><p>The complete resources including code and worksheets are available on my <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/"><strong>Github repo</strong></a></p><h3>1. Defining Curation layer</h3><p>First of all we will define the tables and sequences for the curated layer (schema)</p><blockquote>you can find the complete worksheet for this step <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/blob/main/Snowflake%20Worksheets/7.%20Source%20to%20Curated%20Layer.sql"><strong>here</strong></a></blockquote><p><strong>1. Creating Sequences</strong></p><p>We will be first creating sequences which we’ll be using as primary key for our table while loading the data.</p><p><strong>Snowflake Sequences:</strong> Sequences are basically used to generate unique numbers. The key advantage is that they can be used across sessions and statements, including concurrent statements.</p><pre>-- Create Sequences for the tables<br>use schema curated;<br><br>create or replace sequence in_sales_order_seq<br>  start = 1<br>  increment = 1<br>comment=&#39;This is sequence for India sales order table&#39;;<br>create or replace sequence us_sales_order_seq<br>  start = 1<br>  increment = 1<br>  comment=&#39;This is sequence for USA sales order table&#39;;<br>create or replace sequence fr_sales_order_seq<br>  start = 1<br>  increment = 1<br>  comment=&#39;This is sequence for France sales order table&#39;;</pre><p><strong>2. Defining Tables (DDL)</strong></p><p>Now we will define the schema/structure of our tables to load data into. This includes DDL defining the structure and data types of the columns within the table.</p><p>Since we are using data from three different source file types, we will create three tables.</p><pre>-- curated India sales order table<br>create or replace table in_sales_order (<br> sales_order_key number(38,0),<br> order_id varchar(),<br> order_dt date,<br> customer_name varchar(),<br> mobile_key varchar(),<br> country varchar(),<br> region varchar(),<br> order_quantity number(38,0),<br> local_currency varchar(),<br> local_unit_price number(38,0),<br> promotion_code varchar(),<br> local_total_order_amt number(10,2),<br> local_tax_amt number(10,2),<br> exhchange_rate number(15,7),<br> us_total_order_amt number(23,8),<br> usd_tax_amt number(23,8),<br> payment_status varchar(),<br> shipping_status varchar(),<br> payment_method varchar(),<br> payment_provider varchar(),<br> conctact_no varchar(),<br> shipping_address varchar()<br>);<br><br>-- curated US sales order table<br>create or replace table us_sales_order (<br> sales_order_key number(38,0),<br> order_id varchar(),<br> order_dt date,<br> customer_name varchar(),<br> mobile_key varchar(),<br> country varchar(),<br> region varchar(),<br> order_quantity number(38,0),<br> local_currency varchar(),<br> local_unit_price number(38,0),<br> promotion_code varchar(),<br> local_total_order_amt number(10,2),<br> local_tax_amt number(10,2),<br> exhchange_rate number(15,7),<br> us_total_order_amt number(23,8),<br> usd_tax_amt number(23,8),<br> payment_status varchar(),<br> shipping_status varchar(),<br> payment_method varchar(),<br> payment_provider varchar(),<br> conctact_no varchar(),<br> shipping_address varchar()<br>);<br><br>-- curated FR sales order table<br>create or replace table fr_sales_order (<br> sales_order_key number(38,0),<br> order_id varchar(),<br> order_dt date,<br> customer_name varchar(),<br> mobile_key varchar(),<br> country varchar(),<br> region varchar(),<br> order_quantity number(38,0),<br> local_currency varchar(),<br> local_unit_price number(38,0),<br> promotion_code varchar(),<br> local_total_order_amt number(10,2),<br> local_tax_amt number(10,2),<br> exhchange_rate number(15,7),<br> us_total_order_amt number(23,8),<br> usd_tax_amt number(23,8),<br> payment_status varchar(),<br> shipping_status varchar(),<br> payment_method varchar(),<br> payment_provider varchar(),<br> conctact_no varchar(),<br> shipping_address varchar()<br>);</pre><p><strong>3. Grant permissions</strong></p><p>Grant permissions to the defined role sysadmin</p><pre>-- GRANT PERMISSIONS<br>GRANT ALL ON ALL TABLES IN SCHEMA amazon_sales_dwh.curated TO ROLE sysadmin;<br>GRANT ALL ON ALL SEQUENCES IN SCHEMA amazon_sales_dwh.curated TO ROLE sysadmin;</pre><h3>2. Data Curation</h3><p>Now we will use python script to curate the data. Curation is basically like cleaning and massaging the data using the functions like filter and joining with different data.</p><blockquote>you can find the complete python script<strong> </strong><a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/blob/main/step_4_source_to_curated.py"><strong>here</strong></a></blockquote><p><strong>1. Filtering</strong></p><p>This function filters the data by given value provided.</p><pre>def filter_dataset(df: DataFrame, column_name: str, filter_value: str) -&gt; DataFrame:<br>    &quot;&quot;&quot;<br>    Filter the DataFrame based on a specified column and value.<br>    This function filters the input DataFrame to include only the rows where the specified column&#39;s<br>    value matches the given value.<br>    Args:<br>        df (DataFrame): The input DataFrame to be filtered.<br>        column_name (str): The name of the column on which the filter is to be applied.<br>        filter_value (str): The value to filter the rows by.<br>    Returns:<br>        DataFrame: A new DataFrame containing only the rows that match the filter value.<br>    <br>     Example:<br>        filtered_df = filter_dataset(df, &#39;PAYMENT_STATUS&#39;, &#39;Paid&#39;)<br>    &quot;&quot;&quot;<br><br>    return df.filter(col(column_name) == filter_value)</pre><p><strong>2. Process the data</strong></p><p>Now we will process the sales order data which is basically filtering, and combining it with different data like Forex for exchange rates.</p><pre>def process_sales_order(country_code: str):<br>    &quot;&quot;&quot;<br>    Process sales orders for a given country and save the curated data.<br>    This function fetches sales orders from a specific country, filters the data to include only<br>    paid and delivered orders, adds country and region information, performs a join with a<br>    forex exchange rate table, de-duplicates the data, and saves the final curated data to a table.<br>    Args:<br>        country_code (str): The country code for which the sales orders need to be processed.<br>                            Supported country codes are &#39;US&#39;, &#39;IN&#39;, and &#39;FR&#39;.<br>                            &#39;US&#39; for United States<br>                            &#39;IN&#39; for India<br>                            &#39;FR&#39; for France<br>    Raises:<br>        ValueError: If the provided country_code is not supported.<br>    &quot;&quot;&quot;<br>    # Dictionary to map country codes to relevant details<br>    country_details = {<br>        &quot;US&quot;: (&quot;us_sales_order&quot;, &quot;USD&quot;, &quot;US&quot;, &quot;AMER&quot;, &quot;USD2USD&quot;),<br>        &quot;IN&quot;: (&quot;in_sales_order&quot;, &quot;INR&quot;, &quot;IN&quot;, &quot;APAC&quot;, &quot;USD2INR&quot;),<br>        &quot;FR&quot;: (&quot;fr_sales_order&quot;, &quot;EUR&quot;, &quot;FR&quot;, &quot;EU&quot;, &quot;USD2EU&quot;),<br>    }<br>    # Fetch country-specific details<br>    sales_order_table, local_currency, country, region, exchange_rate_col = (<br>        country_details[country_code]<br>    )<br>    # Get the session object and get dataframe<br>    session = get_snowpark_session()<br>    sales_df = session.sql(f&quot;SELECT * FROM {sales_order_table}&quot;)<br>    # Apply filter to select only paid and delivered sale orders<br>    paid_sales_df = filter_dataset(sales_df, &quot;PAYMENT_STATUS&quot;, &quot;Paid&quot;)<br>    shipped_sales_df = filter_dataset(paid_sales_df, &quot;SHIPPING_STATUS&quot;, &quot;Delivered&quot;)<br>    # Adding country and region to the data frame<br>    country_sales_df = shipped_sales_df.with_column(<br>        &quot;Country&quot;, lit(country)<br>    ).with_column(&quot;Region&quot;, lit(region))<br>    # Join to add forex calculation<br>    forex_df = session.sql(&quot;SELECT * FROM amazon_sales_dwh.common.exchange_rate&quot;)<br>    sales_with_forext_df = country_sales_df.join(<br>        forex_df,<br>        country_sales_df[&quot;order_dt&quot;] == forex_df[&quot;date&quot;],<br>        join_type=&quot;outer&quot;,<br>    )<br>    # De-duplication<br>    unique_orders = (<br>        sales_with_forext_df.with_column(<br>            &quot;order_rank&quot;,<br>            rank().over(<br>                Window.partitionBy(col(&quot;order_dt&quot;)).order_by(<br>                    col(&quot;_metadata_last_modified&quot;).desc()<br>                )<br>            ),<br>        )<br>        .filter(col(&quot;order_rank&quot;) == 1)<br>        .select(col(&quot;SALES_ORDER_KEY&quot;).alias(&quot;unique_sales_order_key&quot;))<br>    )<br>    final_sales_df = unique_orders.join(<br>        sales_with_forext_df,<br>        unique_orders[&quot;unique_sales_order_key&quot;]<br>        == sales_with_forext_df[&quot;SALES_ORDER_KEY&quot;],<br>        join_type=&quot;inner&quot;,<br>    )<br>    # Select final columns<br>    final_sales_df = final_sales_df.select(<br>        col(&quot;SALES_ORDER_KEY&quot;),<br>        col(&quot;ORDER_ID&quot;),<br>        col(&quot;ORDER_DT&quot;),<br>        col(&quot;CUSTOMER_NAME&quot;),<br>        col(&quot;MOBILE_KEY&quot;),<br>        col(&quot;Country&quot;),<br>        col(&quot;Region&quot;),<br>        col(&quot;ORDER_QUANTITY&quot;),<br>        lit(local_currency).alias(&quot;LOCAL_CURRENCY&quot;),<br>        col(&quot;UNIT_PRICE&quot;).alias(&quot;LOCAL_UNIT_PRICE&quot;),<br>        col(&quot;PROMOTION_CODE&quot;).alias(&quot;PROMOTION_CODE&quot;),<br>        col(&quot;FINAL_ORDER_AMOUNT&quot;).alias(&quot;LOCAL_TOTAL_ORDER_AMT&quot;),<br>        col(&quot;TAX_AMOUNT&quot;).alias(&quot;local_tax_amt&quot;),<br>        col(exchange_rate_col).alias(&quot;Exchange_Rate&quot;),<br>        (col(&quot;FINAL_ORDER_AMOUNT&quot;) / col(exchange_rate_col)).alias(<br>            &quot;US_TOTAL_ORDER_AMT&quot;<br>        ),<br>        (col(&quot;TAX_AMOUNT&quot;) / col(exchange_rate_col)).alias(&quot;USD_TAX_AMT&quot;),<br>        col(&quot;payment_status&quot;),<br>        col(&quot;shipping_status&quot;),<br>        col(&quot;payment_method&quot;),<br>        col(&quot;payment_provider&quot;),<br>        (<br>            col(&quot;phone&quot;).alias(&quot;contact_no&quot;)<br>            if country_code in (&quot;US&quot;, &quot;FR&quot;)<br>            else col(&quot;mobile&quot;).alias(&quot;contact_no&quot;)<br>        ),<br>        col(&quot;shipping_address&quot;),<br>    )<br>    # Write final dataframe to the corresponding curated table<br>    final_sales_df.write.save_as_table(<br>        f&quot;amazon_sales_dwh.curated.{country.lower()}_sales_order&quot;, mode=&quot;append&quot;<br>    )</pre><p>If the script outputs correctly then data curation is successful 🎉. Feel free to comment if you face any issue while running the script.</p><p>Follow the next step <a href="https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-part-5-ee88c51f2c55"><strong><em>here</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52f758a12774" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering with SnowFlake and Amazon Sales Data: Part 3]]></title>
            <link>https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-part-3-60e0704043a0?source=rss-7329c51e441b------2</link>
            <guid isPermaLink="false">https://medium.com/p/60e0704043a0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Umair Karel]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 04:42:09 GMT</pubDate>
            <atom:updated>2024-06-07T11:55:05.599Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing our exploration of an end-to-end ETL (Extract, Transform, Load) data pipeline for <em>Amazon Sales</em> data using Snowpark and Snowflake. In this part we will focus on working on Source and Common Layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*dtVnU8tffPytvhclwfmwnA.png" /></figure><blockquote>Checkout <a href="https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-170048a368d7"><strong>Part 1</strong></a> of this series</blockquote><h3>Where to find complete resources for the series?</h3><p>The complete resources including code and worksheets are available on my G<a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/"><strong>ithub repo</strong></a></p><h3>1. Working on common objects (layer)</h3><p>Remember we create a schema named common, we will be using this to store objects which are being used by multiple schema’s. You can assume this as global variables which are being used by any schema.</p><p>we will use this to store file formats which are basically a parser which we&#39;ll use while loading the data from staging to the tables.</p><blockquote>you can find the complete worksheet for this step <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/blob/main/Snowflake%20Worksheets/4.%20Common%20Schema.sql"><strong>here</strong></a></blockquote><p><strong>1. Create file formats</strong></p><pre>-- create file formats csv (India), json (France), Parquet (USA)<br>create or replace file format my_csv_format<br>  type = csv<br>  field_delimiter = &#39;,&#39;<br>  skip_header = 1<br>  null_if = (&#39;null&#39;, &#39;null&#39;)<br>  empty_field_as_null = true<br>  field_optionally_enclosed_by = &#39;\042&#39;<br>  compression = auto;<br><br>-- json file format with strip outer array true<br>create or replace file format my_json_format<br>  type = json<br>  strip_outer_array = true<br>  compression = auto;<br><br>-- parquet file format<br>create or replace file format my_parquet_format<br>  type = parquet<br>  compression = snappy;</pre><p><strong>2. Add Exchange rate data</strong></p><p>Since we have sales data from three different countries we need to add exchange rate for these countries to have all values in USD. This is called data normalization i.e all data must be in same type.</p><pre>use schema common;<br><br>create or replace transient table exchange_rate(<br>    date date, <br>    usd2usd decimal(10,7),<br>    usd2eu decimal(10,7),<br>    usd2can decimal(10,7),<br>    usd2uk decimal(10,7),<br>    usd2inr decimal(10,7),<br>    usd2jp decimal(10,7)<br>);<br><br>copy into amazon_sales_dwh.common.exchange_rate<br>from <br>(<br>select <br>    t.$1::date as exchange_dt,<br>    to_decimal(t.$2) as usd2usd,<br>    to_decimal(t.$3,12,10) as usd2eu,<br>    to_decimal(t.$4,12,10) as usd2can,<br>    to_decimal(t.$4,12,10) as usd2uk,<br>    to_decimal(t.$4,12,10) as usd2inr,<br>    to_decimal(t.$4,12,10) as usd2jp<br>from <br>     @amazon_sales_dwh.source.data_stg/exchange-rate-data.csv<br>     (file_format =&gt; &#39;amazon_sales_dwh.common.my_csv_format&#39;) t</pre><p><strong>3. Grant permissions</strong></p><pre>-- Grant permissions for all items to sysadmin (you can create and use different role too)<br>-- It is not necessary to provide &quot;ALL ON ALL&quot; permission, here I have used just for simplicity.<br><br>GRANT ALL PRIVILEGES ON FILE FORMAT AMAZON_SALES_DWH.COMMON.MY_CSV_FORMAT TO sysadmin;<br>GRANT ALL PRIVILEGES ON FILE FORMAT AMAZON_SALES_DWH.COMMON.MY_JSON_FORMAT TO sysadmin;<br>GRANT ALL PRIVILEGES ON FILE FORMAT AMAZON_SALES_DWH.COMMON.MY_PARQUET_FORMAT TO sysadmin;<br><br>GRANT ALL ON ALL TABLES IN SCHEMA amazon_sales_dwh.common TO ROLE sysadmin;</pre><h3>2. Working on source layer</h3><p>Now that we have staged our data to an internal snowflake stage. We will now load this data to the tables in the source schema (layer)</p><blockquote>you can find the complete worksheet for this step <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/blob/main/Snowflake%20Worksheets/3.%20Source%20Tables.sql"><strong>here</strong></a></blockquote><p><strong>1. Creating Sequences</strong></p><p>We will be first creating sequences which we’ll be using as primary key for our table while loading the data.</p><p><strong>Snowflake Sequences:</strong> Sequences are basically used to generate unique numbers. The key advantage is that they can be used across sessions and statements, including concurrent statements.</p><pre>-- Create Sequences for the tables<br>use schema source;<br><br>create or replace sequence in_sales_order_seq<br>  start = 1<br>  increment = 1<br>comment=&#39;This is sequence for India sales order table&#39;;<br>create or replace sequence us_sales_order_seq<br>  start = 1<br>  increment = 1<br>  comment=&#39;This is sequence for USA sales order table&#39;;<br>create or replace sequence fr_sales_order_seq<br>  start = 1<br>  increment = 1<br>  comment=&#39;This is sequence for France sales order table&#39;;</pre><p><strong>2. Creating Source Tables (DDL)</strong></p><p>Now we will define the schema/structure of our tables to load data into. This includes DDL defining the structure and data types of the columns within the table.</p><p>Since we are using data from three different source file types, we will create three tables.</p><pre>-- India Sales Table in Source Schema (CSV File)<br>create or replace transient table in_sales_order (<br> sales_order_key number(38,0),<br> order_id varchar(),<br> customer_name varchar(),<br> mobile_key varchar(),<br> order_quantity number(38,0),<br> unit_price number(38,0),<br> order_valaue number(38,0),<br> promotion_code varchar(),<br> final_order_amount number(10,2),<br> tax_amount number(10,2),<br> order_dt date,<br> payment_status varchar(),<br> shipping_status varchar(),<br> payment_method varchar(),<br> payment_provider varchar(),<br> mobile varchar(),<br> shipping_address varchar(),<br> _metadata_file_name varchar(),<br> _metadata_row_numer number(38,0),<br> _metadata_last_modified timestamp_ntz(9)<br>);<br><br>-- US Sales Table in Source Schema (Parquet File)<br>create or replace transient table us_sales_order (<br> sales_order_key number(38,0),<br> order_id varchar(),<br> customer_name varchar(),<br> mobile_key varchar(),<br> order_quantity number(38,0),<br> unit_price number(38,0),<br> order_valaue number(38,0),<br> promotion_code varchar(),<br> final_order_amount number(10,2),<br> tax_amount number(10,2),<br> order_dt date,<br> payment_status varchar(),<br> shipping_status varchar(),<br> payment_method varchar(),<br> payment_provider varchar(),<br> phone varchar(),<br> shipping_address varchar(),<br> _metadata_file_name varchar(),<br> _metadata_row_numer number(38,0),<br> _metadata_last_modified timestamp_ntz(9)<br>);<br><br>-- France Sales Table in Source Schema (JSON File)<br>create or replace transient table fr_sales_order (<br> sales_order_key number(38,0),<br> order_id varchar(),<br> customer_name varchar(),<br> mobile_key varchar(),<br> order_quantity number(38,0),<br> unit_price number(38,0),<br> order_valaue number(38,0),<br> promotion_code varchar(),<br> final_order_amount number(10,2),<br> tax_amount number(10,2),<br> order_dt date,<br> payment_status varchar(),<br> shipping_status varchar(),<br> payment_method varchar(),<br> payment_provider varchar(),<br> phone varchar(),<br> shipping_address varchar(),<br> _metadata_file_name varchar(),<br> _metadata_row_numer number(38,0),<br> _metadata_last_modified timestamp_ntz(9)<br>);</pre><p><strong>3. Load data from stage to source tables</strong></p><p>After defining the tables for our source schema, Now we will load the data from stage to these tables.</p><p>For this we will be using the given python script to load data. Note that we can do this directly in worksheet too. But to automate this process we use Python script</p><pre>&quot;&quot;&quot;<br>Snowflake load data from staging to source tables<br>&quot;&quot;&quot;<br><br>import os<br>import sys<br>import logging<br>from snowflake.snowpark import Session<br>from dotenv import load_dotenv<br>load_dotenv()<br># initiate logging at info level<br>logging.basicConfig(<br>    stream=sys.stdout,<br>    level=logging.INFO,<br>    format=&quot;%(asctime)s - %(levelname)s - %(message)s&quot;,<br>    datefmt=&quot;%I:%M:%S&quot;,<br>)<br><br>COUNTRY_SQL_STATEMENTS = {<br>    &quot;in&quot;: &quot;&quot;&quot;<br>        COPY INTO amazon_sales_dwh.source.in_sales_order<br>        FROM (<br>            SELECT<br>                amazon_sales_dwh.source.in_sales_order_seq.NEXTVAL,<br>                $1::text AS order_id,<br>                $2::text AS customer_name,<br>                $3::text AS mobile_key,<br>                $4::number AS order_quantity,<br>                $5::number AS unit_price,<br>                $6::number AS order_value,<br>                $7::text AS promotion_code,<br>                $8::number(10,2) AS final_order_amount,<br>                $9::number(10,2) AS tax_amount,<br>                t.$10::date AS order_dt,<br>                t.$11::text AS payment_status,<br>                t.$12::text AS shipping_status,<br>                t.$13::text AS payment_method,<br>                t.$14::text AS payment_provider,<br>                t.$15::text AS mobile,<br>                t.$16::text AS shipping_address,<br>                metadata$filename AS stg_file_name,<br>                metadata$file_row_number AS stg_row_number,<br>                metadata$file_last_modified AS stg_last_modified<br>            FROM<br>                @amazon_sales_dwh.source.data_stg/sales/source=IN/format=csv/<br>                (file_format =&gt; &#39;amazon_sales_dwh.common.my_csv_format&#39;) t<br>        )<br>        ON_ERROR = CONTINUE<br>        &quot;&quot;&quot;,<br>    &quot;us&quot;: &quot;&quot;&quot;<br>        COPY INTO amazon_sales_dwh.source.us_sales_order<br>        FROM (<br>            SELECT<br>                amazon_sales_dwh.source.us_sales_order_seq.NEXTVAL,<br>                $1:&quot;Order ID&quot;::text AS order_id,<br>                $1:&quot;Customer Name&quot;::text AS customer_name,<br>                $1:&quot;Mobile Model&quot;::text AS mobile_key,<br>                TO_NUMBER($1:&quot;Quantity&quot;) AS quantity,<br>                TO_NUMBER($1:&quot;Price per Unit&quot;) AS unit_price,<br>                TO_DECIMAL($1:&quot;Total Price&quot;) AS total_price,<br>                $1:&quot;Promotion Code&quot;::text AS promotion_code,<br>                $1:&quot;Order Amount&quot;::number(10,2) AS order_amount,<br>                TO_DECIMAL($1:&quot;Tax&quot;) AS tax,<br>                $1:&quot;Order Date&quot;::date AS order_dt,<br>                $1:&quot;Payment Status&quot;::text AS payment_status,<br>                $1:&quot;Shipping Status&quot;::text AS shipping_status,<br>                $1:&quot;Payment Method&quot;::text AS payment_method,<br>                $1:&quot;Payment Provider&quot;::text AS payment_provider,<br>                $1:&quot;Phone&quot;::text AS phone,<br>                $1:&quot;Delivery Address&quot;::text AS shipping_address,<br>                metadata$filename AS stg_file_name,<br>                metadata$file_row_number AS stg_row_number,<br>                metadata$file_last_modified AS stg_last_modified<br>            FROM<br>                @amazon_sales_dwh.source.data_stg/sales/source=US/format=parquet/<br>                (file_format =&gt; amazon_sales_dwh.common.my_parquet_format)<br>        )<br>        ON_ERROR = CONTINUE<br>        &quot;&quot;&quot;,<br>    &quot;fr&quot;: &quot;&quot;&quot;<br>        COPY INTO amazon_sales_dwh.source.fr_sales_order<br>        FROM (<br>            SELECT<br>                amazon_sales_dwh.source.fr_sales_order_seq.NEXTVAL,<br>                $1:&quot;Order ID&quot;::text AS order_id,<br>                $1:&quot;Customer Name&quot;::text AS customer_name,<br>                $1:&quot;Mobile Model&quot;::text AS mobile_key,<br>                TO_NUMBER($1:&quot;Quantity&quot;) AS quantity,<br>                TO_NUMBER($1:&quot;Price per Unit&quot;) AS unit_price,<br>                TO_DECIMAL($1:&quot;Total Price&quot;) AS total_price,<br>                $1:&quot;Promotion Code&quot;::text AS promotion_code,<br>                $1:&quot;Order Amount&quot;::number(10,2) AS order_amount,<br>                TO_DECIMAL($1:&quot;Tax&quot;) AS tax,<br>                $1:&quot;Order Date&quot;::date AS order_dt,<br>                $1:&quot;Payment Status&quot;::text AS payment_status,<br>                $1:&quot;Shipping Status&quot;::text AS shipping_status,<br>                $1:&quot;Payment Method&quot;::text AS payment_method,<br>                $1:&quot;Payment Provider&quot;::text AS payment_provider,<br>                $1:&quot;Phone&quot;::text AS phone,<br>                $1:&quot;Delivery Address&quot;::text AS shipping_address,<br>                metadata$filename AS stg_file_name,<br>                metadata$file_row_number AS stg_row_number,<br>                metadata$file_last_modified AS stg_last_modified<br>            FROM<br>                @amazon_sales_dwh.source.data_stg/sales/source=FR/format=json/<br>                (file_format =&gt; amazon_sales_dwh.common.my_json_format)<br>        )<br>        ON_ERROR = CONTINUE<br>        &quot;&quot;&quot;,<br>}<br><br># snowpark session<br>def get_snowpark_session() -&gt; Session:<br>    &quot;&quot;&quot;Create Snowpark Session&quot;&quot;&quot;<br>    connection_parameters = {<br>        &quot;ACCOUNT&quot;: os.environ.get(&quot;ACCOUNT_ID&quot;),<br>        &quot;USER&quot;: os.environ.get(&quot;SF_USER&quot;),<br>        &quot;PASSWORD&quot;: os.environ.get(&quot;PASSWORD&quot;),<br>        &quot;ROLE&quot;: os.environ.get(&quot;ROLE&quot;),<br>        &quot;DATABASE&quot;: os.environ.get(&quot;DATABASE&quot;),<br>        &quot;SCHEMA&quot;: os.environ.get(&quot;SCHEMA&quot;),<br>        &quot;WAREHOUSE&quot;: os.environ.get(&quot;WAREHOUSE&quot;),<br>    }<br>    # creating snowflake session object<br>    return Session.builder.configs(connection_parameters).create()<br><br>def ingest_sales(session: Session, country_code: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Ingests sales orders from a staged CSV file into the respective table in the data warehouse.<br>    Parameters:<br>        session (Session): The Snowflake session object used to execute the SQL query.<br>        country_code (str): The country code of data to ingest.<br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    session.sql(COUNTRY_SQL_STATEMENTS.get(country_code, &quot;&quot;)).collect()<br><br>def main():<br>    &quot;&quot;&quot;Entrypoint&quot;&quot;&quot;<br>    # get the session object and get dataframe<br>    session = get_snowpark_session()<br>    # ingest india sales data<br>    ingest_sales(session, &quot;in&quot;)<br>    # ingest us sales data<br>    ingest_sales(session, &quot;us&quot;)<br>    # ingest france sales data<br>    ingest_sales(session, &quot;fr&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>If the script outputs correctly then data loading is successful 🎉. Feel free to comment if you face any issue while running the script.</p><p>Follow the next step <a href="https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-part-4-52f758a12774"><strong><em>here</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60e0704043a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering with SnowFlake and Amazon Sales Data: Part 2]]></title>
            <link>https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-part-2-0aea6f8b7e8c?source=rss-7329c51e441b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0aea6f8b7e8c</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[snowpark]]></category>
            <dc:creator><![CDATA[Umair Karel]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 09:25:14 GMT</pubDate>
            <atom:updated>2024-06-07T11:53:52.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing our exploration of an end-to-end ETL (Extract, Transform, Load) data pipeline for <em>Amazon Sales</em> data using Snowpark and Snowflake. In this part we will focus on working on Data Ingestion and Staging</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*nzBf3A9kHcAQlnCME69-Qg.png" /></figure><blockquote>Checkout <a href="https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-170048a368d7"><strong>Part 1</strong></a> of this series.</blockquote><h3>Where to find complete resources for the series?</h3><p>The complete resources including code and worksheets are available on my <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/"><strong>github repo</strong></a></p><h3>1. Creating Database and Schema</h3><p>Now that we have setup our working environment in <a href="https://medium.com/@umairkarel/data-engineering-with-snowflake-and-amazon-sales-data-170048a368d7"><strong>Part 1</strong></a>, We will now setup our database and schema for the development.</p><blockquote>you can find the complete worksheet for this step <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/blob/main/Snowflake%20Worksheets/2.%20Database%20and%20Schema.sql"><strong>here</strong></a></blockquote><p><strong>1. Creating Database</strong></p><p>snowflake has an easy command for creating a new database as follows.</p><pre>create database if not exists amazon_sales_dwh;</pre><p><strong>2. Creating Schemas (Layers)</strong></p><p>In this step we will create different schemas within our database to carry out different level for operations on the data. This includes different levels of cleaning and massaging of the data starting from source layer to the final consumption layer.</p><p><strong>Snowflake Schema:</strong> A <strong>schema</strong> in snowflake is bascially a logical separation of storage within a database. This storage consists of tables, views, file-formats, functions etc. This helps us to create different layers for single project within same database instead of creating multiple different databases.</p><pre>use database amazon_sales_dwh;<br><br>create schema if not exists source; -- will have source, data stage here (source layer)<br>create schema if not exists curated; -- data curation and de-duplication (curation layer)<br>create schema if not exists consumption; -- fact &amp; dimension (consumption layer)<br>create schema if not exists common; -- for file formats sequence object etc (common objects among layers)</pre><h3>2. Staging Files and Data ingestion</h3><p>For ingesting the data from different files into our tables we first need to create stage for the data, Snowflake allows internal and external stage (S3 etc.). In this demo we will be using internal stage just to keep things simple and free.</p><p><strong>Snowflake Stage:</strong> A stage is basically an area where data files are stored ( “staged”) so that the data in the files can be loaded into a table.</p><p><strong>1. Creating Stage</strong></p><pre>-- Create Stage (Internal)<br>use schema source;<br><br>create or replace stage data_stg;</pre><p><strong>2. Grant Permissions</strong></p><p>This step is important as we first need to grant permissions to new objects we created to the defined role to be used which in our case is sysadmin.</p><blockquote><strong><em>Note:</em></strong><em> Skipping this step can cause error while pushing data to the stage.</em></blockquote><pre>-- Grant permissions for all items to sysadmin (you can create and use different role too)<br>-- It is not necessary to provide &quot;ALL ON ALL&quot; permission, here I have used just for simplicity.<br><br>GRANT ALL ON ALL SCHEMAS IN DATABASE amazon_sales_dwh TO ROLE sysadmin;<br>GRANT ALL ON ALL TABLES IN SCHEMA amazon_sales_dwh.source TO ROLE sysadmin;<br>GRANT ALL ON ALL SEQUENCES IN SCHEMA amazon_sales_dwh.source TO ROLE sysadmin;<br>GRANT ALL PRIVILEGES ON STAGE data_stg TO sysadmin;</pre><p><strong>3. Uploading data to stage (Data Ingestion)</strong></p><p>Now that we have created internal stage and granted all the necessary permissions, We can now upload our data to the stage. For this we will be using a Python Script that uses SnowFlake&#39;s <strong>SnowPark</strong></p><blockquote>You can find the script <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/blob/main/step_2_stage_data.py"><strong>here</strong></a> and data files <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/tree/main/amazon-sales-data"><strong>here</strong></a></blockquote><pre>&quot;&quot;&quot;<br>Snowflake data staging script<br>&quot;&quot;&quot;<br><br>import os<br>import sys<br>import logging<br>from snowflake.snowpark import Session<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br># initiate logging at info level<br>logging.basicConfig(<br>    stream=sys.stdout,<br>    level=logging.INFO,<br>    format=&quot;%(asctime)s - %(levelname)s - %(message)s&quot;,<br>    datefmt=&quot;%I:%M:%S&quot;,<br>)<br># Stage Location<br>STAGE_LOCATION = &quot;@amazon_sales_dwh.source.data_stg&quot;<br><br># snowpark session<br>def get_snowpark_session() -&gt; Session:<br>    &quot;&quot;&quot;Create Snowpark Session&quot;&quot;&quot;<br>    connection_parameters = {<br>        &quot;ACCOUNT&quot;: os.environ.get(&quot;ACCOUNT_ID&quot;),<br>        &quot;USER&quot;: os.environ.get(&quot;SF_USER&quot;),<br>        &quot;PASSWORD&quot;: os.environ.get(&quot;PASSWORD&quot;),<br>        &quot;ROLE&quot;: os.environ.get(&quot;ROLE&quot;),<br>        &quot;DATABASE&quot;: os.environ.get(&quot;DATABASE&quot;),<br>        &quot;SCHEMA&quot;: os.environ.get(&quot;SCHEMA&quot;),<br>        &quot;WAREHOUSE&quot;: os.environ.get(&quot;WAREHOUSE&quot;),<br>    }<br>    # creating snowflake session object<br>    return Session.builder.configs(connection_parameters).create()<br><br>def traverse_directory(<br>    directory: str, file_extension: str<br>) -&gt; tuple[list[str], list[str], list[str]]:<br>    &quot;&quot;&quot;Traverse the directory to get filename, partition and local file path.<br>    Args:<br>        directory (str): The path of the directory to traverse.<br>        file_extension (str): The file extension to filter files.<br>    Returns:<br>        Tuple[List[str], List[str], List[str]]: A tuple containing three lists:<br>            - A list of filenames with the specified extension.<br>            - A list of partition directories relative to the base directory.<br>            - A list of local file paths corresponding to the filenames.<br>    &quot;&quot;&quot;<br>    local_file_path = []<br>    file_name = []  # List to store file paths<br>    partition_dir = []<br>    for root, _, files in os.walk(directory):<br>        for file in files:<br>            if file.endswith(file_extension):<br>                file_path = os.path.join(root, file)<br>                file_name.append(file)<br>                partition_dir.append(root.replace(directory, &quot;&quot;))<br>                local_file_path.append(file_path)<br>    return file_name, partition_dir, local_file_path<br><br>def upload_files(<br>    session: Session,<br>    file_names: list[str],<br>    partition_dirs: list[str],<br>    local_file_paths: list[str],<br>    stage_location: str,<br>) -&gt; None:<br>    &quot;&quot;&quot;Upload files to the Snowflake stage.<br>    Args:<br>        session (SnowflakeConnection): An active Snowflake session.<br>        file_names (List[str]): A list of filenames to be uploaded.<br>        partition_dirs (List[str]): A list of partition directories corresponding to the files.<br>        local_file_paths (List[str]): A list of local file paths for the files to be uploaded.<br>        stage_location (str): The target stage location in Snowflake.<br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    for index, file_element in enumerate(file_names):<br>        try:<br>            put_result = session.file.put(<br>                local_file_paths[index],<br>                f&quot;{stage_location}/{partition_dirs[index]}&quot;,<br>                auto_compress=False,<br>                overwrite=True,<br>                parallel=10,<br>            )<br>            logging.info(&quot;Uploaded %s =&gt; %s&quot;, file_element, put_result[0].status)<br>        except Exception as e:<br>            logging.error(&quot;Error uploading %s: %s&quot;, file_element, e)<br><br>def main():<br>    &quot;&quot;&quot;Entrypoint&quot;&quot;&quot;<br>    session = get_snowpark_session()<br>    try:<br>        logging.info(&quot;Session created successfully&quot;)<br>        # Specify the directory path to traverse<br>        directory_path = &quot;./amazon-sales-data/&quot;<br>        # Traverse directory for CSV, Parquet, and JSON files<br>        csv_file_name, csv_partition_dir, csv_local_file_path = traverse_directory(<br>            directory_path, &quot;.csv&quot;<br>        )<br>        parquet_file_name, parquet_partition_dir, parquet_local_file_path = (<br>            traverse_directory(directory_path, &quot;.parquet&quot;)<br>        )<br>        json_file_name, json_partition_dir, json_local_file_path = traverse_directory(<br>            directory_path, &quot;.json&quot;<br>        )<br>        # Upload files to Snowflake stage<br>        upload_files(<br>            session,<br>            csv_file_name,<br>            csv_partition_dir,<br>            csv_local_file_path,<br>            STAGE_LOCATION,<br>        )<br>        upload_files(<br>            session,<br>            parquet_file_name,<br>            parquet_partition_dir,<br>            parquet_local_file_path,<br>            STAGE_LOCATION,<br>        )<br>        upload_files(<br>            session,<br>            json_file_name,<br>            json_partition_dir,<br>            json_local_file_path,<br>            STAGE_LOCATION,<br>        )<br>    except Exception as e:<br>        logging.error(&quot;An error occurred: %s&quot;, e)<br>    finally:<br>        if session:<br>            session.close()<br>            logging.info(&quot;Session closed&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>If the script outputs correctly then data staging is successful 🎉. Feel free to comment if you face any issue while running the script.</p><p>You can also verify uploaded files by listing the staged files.</p><pre>-- List stage files<br>use schema source;<br>list @data_stg;</pre><p>Follow the next step <a href="https://medium.com/@umairkarel/data-engineering-with-snowflake-and-amazon-sales-data-part-3-60e0704043a0"><strong><em>here</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0aea6f8b7e8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering with SnowFlake and Amazon Sales Data]]></title>
            <link>https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-170048a368d7?source=rss-7329c51e441b------2</link>
            <guid isPermaLink="false">https://medium.com/p/170048a368d7</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Umair Karel]]></dc:creator>
            <pubDate>Fri, 31 May 2024 06:37:52 GMT</pubDate>
            <atom:updated>2024-06-06T09:31:27.460Z</atom:updated>
            <content:encoded><![CDATA[<p>In this series we’ll explore an end-to-end ETL (Extract, Transform, Load) data pipeline for <em>Amazon Sales</em> data using Snowpark and Snowflake. We will focus is on efficiently handling Amazon’s sales data, starting from loading(staging) data to creating dashboard. We will go through the journey from data curation where we&#39;ll transform and clean the data to modelling the data (dimensional modelling). We will go through each phase in detail, Stay tuned!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*G8m_mxMeRlEFDRWxRqPDzw.png" /><figcaption>Data Flow Diagram</figcaption></figure><blockquote>Come along as we delve into the key concepts for constructing a robust ETL pipeline with Snowflake.</blockquote><h3>Where to find complete resources for the series?</h3><p>The complete resources including code and worksheets are available on my GitHub Repo: <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/"><strong>here</strong></a></p><h3>1. Setting up the environment</h3><p>First of all, let’s setup our environment to work. This includes creating virtual warehouse, user, role and permissions setup.</p><blockquote>you can find the complete worksheet for this step <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering/blob/main/Snowflake%20Worksheets/1.%20Setup.sql"><strong>here</strong></a></blockquote><p><strong>1. Creating Virtual Warehouse</strong></p><p>here we will be creating a standard medium sized warehouse for our sample project which will be free for trail account.</p><pre>use role sysadmin;<br>create warehouse amazon_sales<br>    with<br>    warehouse_size = &#39;medium&#39;<br>    warehouse_type = &#39;standard&#39;<br>    auto_suspend = 60<br>    auto_resume = true<br>    min_cluster_count = 1<br>    max_cluster_count = 1;</pre><p><strong>2. Creating User</strong></p><pre>use role accountadmin;<br>create user amazon_sales_user<br>    password = &#39;Test@123#&#39;<br>    default_role = sysadmin<br>    default_secondary_roles = (&#39;ALL&#39;)<br>    must_change_password = false;</pre><p><strong>3. Granting permissions</strong></p><blockquote><strong>Note: </strong>you don’t have to use role sysadmin, you can create a separate role and use it. But here I have used sysadmin for simplicity.</blockquote><pre>grant role sysadmin to user amazon_sales_user;<br>grant USAGE on warehouse amazon_sales to role sysadmin;</pre><p><strong>4. Connecting to Snowflake with Python using Snowpark</strong></p><p>Let’s write a simple python script to connect to our Snowflake warehouse database.</p><blockquote>you can find the script (<strong>step_1_check_connection.py</strong>) and its dependency <a href="https://github.com/umairkarel/Amazon-Sales-Data-Engineering"><strong>here</strong></a> as python project with poetry dependency management.</blockquote><pre>ACCOUNT_ID=&quot;&lt;orgname&gt;-&lt;account_name&gt;&quot;<br>SF_USER=username<br>PASSWORD=password<br>ROLE=SYSADMIN<br>DATABASE=AMAZON_SALES_DWH<br>SCHEMA=SOURCE<br>WAREHOUSE=AMAZON_SALES</pre><pre>&quot;&quot;&quot;<br>    Snowflake connection script<br>&quot;&quot;&quot;<br>import os<br>import sys<br>import logging<br>from snowflake.snowpark import Session<br>from dotenv import load_dotenv<br>load_dotenv()<br><br># initiate logging at info level<br>logging.basicConfig(<br>    stream=sys.stdout,<br>    level=logging.INFO,<br>    format=&quot;%(asctime)s - %(levelname)s - %(message)s&quot;,<br>    datefmt=&quot;%I:%M:%S&quot;,<br>)<br><br># snowpark session<br>def get_snowpark_session() -&gt; Session:<br>    &quot;&quot;&quot;Create Snowpark Session&quot;&quot;&quot;<br>    connection_parameters = {<br>        &quot;ACCOUNT&quot;: os.environ.get(&quot;ACCOUNT_ID&quot;),<br>        &quot;USER&quot;: os.environ.get(&quot;SF_USER&quot;),<br>        &quot;PASSWORD&quot;: os.environ.get(&quot;PASSWORD&quot;),<br>        &quot;ROLE&quot;: os.environ.get(&quot;ROLE&quot;),<br>        &quot;DATABASE&quot;: os.environ.get(&quot;DATABASE&quot;),<br>        &quot;SCHEMA&quot;: os.environ.get(&quot;SCHEMA&quot;),<br>        &quot;WAREHOUSE&quot;: os.environ.get(&quot;WAREHOUSE&quot;),<br>    }<br>    # creating snowflake session object<br>    return Session.builder.configs(connection_parameters).create()<br><br>def main():<br>    &quot;&quot;&quot;Entrypoint&quot;&quot;&quot;<br>    session = get_snowpark_session()<br>    context_df = session.sql(<br>        &quot;&quot;&quot;<br>        select <br>            current_role(),<br>            current_database(),<br>            current_schema(),<br>            current_warehouse()<br>        &quot;&quot;&quot;<br>    )<br>    context_df.show(2)<br>    customer_df = session.sql(<br>        &quot;&quot;&quot;<br>        select<br>            c_custkey,<br>            c_name,<br>            c_phone,<br>            c_mktsegment<br>        from<br>            snowflake_sample_data.tpch_sf1.customer<br>        limit 10<br>        &quot;&quot;&quot;<br>    )<br>    customer_df.show(5)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>If the script outputs correctly then connection is <strong>successful 🎉</strong>. Feel free to comment if you face any issue while running the script.</p><p>Follow the next step <a href="https://umairkarel.medium.com/data-engineering-with-snowflake-and-amazon-sales-data-part-2-0aea6f8b7e8c"><strong><em>here</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=170048a368d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of Pointers in C]]></title>
            <link>https://umairkarel.medium.com/basics-of-pointers-in-c-ba51052a3149?source=rss-7329c51e441b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba51052a3149</guid>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Umair Karel]]></dc:creator>
            <pubDate>Wed, 26 Oct 2022 12:06:34 GMT</pubDate>
            <atom:updated>2022-10-26T12:06:34.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*T6yGtsj9U6TkXV2e4foYVg.jpeg" /></figure><p>Before digging into the pointers, let us first understand how the variables are stored into the memory and what is going on under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*Yr_mjdosXN-ir_RUpgAHRw.png" /><figcaption>RAM</figcaption></figure><p>When we talk about Computer’s memory we mostly talk about the RAM. We could think of computer’s memory or RAM as just a grid of bytes. where each of them have unique number/address associated with it. When we declare a variable it actually have the address to the memory location where the space is allocated for it. Declaring a variable let say, int x; is like saying <em>“Hey computer, please allocate me some memory to store data of type </em>int<em> and store its address in the variable </em>x<em>”</em>. so, now we know how the variables are stored and what they contains. now, the question is can’t we get the memory address of the variable? this is where the pointers comes into the picture.</p><blockquote><strong>Pointer is just a variable that stores an address of the memory location.</strong></blockquote><p>Now how do we use pointers? it turns out, In C we have operator, &amp; (Address of) which basically gives the address of particular object/variable which has to be stored in pointer variable denoted by *. Let us understand all these through an Example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*QHq2CRCuPPRU8sG9YaRJPA.png" /><figcaption>Pointers example code</figcaption></figure><p>First of all, We are initializing a variable x. then, we are using &amp;x where C is going to figure out for you what is the address of that variable(x) in the computer’s memory(RAM). Now, to store that address we need to have a variable that can store the address of another variable and not the value. which is why we use * operator. * just tells the compiler that, this is not a regular variable but the pointer variable which stores an address of something.</p><p>That’s it for now, will post more detail and advance concepts related to pointers in upcoming blogs. Stay tuned!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba51052a3149" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[But what is an API?]]></title>
            <link>https://umairkarel.medium.com/but-what-is-an-api-6d0524dda6b?source=rss-7329c51e441b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d0524dda6b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[crud-api]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Umair Karel]]></dc:creator>
            <pubDate>Thu, 28 Oct 2021 04:24:16 GMT</pubDate>
            <atom:updated>2021-10-29T04:02:26.883Z</atom:updated>
            <content:encoded><![CDATA[<p>You might have heard the word “API” and wondered “What the hell is this?”</p><p>Don’t Worry. I am there… I’ll explain the basic overview and understanding of an API in the most intuitive way. Let’s dive into it!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_9l3EqB6Oeq2OuDd-eZwSw.png" /></figure><p>API is just an acronym for <strong>Application Programming Interface</strong>. It is a software intermediary that allows two applications to talk to each other. It is the medium through which Frontend and Backend communicate with each other. Ahh, this is getting technical… I won’t go into much technical detail, let’s just keep it simple.</p><p>Let’s take an example of a Restaurant. A restaurant has two ends (applications in our definition). <strong>Frontend</strong> which is all the Tables, Chairs and decor, where the actual customer(user) sits and interacts mostly. The <strong>Backend</strong> which is the kitchen. Now, when a customer enters the restaurant it is not that the customer’s themselves will go to the kitchen(backend), get whatever they wants, go back(frontend), sit and eat. This doesn’t sound great. So, we need to have some kind of a medium to get your order to the kitchen and deliver your food back to your table. This is where the <strong>waiter</strong> comes into the picture. Yeah, you guessed it right, <strong>waiter </strong>is our <strong>API</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t3hF-LAAYzrOKgLy" /></figure><p>The waiter(API) takes your order(request) and informs the kitchen(backend). based on what you have ordered(requested) waiter deliver your food(response). Now, it sounds good. This is what an <strong>API is, a link between two endpoints/applications.</strong></p><h3>What Is CRUD?</h3><p>Now that you have a basic understanding of an API, let’s discuss CRUD functionality.</p><p>CRUD is just an acronym for Create, Read, Update &amp; Delete. These are the major functions used to interact with our database. If you know SQL you might be comfortable with Insert, Select, Update &amp; Delete. with a little nudge, CRUD are the major HTTP methods. Why are we reading this? What does it have to do with the API? The answer is simple, we use an API to implement CRUD functionalities called as <strong>CRUD API</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*zk5AJIKYjktwjqOV" /></figure><p>API communicates using HTTP protocol, where we have a set of HTTP methods mainly four POST, GET, PUT, DELETE. Let’s understand these methods using an Example of <strong>Instagram</strong>.</p><p><strong>POST</strong></p><p>When you post a photo/video/story, you are actually calling a POST request to the Instagram API with the Data to be posted as the image/video along with the caption, location and all. The post you created is now in the database. POST usually adds a new resource.</p><p><strong>GET</strong></p><p>When you open the app/website you see all the post’s shared by your followings. This is done by the GET method, the GET method gets the needed(requested) data from the database.</p><p><strong>PUT</strong></p><p>PUT is used to update a resource or data which is already present into the database. Like if you update your post’s caption, you are actually using a PUT method.</p><p><strong>DELETE</strong></p><p>This is simple. It is used to delete a resource from the database. Deleting a post, comment etc..</p><p>So that’s all for now! I hope you have a brief understanding of API and CRUD API. Now you are ready to dig deep into the technical details and implement your own API. Stay updated for my next blog!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d0524dda6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>