<?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 Sandy Lauguico on Medium]]></title>
        <description><![CDATA[Stories by Sandy Lauguico on Medium]]></description>
        <link>https://medium.com/@sclauguico?source=rss-47876a26005------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*D4-hpfFJ6IkXw0mV_jzzJw.jpeg</url>
            <title>Stories by Sandy Lauguico on Medium</title>
            <link>https://medium.com/@sclauguico?source=rss-47876a26005------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:04:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sclauguico/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[ECOM Phase 4: Building AI Agents for E-Commerce Analytics with LangGraph]]></title>
            <link>https://medium.com/@sclauguico/ecom-phase-4-building-ai-agents-for-e-commerce-analytics-with-langgraph-fd1b2471482d?source=rss-47876a26005------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd1b2471482d</guid>
            <dc:creator><![CDATA[Sandy Lauguico]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 05:28:16 GMT</pubDate>
            <atom:updated>2025-10-18T08:44:57.121Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Developing an AI-powered business and analytics consultant that analyzes e-commerce data stored in a data warehouse</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JnJzgNa3H7_IjtdLLrBVA.png" /><figcaption>ECOM Phase 4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46jtfpnP4k5AQJbAbnh_-g.png" /><figcaption>End-to-End AI Data Pipeline Diagram</figcaption></figure><h3>Introduction</h3><p>After building out the data pipeline in Phase 1, I ran into something that I think every data engineer can relate to. I had clean, well-structured data sitting in Snowflake, but turning it into meaningful insights would require going through a full Data Science Life Cycle. That’s something I plan to tackle later. While I could write SQL and build dashboards (<a href="https://medium.com/@sclauguico/ecom-phase-3-part-1-unlocking-business-value-with-sql-8ad1642107d9">ECOM Phase 3</a>), each new business question, especially one-off or ad hoc requests, often required additional queries, new visualizations, and manual analysis that wouldn’t scale and might only be used once.</p><p>That got me thinking: what if I could just talk to my data? Not literally, but close. Instead of writing out SELECT * FROM orders WHERE… every time I wanted to understand sales trends, what if I could just ask, “How are the sales trending this month?” and get back not just numbers, but meaningful insights and recommendations?</p><p>That question led me to Phase 4. I built AI agents that can analyze e-commerce data and deliver business intelligence on demand. This isn’t about replacing analysts. We still need human expertise for strategy and deep domain knowledge. But we can automate the routine exploratory “what’s happening with our metrics” kind of questions that tend to eat up time.</p><p>Using LangGraph to coordinate multiple AI agents and Claude for the analysis itself, I built a system that feels like having a data analyst on standby 24/7. Now, you can ask a question in plain English, and it pulls the right data from Snowflake, runs the analysis, and delivers actionable recommendations.</p><p>As someone who programs for a living, this isn’t about replacing the work we do, but as Andrej Karpathy said, “The hottest new programming language is English.”</p><h3>Project Vision and Scope</h3><p>Phase 4 aims to bridge the gap between data availability and business intelligence by creating an AI-powered layer that sits on top of the existing data infrastructure. The goal is to use an approach that can democratize data access for business users who need insights but shouldn’t need to write SQL or interpret complex dashboards.</p><p><strong>Key Objectives:</strong></p><ul><li>Enable natural language querying of e-commerce data</li><li>Provide intelligent analysis with common e-commerce metrics</li><li>Generate actionable business recommendations</li><li>Maintain real-time connectivity to Snowflake</li><li>Create an intuitive web interface for non-technical users</li></ul><p><strong>Prerequisites:</strong> This project requires <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1</a> to be completed first. You need a functioning Snowflake data warehouse with clean, transformed e-commerce data.</p><h3>I. Project Setup</h3><p>Accompanying <a href="https://github.com/sclauguico/ecom-ai-analyzer">GitHub repository</a> for this article</p><p>New version featuring enhanced chart generation capabilities, available in this separate <a href="https://github.com/sclauguico/ecom-ai-agents">GitHub repository</a> as demonstrated at PyCon Davao.</p><h4>1. Project Directory Structure</h4><p><strong>Steps:</strong></p><ol><li>Create the main project directory:</li></ol><pre>mkdir ecom-ai-analyzer<br>cd ecom-ai-analyzer</pre><p>2. Create the following directory structure:</p><pre>ecom-ai-analyzer/<br>├── backend/<br>│   ├── tests/<br>│   │   ├── test_integration.py<br>│   ├── .dockerignore<br>│   ├── Dockerfile<br>│   ├── test_snowflake.py<br>│   ├── tool_snowflake.py<br>│   ├── langgraph_agents.py<br>│   └── main.py<br>├── frontend/<br>│   ├── .dockerignore<br>│   ├── Dockerfile<br>│   ├── src/<br>│   │   ├── App.tsx<br>│   │   ├── App.css<br>│   │   └── index.tsx<br>│   ├── public/<br>│   │   ├── index.html<br>│   │   └── manifest.json<br>│   ├── package.json<br>│   ├── package-lock.json<br>│   └── .env<br>├── requirements.txt<br>├── .env<br>├── docker-compose.yml<br>└── README.md</pre><h4>2. Environment Setup</h4><p><strong>Steps:</strong></p><ol><li>Create a virtual environment on the root directory:</li></ol><pre>python -m venv venv # in the next AI project, I&#39;ll use uv by Astral :)<br># On Windows: <br>venv\Scripts\activate<br># On mac: <br>source venv/bin/activate</pre><p>Note: If you want to use uv, refer to this <a href="https://docs.astral.sh/uv/guides/projects/">documentation</a>. It’s like pip, but much faster!</p><p>2. Create requirements.txt:</p><pre>fastapi==0.104.1<br>uvicorn[standard]==0.24.0<br>pydantic==2.5.0<br>python-dotenv==1.0.0<br>pandas==2.0.3<br>snowflake-connector-python==3.6.0<br>langgraph&gt;=0.1.0<br>langchain&gt;=0.2.0<br>langchain-anthropic&gt;=0.1.15<br>anthropic&gt;=0.16.0<br>websockets==12.0<br>pytest==7.4.3<br>pytest-asyncio==0.21.1</pre><p>3. Install dependencies:</p><pre>  pip install -r requirements.txt</pre><p>4. Create .env file:</p><pre># Snowflake Configuration<br>SNOWFLAKE_USER=your_username<br>SNOWFLAKE_PASSWORD=your_password<br>SNOWFLAKE_ACCOUNT=your_account_id<br>SNOWFLAKE_WAREHOUSE=ECOM_WH<br>SNOWFLAKE_DATABASE=ECOM_DB<br>SNOWFLAKE_RAW_SCHEMA=ECOM_RAW<br>SNOWFLAKE_ROLE=ECOM_ROLE<br><br># Anthropic Configuration<br>ANTHROPIC_API_KEY=your_anthropic_api_key</pre><p><strong>Note:</strong> Don’t share your .env file. Add it to .gitignore.</p><p>Sample .gitignore. Place file on root directory. This excludes listed files when pushing to Git.</p><pre>.git<br>.env<br>venv/<br>__pycache__/<br>.DS_Store</pre><h3>II. Database Connection Setup</h3><h4>1. Snowflake Tools</h4><p><strong>Steps:</strong></p><ol><li>Create backend/test_snowflake.py:</li></ol><pre># Import libraries<br>import os<br>import snowflake.connector<br>import pandas as pd<br>from dotenv import load_dotenv<br><br># Load .env<br>load_dotenv(override=True) <br><br>def test_connection():<br>    conn = snowflake.connector.connect(<br>        user=os.getenv(&#39;SNOWFLAKE_USER&#39;),<br>        password=os.getenv(&#39;SNOWFLAKE_PASSWORD&#39;),<br>        account=os.getenv(&#39;SNOWFLAKE_ACCOUNT&#39;),<br>        warehouse=os.getenv(&#39;SNOWFLAKE_WAREHOUSE&#39;),<br>        database=os.getenv(&#39;SNOWFLAKE_DATABASE&#39;),<br>        schema=os.getenv(&#39;SNOWFLAKE_RAW_SCHEMA&#39;),<br>        role=os.getenv(&#39;SNOWFLAKE_ROLE&#39;),<br>        insecure_mode=True,<br>    )<br>    <br>    cursor = conn.cursor()<br>    <br>    # Test basic connection<br>    cursor.execute(&quot;SELECT CURRENT_VERSION()&quot;)<br>    print(f&quot;Snowflake version: {cursor.fetchone()[0]}&quot;)<br>    <br>    # Check available tables<br>    cursor.execute(&quot;SHOW TABLES&quot;)<br>    tables = cursor.fetchall()<br>    print(f&quot;Found {len(tables)} tables:&quot;)<br>    for table in tables[:8]:<br>        print(f&quot;  - {table[1]}&quot;)<br>    <br>    # Test sample data from orders<br>    cursor.execute(&quot;SELECT COUNT(*) FROM ORDERS&quot;)<br>    order_count = cursor.fetchone()[0]<br>    print(f&quot;\nTotal orders: {order_count}&quot;)<br>    <br>    cursor.execute(&quot;SELECT * FROM ORDERS LIMIT 3&quot;)<br>    sample_orders = cursor.fetchall()<br>    print(&quot;\nSample orders:&quot;)<br>    for order in sample_orders:<br>        print(f&quot;  Order ID: {order[0]}, Total: ${order[4]}&quot;)<br>    <br>    cursor.close()<br>    conn.close()<br>    print(&quot;\nConnection test successful!&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    test_connection()</pre><p>2. Test the connection. Ensure venv is activated before running:</p><pre>cd backend<br>python test_snowflake.py</pre><p>Sample output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*Vd_REzCjqTe7kErmFOHPZg.png" /><figcaption>Test Snowflake Connection</figcaption></figure><p>3. Create backend/tool_snowflake.py:</p><pre># Import libraries<br>import json<br>import pandas as pd<br>import snowflake.connector<br>from datetime import datetime, timedelta<br>from typing import Dict, Any<br>import os<br>from dotenv import load_dotenv<br><br># Load .env<br>load_dotenv(override=True)<br><br># Define SnowflakeTools<br>class SnowflakeTools:<br>    def __init__(self):<br>        self.conn = snowflake.connector.connect(<br>            user=os.getenv(&#39;SNOWFLAKE_USER&#39;),<br>            password=os.getenv(&#39;SNOWFLAKE_PASSWORD&#39;),<br>            account=os.getenv(&#39;SNOWFLAKE_ACCOUNT&#39;),<br>            warehouse=os.getenv(&#39;SNOWFLAKE_WAREHOUSE&#39;),<br>            database=os.getenv(&#39;SNOWFLAKE_DATABASE&#39;),<br>            schema=os.getenv(&#39;SNOWFLAKE_RAW_SCHEMA&#39;),<br>            role=os.getenv(&#39;SNOWFLAKE_ROLE&#39;),<br>            insecure_mode=True,<br>        )<br>    <br>    # Function for getting the sales metrics<br>    def get_sales_metrics(self, days: int = 30) -&gt; Dict[str, Any]:<br>        cursor = self.conn.cursor()<br>        end_date = datetime.now()<br>        start_date = end_date - timedelta(days=days)<br>        <br>        query = &quot;&quot;&quot;<br>        SELECT <br>            COUNT(*) as total_orders,<br>            SUM(total_amount) as total_revenue,<br>            AVG(total_amount) as avg_order_value,<br>            COUNT(DISTINCT customer_id) as unique_customers<br>        FROM orders <br>        WHERE order_date &gt;= %s AND order_date &lt;= %s<br>        &quot;&quot;&quot;<br>        <br>        cursor.execute(query, (start_date, end_date))<br>        result = cursor.fetchone()<br>        <br>        return {<br>            &quot;period_days&quot;: days,<br>            &quot;total_orders&quot;: result[0] or 0,<br>            &quot;total_revenue&quot;: float(result[1] or 0),<br>            &quot;avg_order_value&quot;: float(result[2] or 0),<br>            &quot;unique_customers&quot;: result[3] or 0<br>        }<br>    <br>    # Function for getting the top products<br>    def get_top_products(self, no_products: int = 10) -&gt; Dict[str, Any]:<br>        cursor = self.conn.cursor()<br>        <br>        query = &quot;&quot;&quot;<br>        SELECT <br>            p.product_name,<br>            SUM(oi.quantity) as total_sold,<br>            SUM(oi.total_price) as total_revenue,<br>            COUNT(DISTINCT oi.order_id) as orders_count<br>        FROM order_items oi<br>        JOIN products p ON oi.product_id = p.product_id<br>        GROUP BY p.product_id, p.product_name<br>        ORDER BY total_revenue DESC<br>        LIMIT %s<br>        &quot;&quot;&quot;<br>        <br>        cursor.execute(query, (no_products,))<br>        results = cursor.fetchall()<br>        <br>        products = []<br>        for row in results:<br>            products.append({<br>                &quot;product_name&quot;: row[0],<br>                &quot;total_sold&quot;: row[1],<br>                &quot;total_revenue&quot;: float(row[2]),<br>                &quot;orders_count&quot;: row[3]<br>            })<br>        <br>        return {&quot;top_products&quot;: products}<br>    <br>    # Function for defining customer segments (simple example based on income)<br>    def get_customer_segments(self) -&gt; Dict[str, Any]:<br>        cursor = self.conn.cursor()<br>        <br>        query = &quot;&quot;&quot;<br>        SELECT <br>            CASE <br>                WHEN annual_income &gt;= 80000 THEN &#39;High Value&#39;<br>                WHEN annual_income &gt;= 50000 THEN &#39;Mid Value&#39;<br>                ELSE &#39;Low Value&#39;<br>            END as segment,<br>            COUNT(*) as customer_count,<br>            AVG(annual_income) as avg_income<br>        FROM customers<br>        WHERE is_active = TRUE<br>        GROUP BY segment<br>        ORDER BY avg_income DESC<br>        &quot;&quot;&quot;<br>        <br>        cursor.execute(query)<br>        results = cursor.fetchall()<br>        <br>        segments = []<br>        for row in results:<br>            segments.append({<br>                &quot;segment&quot;: row[0],<br>                &quot;customer_count&quot;: row[1],<br>                &quot;avg_income&quot;: float(row[2])<br>            })<br>        <br>        return {&quot;customer_segments&quot;: segments}<br><br># Function for testing SnowflakeTools class and its functions<br>def test_tools():<br>    tools = SnowflakeTools()<br>    <br>    print(&quot;Testing sales metrics:&quot;)<br>    sales = tools.get_sales_metrics(30) # Set days parameter and pass in any number as argument, setting 30 for this project limit<br>    print(json.dumps(sales, indent=2))<br>    <br>    print(&quot;\nTesting top products:&quot;)<br>    products = tools.get_top_products(5) # Set no_products parameter and pass in any number as argument, setting 10 for this project limit<br>    print(json.dumps(products, indent=2))<br>    <br>    print(&quot;\nTesting customer segments:&quot;)<br>    segments = tools.get_customer_segments()<br>    print(json.dumps(segments, indent=2))<br><br>if __name__ == &quot;__main__&quot;:<br>    # Run test_tools<br>    test_tools()</pre><p>Sample output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*mJUf-RTR_QMwdL7Y6ug-qA.png" /><figcaption>Snowflake Tool Output</figcaption></figure><p><strong>Note:</strong> As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><p>4. Run the Snowflake tool:</p><pre>cd backend # If not yet on this directory<br>python tool_snowflake.py</pre><p><strong>Tip:</strong> Commit frequently when adding a Python script, and push at natural breakpoints or end of work sessions. I used to practice creating separate branches, creating PRs, and merging as well even when working alone.</p><p>For this project, I am just pushing directly to main. My sample Git workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fLMBGnbjD8vi6N8J9OlwCg.png" /><figcaption>Sample Git Workflow</figcaption></figure><h3>III. AI Agents Setup</h3><h4>1. LangGraph Agents</h4><p>Refer to this mermaid diagram for building the Agents and Tools with LangGraph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*Qua19BwS7VGhgYJ4GCDu4Q.png" /><figcaption>Mermaid Diagram of AI Agents and Tools</figcaption></figure><p>Note: The arrows from the Data Extractor Agent to the tools represent conditional edges and are not shown in the diagram. For a more accurate representation, please refer to <a href="https://github.com/sclauguico/ecom-ai-analyzer/blob/main/backend/workflow.png">this diagram</a> rendered in IPython.</p><p><strong>Steps:</strong></p><ol><li>Create backend/langgraph_agents.py:</li></ol><pre># Import libraries<br>from typing import TypedDict, Dict, Any<br>from langchain_anthropic import ChatAnthropic<br>from langgraph.graph import StateGraph, END<br>from langgraph.checkpoint.memory import MemorySaver<br>from tool_snowflake import SnowflakeTools<br>import json<br>import os<br>from dotenv import load_dotenv<br><br># Load .env<br>load_dotenv(override=True)<br><br># Define the structure for storing input query, retrieved data, and AI-generated insights<br>class AnalysisState(TypedDict):<br>    query: str<br>    data: Dict[str, Any]<br>    analysis: str<br>    recommendations: str<br>    next_action: str<br>    step_count: int<br>    finished: bool<br><br># Define the EcommerceAgents class: Blueprint for creating the agents and tools<br>class EcommerceAgents:<br>    # Define the constructor that runs automatically when an object is instantiated from this class<br>    def __init__(self):<br>        self.llm = ChatAnthropic(<br>            model=&quot;claude-3-sonnet-20240229&quot;, # Define a model. Claude Sonnet is my fave!<br>            api_key=os.getenv(&#39;ANTHROPIC_API_KEY&#39;)<br>        )<br>        # Instantiate supporting objects used by these classes<br>        self.tools = SnowflakeTools()<br>        self.memory = MemorySaver()<br>        self.graph = self._build_graph()<br>    <br>    # Define class methods: Extractor Agent<br>    def data_extractor_agent(self, state: AnalysisState) -&gt; AnalysisState:<br>        query_lower = state[&#39;query&#39;].lower()<br>        <br>        if not state[&#39;data&#39;]:<br>            if &#39;sales&#39; in query_lower or &#39;revenue&#39; in query_lower:<br>                state[&quot;next_action&quot;] = &quot;get_sales_metrics&quot;<br>            elif &#39;product&#39; in query_lower:<br>                state[&quot;next_action&quot;] = &quot;get_top_products&quot;<br>            else:<br>                state[&quot;next_action&quot;] = &quot;get_sales_metrics&quot;<br>        elif len(state[&#39;data&#39;]) == 1:<br>            if &#39;product&#39; in query_lower and &#39;top_products&#39; not in state[&#39;data&#39;]:<br>                state[&quot;next_action&quot;] = &quot;get_top_products&quot;<br>            elif &#39;customer&#39; in query_lower and &#39;customer_segments&#39; not in state[&#39;data&#39;]:<br>                state[&quot;next_action&quot;] = &quot;get_customer_segments&quot;<br>            else:<br>                state[&quot;next_action&quot;] = &quot;analyst_agent&quot;<br>        else:<br>            state[&quot;next_action&quot;] = &quot;analyst_agent&quot;<br>        <br>        state[&quot;step_count&quot;] += 1<br>        return state<br>    <br>    # Define class methods: Analyst Agent<br>    def analyst_agent(self, state: AnalysisState) -&gt; AnalysisState:<br>        if not state[&#39;data&#39;]:<br>            state[&quot;next_action&quot;] = &quot;data_extractor_agent&quot;<br>        else:<br>            data_str = json.dumps(state[&quot;data&quot;], indent=2)<br>            analyze_prompt = f&quot;&quot;&quot;<br>            Analyze this data for: {state[&#39;query&#39;]}\nData: {data_str}\n<br>            Provide 3 clear analysis in bullet points focusing on:<br>            1. Key metrics and trends<br>            2. Notable patterns or outliers<br>            3. Data-driven observations<br>            <br>            Keep the analysis factual and specific.<br>            Make your responses short and concise.<br>            &quot;&quot;&quot;<br>            <br>            response = self.llm.invoke(analyze_prompt)<br>            state[&quot;analysis&quot;] = response.content<br>            state[&quot;next_action&quot;] = &quot;consultant_agent&quot;<br>        <br>        state[&quot;step_count&quot;] += 1<br>        return state<br>    <br>    # Define class methods: Consultant Agent<br>    def consultant_agent(self, state: AnalysisState) -&gt; AnalysisState:<br>        prompt = f&quot;&quot;&quot;<br>        Based on analysis: {state[&#39;analysis&#39;]}\n<br>        <br>        Provide 3 specific business recommendations in bullet points<br>        <br>        Focus on actionable recommendations that can improve:<br>        - Revenue growth<br>        - Customer retention<br>        - Operational efficiency<br>        <br>        Be specific and practical. Make your responses short and concise.&quot;&quot;&quot;<br>        <br>        response = self.llm.invoke(prompt)<br>        state[&quot;recommendations&quot;] = response.content<br>        state[&quot;finished&quot;] = True<br>        state[&quot;step_count&quot;] += 1<br>        return state<br>    <br>    # Define class methods: Get sales metrics tool from SnowflakeTools class<br>    def get_sales_metrics_tool(self, state: AnalysisState) -&gt; AnalysisState:<br>        result = self.tools.get_sales_metrics()<br>        state[&quot;data&quot;][&quot;sales_metrics&quot;] = result<br>        return state<br>    <br>    # Define class methods: Get top products tool from SnowflakeTools class<br>    def get_top_products_tool(self, state: AnalysisState) -&gt; AnalysisState:<br>        result = self.tools.get_top_products()<br>        state[&quot;data&quot;][&quot;top_products&quot;] = result<br>        return state<br>    <br>    # Define class methods: Get customer segments tool from SnowflakeTools class<br>    def get_customer_segments_tool(self, state: AnalysisState) -&gt; AnalysisState:<br>        result = self.tools.get_customer_segments()<br>        state[&quot;data&quot;][&quot;customer_segments&quot;] = result<br>        return state<br>    <br>    # Define class methods: router, for directing the flow of the agent system based on the current state object<br>    # This method returns the name of the next method (or node) to invoke<br>    # It behaves like a decision controller for the AI agents<br>    def router(self, state: AnalysisState) -&gt; str:<br>        if state[&quot;finished&quot;] or state[&quot;step_count&quot;] &gt;= 10:<br>            return &quot;end&quot;<br>        <br>        action = state.get(&quot;next_action&quot;, &quot;&quot;)<br>        <br>        if action == &quot;analyst_agent&quot;:<br>            return &quot;analyst_agent&quot;<br>        elif action == &quot;consultant_agent&quot;:<br>            return &quot;consultant_agent&quot;<br>        elif action == &quot;get_sales_metrics&quot;:<br>            return &quot;get_sales_metrics&quot;<br>        elif action == &quot;get_top_products&quot;:<br>            return &quot;get_top_products&quot;<br>        elif action == &quot;get_customer_segments&quot;:<br>            return &quot;get_customer_segments&quot;<br>        else:<br>            return &quot;data_extractor_agent&quot;<br>    <br>    # Define a private method: _build_graph<br>    # This method constructs and returns the StateGraph object, the control flow<br>    # for how the AI agents (class methods) interact. The graph is part of this class&#39;s internal logic<br>    # and encapsulates the decision routing between agents.<br>    def _build_graph(self):<br>        workflow = StateGraph(AnalysisState)<br>        <br>        workflow.add_node(&quot;data_extractor_agent&quot;, self.data_extractor_agent)<br>        workflow.add_node(&quot;analyst_agent&quot;, self.analyst_agent)<br>        workflow.add_node(&quot;consultant_agent&quot;, self.consultant_agent)<br>        workflow.add_node(&quot;get_sales_metrics&quot;, self.get_sales_metrics_tool)<br>        workflow.add_node(&quot;get_top_products&quot;, self.get_top_products_tool)<br>        workflow.add_node(&quot;get_customer_segments&quot;, self.get_customer_segments_tool)<br>        <br>        # Define the entry point, the first agent to run when the graph is invoked<br>        workflow.set_entry_point(&quot;data_extractor_agent&quot;)<br>        <br>        # Define conditional transitions based on the router method (a class method used as a controller)<br>        workflow.add_conditional_edges(<br>            &quot;data_extractor_agent&quot;,<br>            self.router,<br>            {<br>                &quot;get_sales_metrics&quot;: &quot;get_sales_metrics&quot;,<br>                &quot;get_top_products&quot;: &quot;get_top_products&quot;,<br>                &quot;get_customer_segments&quot;: &quot;get_customer_segments&quot;,<br>                &quot;analyst_agent&quot;: &quot;analyst_agent&quot;,<br>                &quot;data_extractor_agent&quot;: &quot;data_extractor_agent&quot;,<br>                &quot;end&quot;: END<br>            }<br>        )<br>        <br>        workflow.add_conditional_edges(<br>            &quot;analyst_agent&quot;,<br>            self.router,<br>            {<br>                &quot;consultant_agent&quot;: &quot;consultant_agent&quot;,<br>                &quot;data_extractor_agent&quot;: &quot;data_extractor_agent&quot;,<br>                &quot;end&quot;: END<br>            }<br>        )<br>        <br>        workflow.add_conditional_edges(<br>            &quot;consultant_agent&quot;,<br>            self.router,<br>            {<br>                &quot;end&quot;: END<br>            }<br>        )<br>        <br>        # Add fixed transitions back to the extractor after tool use, loop-like behavior<br>        workflow.add_edge(&quot;get_sales_metrics&quot;, &quot;data_extractor_agent&quot;)<br>        workflow.add_edge(&quot;get_top_products&quot;, &quot;data_extractor_agent&quot;)<br>        workflow.add_edge(&quot;get_customer_segments&quot;, &quot;data_extractor_agent&quot;)<br>        <br>        return workflow.compile(checkpointer=self.memory)<br>    <br>    # Define the analyze method: this is the public interface (exposed behavior)<br>    # that users interact with when they want to run a query through the agent system<br>    def analyze(self, query: str, thread_id: str = &quot;default&quot;) -&gt; Dict[str, Any]:<br>        config = {&quot;configurable&quot;: {&quot;thread_id&quot;: thread_id}}<br>        <br>        # Instantiate the initial state object, includes query and default values<br>        initial_state = AnalysisState(<br>            query=query,<br>            data={},<br>            analysis=&quot;&quot;,<br>            recommendations=&quot;&quot;,<br>            next_action=&quot;&quot;,<br>            step_count=0,<br>            finished=False<br>        )<br>        <br>        # Invoke the graph (object behavior) using the configured settings and state<br>        result = self.graph.invoke(initial_state, config=config)<br>        <br>        # Return a dictionary of output, a structured response from the AI agents<br>        return {<br>            &quot;query&quot;: result[&quot;query&quot;],<br>            &quot;total_steps&quot;: result[&quot;step_count&quot;],<br>            &quot;data&quot;: result[&quot;data&quot;],<br>            &quot;analysis&quot;: result[&quot;analysis&quot;],<br>            &quot;recommendations&quot;: result[&quot;recommendations&quot;]<br>        }<br><br>def test_agents_and_tools():<br>    # Instantitate agents object from Ecommerce Agent class<br>    agents = EcommerceAgents()<br>    # Invoke analyze method<br>    result = agents.analyze(&quot;What are the sales and top products?&quot;) # Add the user question as argument for the query parameter<br>    print(f&quot;Steps: {result[&#39;total_steps&#39;]}&quot;) # Output number of steps taken<br>    print(f&quot;Data: {list(result[&#39;data&#39;].keys())}&quot;) # Output result data keys<br><br>if __name__ == &quot;__main__&quot;:<br>    test_agents_and_tools()</pre><p>2. Test the agents:</p><pre>cd backend<br>python langgraph_agents.py</pre><p><strong>Side story:</strong> As you may notice in the code comments, I love using words like <em>class</em>, <em>object</em>, <em>function</em>, <em>method,</em> <em>constructor</em>, <em>parameter</em>, and <em>argument</em>, and even fancy ones like <em>instantiate</em>. It helps reinforce my understanding of how object-oriented programming (OOP) works, and keeps the mental model fresh every time.</p><h3>IV. FastAPI Backend Setup</h3><h4>1. API Development</h4><p><strong>Steps:</strong></p><ol><li>Create backend/main.py:</li></ol><pre># Import libraries<br>from fastapi import FastAPI<br>from fastapi.middleware.cors import CORSMiddleware<br>from pydantic import BaseModel # BaseModel is a superclass for defining data models<br>from langgraph_agents import EcommerceAgents # Self-defined / custom class from langgraph_agents.py<br>from tool_snowflake import SnowflakeTools # Self-defined / custom class from tool_snowflake.py<br>import uvicorn<br>import asyncio<br>from concurrent.futures import ThreadPoolExecutor<br><br># Instantiate the FastAPI application class to create FastAPI object app<br>app = FastAPI(title=&quot;E-Commerce AI Agents Analyzer API&quot;)<br><br># Add middleware to the app using a method of the app instance<br>app.add_middleware(<br>    CORSMiddleware, # Class used to handle cross-origin requests<br>    allow_origins=[&quot;http://localhost:3000&quot;], # Parameters passed to the constructor and arguments (actual values) added to parameters<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br># Instantiate classes to create objects<br>agents = EcommerceAgents() # Constructor of EcommerceAgents is invoked<br>tools = SnowflakeTools() # Constructor of SnowflakeTools is invoked<br>executor = ThreadPoolExecutor(max_workers=4) # ThreadPoolExecutor object instantiated<br><br># Define a data model using class which inherits from Pydantic&#39;s BaseModel<br>class AnalysisRequest(BaseModel):<br>    query: str # Attribute (parameter) of the class<br><br># Another data model class used for response formatting<br>class QuickInsight(BaseModel):<br>    metric: str # Class parameters<br>    value: str<br>    trend: str<br><br># Define a method which is an asynchronous function to check API health<br># Decorator: @app.get registers this method to respond to HTTP GET requests at &quot;/health&quot;<br>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    return {&quot;status&quot;: &quot;healthy&quot;, &quot;service&quot;: &quot;ecommerce-ai-agents-analyzer&quot;}<br><br># Define another method for the /quick-insights endpoint<br># Decorator: @app.get binds this method to a route for GET requests<br>@app.get(&quot;/quick-insights&quot;)<br>async def get_quick_insights():<br>    def get_insights(): # Inner function, used in executor thread<br>        # Method invocations on the &#39;tools&#39; object<br>        sales = tools.get_sales_metrics(30)<br>        products = tools.get_top_products(3)<br>        segments = tools.get_customer_segments()<br>        <br>        # Return list of instantiated QuickInsight objects which are passing arguments to constructor<br>        return [<br>            QuickInsight(<br>                metric=&quot;Total Revenue (30 days)&quot;,<br>                value=f&quot;${sales[&#39;total_revenue&#39;]:,.2f}&quot;,<br>                trend=f&quot;{sales[&#39;total_orders&#39;]} orders&quot;<br>            ),<br>            QuickInsight(<br>                metric=&quot;Top Product&quot;,<br>                value=products[&#39;top_products&#39;][0][&#39;product_name&#39;] if products[&#39;top_products&#39;] else &quot;N/A&quot;,<br>                trend=f&quot;${products[&#39;top_products&#39;][0][&#39;total_revenue&#39;]:,.2f}&quot; if products[&#39;top_products&#39;] else &quot;N/A&quot;<br>            ),<br>            QuickInsight(<br>                metric=&quot;Active Customers&quot;,<br>                value=str(sum(seg[&#39;customer_count&#39;] for seg in segments[&#39;customer_segments&#39;])),<br>                trend=&quot;Across all segments&quot;<br>            )<br>        ]<br>    <br>    # Use asyncio to run blocking function in a separate thread using event loop<br>    loop = asyncio.get_event_loop()<br>    insights = await loop.run_in_executor(executor, get_insights)<br>    return {&quot;insights&quot;: insights}<br><br># Define a method that handles POST requests and accepts a class instance as a parameter<br># Decorator: @app.post binds this method to HTTP POST requests at the &quot;/analyze&quot; route<br>@app.post(&quot;/analyze&quot;)<br>async def analyze_data(request: AnalysisRequest): # Method takes in a parameter of type AnalysisRequest<br>    def run_analysis(): # Inner function (non-async) to run in thread<br>        return agents.analyze(request.query) # Method call on the &#39;agents&#39; class instance<br>    <br>    loop = asyncio.get_event_loop()<br>    result = await loop.run_in_executor(executor, run_analysis)<br>    <br>    # Structured response, includes data returned from the analyze method<br>    return {<br>        &quot;analysis_id&quot;: &quot;temp_id&quot;,<br>        &quot;query&quot;: result[&quot;query&quot;],<br>        &quot;status&quot;: &quot;completed&quot;,<br>        &quot;results&quot;: {<br>            &quot;total_steps&quot;: result[&quot;total_steps&quot;],<br>            &quot;data&quot;: result[&quot;data&quot;],<br>            &quot;analysis&quot;: result[&quot;analysis&quot;],<br>            &quot;recommendations&quot;: result[&quot;recommendations&quot;]<br>        }<br>    }<br><br># Main entry point of the script when executed directly<br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;Starting E-Commerce AI Agents Analyzer API...&quot;)<br>    # Start the web server: method call that runs the FastAPI app<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><p>2. Test the API:</p><pre>cd backend<br>python main.py</pre><p>3. Visit http://localhost:8000/docs to see the API documentation.</p><p>You can test the API endpoints using any of these three approaches:</p><p><strong>Method 1: FastAPI Documentation (Recommended)</strong></p><ul><li>Go to `http://localhost:8000/docs`</li><li>Test the `/health` endpoint directly in the browser interface</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hV-R7t_VTQmZHB6V6O0POw.png" /><figcaption>Testing the API on the FastAPI Docs</figcaption></figure><p><strong>Method 2: Postman</strong></p><ul><li>Open <a href="https://www.postman.com/">Postman</a></li><li>Create a GET request to `http://localhost:8000/quick-insights`</li><li>Send the request to see the dashboard metrics</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*7WD3AjtPIdccHW9l8c0bgw.png" /><figcaption>Testing the API on Postman</figcaption></figure><p><strong>Method 3: Terminal/Command Line</strong></p><ul><li>Open your terminal</li><li>Run the following curl command:</li></ul><pre>curl -X POST http://localhost:8000/analyze \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;query&quot;: &quot;Which customer segments should we focus our marketing efforts to?&quot;}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*l5gFSXQWILQ0umWIGaX5VA.png" /><figcaption>Testing the API on the Terminal</figcaption></figure><h3>V. React Frontend Setup</h3><h4>1. Frontend Development</h4><p><strong>Steps:</strong></p><ol><li>Initialize React app:</li></ol><pre>cd frontend<br>npx create-react-app . # template typescript<br># Enter y when prompted<br>npm install axios</pre><p>2. Create src/App.tsx:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br>import &#39;./App.css&#39;;<br><br>const API_BASE = &#39;http://localhost:8000&#39;;<br><br>interface QuickInsight {<br>  metric: string;<br>  value: string;<br>  trend: string;<br>}<br><br>interface AnalysisResult {<br>  analysis_id: string;<br>  query: string;<br>  status: string;<br>  results?: {<br>    data: any;<br>    analysis: string;<br>    recommendations: string;<br>  };<br>}<br><br>function QuickInsights() {<br>  const [insights, setInsights] = useState&lt;QuickInsight[]&gt;([]);<br>  const [loading, setLoading] = useState(true);<br><br>  useEffect(() =&gt; {<br>    // TODO: add retry logic if this fails<br>    axios.get(`${API_BASE}/quick-insights`)<br>      .then(response =&gt; {<br>        console.log(&#39;Got insights:&#39;, response.data);<br>        setInsights(response.data.insights);<br>        setLoading(false);<br>      })<br>      .catch(error =&gt; {<br>        console.error(&#39;Failed to fetch insights:&#39;, error);<br>        setLoading(false);<br>      });<br>  }, []);<br><br>  if (loading) {<br>    return (<br>      &lt;div className=&quot;loading-container&quot;&gt;<br>        &lt;div className=&quot;spinner&quot;&gt;&lt;/div&gt;<br>        &lt;div className=&quot;loading-text&quot;&gt;Loading insights...&lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  return (<br>    &lt;div className=&quot;insights-grid&quot;&gt;<br>      {insights.map((insight, i) =&gt; (<br>        &lt;div key={i} className=&quot;insight-card&quot;&gt;<br>          &lt;div className=&quot;card-accent&quot;&gt;&lt;/div&gt;<br>          &lt;div className=&quot;metric-label&quot;&gt;{insight.metric}&lt;/div&gt;<br>          &lt;div className=&quot;metric-value&quot;&gt;{insight.value}&lt;/div&gt;<br>          &lt;div className=&quot;metric-trend&quot;&gt;<br>            &lt;span&gt;▲&lt;/span&gt; {insight.trend}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>function AnalysisChat() {<br>  const [query, setQuery] = useState(&#39;&#39;);<br>  const [result, setResult] = useState&lt;AnalysisResult | null&gt;(null);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(&#39;&#39;);<br><br>  const handleSubmit = async () =&gt; {<br>    if (!query.trim()) return;<br>    <br>    setLoading(true);<br>    setError(&#39;&#39;);<br>    setResult(null);<br><br>    try {<br>      console.log(&#39;Sending query:&#39;, query);<br>      const response = await axios.post(`${API_BASE}/analyze`, { query });<br>      setResult(response.data);<br>      console.log(&#39;Analysis complete:&#39;, response.data);<br>    } catch (err) {<br>      console.error(&#39;Analysis failed:&#39;, err);<br>      setError(&#39;Something went wrong. Try again?&#39;);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };<br><br>  const handleKeyPress = (e: React.KeyboardEvent) =&gt; {<br>    if (e.key === &#39;Enter&#39;) {<br>      handleSubmit();<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;analysis-container&quot;&gt;<br>      &lt;div className=&quot;query-box&quot;&gt;<br>        &lt;div className=&quot;input-group&quot;&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            placeholder=&quot;Ask about your e-commerce data...&quot;<br>            value={query}<br>            onChange={(e) =&gt; setQuery(e.target.value)}<br>            onKeyPress={handleKeyPress}<br>            className=&quot;query-input&quot;<br>          /&gt;<br>          &lt;button<br>            onClick={handleSubmit}<br>            disabled={loading}<br>            className={`analyze-btn ${loading ? &#39;loading&#39; : &#39;&#39;}`}<br>          &gt;<br>            {loading ? (<br>              &lt;span className=&quot;btn-loading&quot;&gt;<br>                &lt;div className=&quot;btn-spinner&quot;&gt;&lt;/div&gt;<br>                Analyzing...<br>              &lt;/span&gt;<br>            ) : &#39;Analyze&#39;}<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br><br>      {error &amp;&amp; (<br>        &lt;div className=&quot;error-box&quot;&gt;<br>          &lt;span&gt;⚠&lt;/span&gt; {error}<br>        &lt;/div&gt;<br>      )}<br><br>      {result &amp;&amp; (<br>        &lt;div className=&quot;results-panel&quot;&gt;<br>          &lt;div className=&quot;results-header&quot;&gt;<br>            &lt;div className=&quot;query-title&quot;&gt;Query: {result.query}&lt;/div&gt;<br>            &lt;span className=&quot;status-badge&quot;&gt;{result.status}&lt;/span&gt;<br>          &lt;/div&gt;<br><br>          {result.results &amp;&amp; (<br>            &lt;div className=&quot;results-content&quot;&gt;<br>              &lt;div className=&quot;result-section&quot;&gt;<br>                &lt;h3&gt;Analysis&lt;/h3&gt;<br>                &lt;div className=&quot;result-text&quot;&gt;<br>                  {result.results.analysis}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br><br>              &lt;div className=&quot;result-section&quot;&gt;<br>                &lt;h3&gt;Recommendations&lt;/h3&gt;<br>                &lt;div className=&quot;result-text&quot;&gt;<br>                  {result.results.recommendations}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br><br>              &lt;div className=&quot;result-section&quot;&gt;<br>                &lt;h3&gt;Raw Data&lt;/h3&gt;<br>                &lt;div className=&quot;raw-data&quot;&gt;<br>                  &lt;pre&gt;{JSON.stringify(result.results.data, null, 2)}&lt;/pre&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>function App() {<br>  const [activeTab, setActiveTab] = useState(&#39;insights&#39;);<br><br>  return (<br>    &lt;div className=&quot;app&quot;&gt;<br>      &lt;div className=&quot;background-effects&quot;&gt;&lt;/div&gt;<br>      <br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;header className=&quot;header&quot;&gt;<br>          &lt;h1 className=&quot;title&quot;&gt;E-COMMERCE AI ANALYZER&lt;/h1&gt;<br>          &lt;p className=&quot;subtitle&quot;&gt;<br>            AI-powered insights from your Snowflake data warehouse<br>          &lt;/p&gt;<br>        &lt;/header&gt;<br><br>        &lt;div className=&quot;tab-nav&quot;&gt;<br>          &lt;div className=&quot;tab-container&quot;&gt;<br>            &lt;button<br>              onClick={() =&gt; setActiveTab(&#39;insights&#39;)}<br>              className={`tab ${activeTab === &#39;insights&#39; ? &#39;active&#39; : &#39;&#39;}`}<br>            &gt;<br>              Quick Insights<br>            &lt;/button&gt;<br>            &lt;button<br>              onClick={() =&gt; setActiveTab(&#39;analysis&#39;)}<br>              className={`tab ${activeTab === &#39;analysis&#39; ? &#39;active&#39; : &#39;&#39;}`}<br>            &gt;<br>              AI Analysis<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;main className=&quot;content&quot;&gt;<br>          {activeTab === &#39;insights&#39; &amp;&amp; &lt;QuickInsights /&gt;}<br>          {activeTab === &#39;analysis&#39; &amp;&amp; &lt;AnalysisChat /&gt;}<br>        &lt;/main&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>3. Add App.css</p><pre>@import url(https://medium.com/&#39;https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&amp;family=Inter:wght@400;500;600;700&amp;display=swap&#39;);<br><br>:root {<br>  --primary: #29b5e8;<br>  --secondary: #24a0cc;<br>  --accent: #00d4ff;<br>  --success: #4ade80;<br>  --warning: #f59e0b;<br>  --bg: #0a0a0a;<br>  --bg-card: #111111;<br>  --bg-hover: #1a1a1a;<br>  --border: #333333;<br>  --text: #e5e7eb;<br>  --text-muted: #9ca3af;<br>  --gradient: linear-gradient(135deg, #29b5e8 0%, #00d4ff 100%);<br>}<br><br>* {<br>  box-sizing: border-box;<br>}<br><br>body {<br>  margin: 0;<br>  background: var(--bg);<br>  font-family: &#39;Inter&#39;, system-ui, sans-serif;<br>  color: var(--text);<br>  overflow-x: hidden;<br>}<br><br>.app {<br>  min-height: 100vh;<br>  background: var(--bg);<br>  position: relative;<br>}<br><br>.background-effects {<br>  position: fixed;<br>  top: -50%;<br>  left: -50%;<br>  width: 200%;<br>  height: 200%;<br>  background: radial-gradient(circle at 25% 25%, rgba(41, 181, 232, 0.1) 0%, transparent 50%), <br>              radial-gradient(circle at 75% 75%, rgba(0, 212, 255, 0.05) 0%, transparent 50%);<br>  pointer-events: none;<br>  z-index: 0;<br>}<br><br>.container {<br>  max-width: 1400px;<br>  margin: 0 auto;<br>  padding: 40px 24px;<br>  position: relative;<br>  z-index: 1;<br>}<br><br>.header {<br>  text-align: center;<br>  margin-bottom: 48px;<br>}<br><br>.title {<br>  font-size: 48px;<br>  font-weight: 700;<br>  margin-bottom: 16px;<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  background: var(--gradient);<br>  -webkit-background-clip: text;<br>  -webkit-text-fill-color: transparent;<br>  letter-spacing: -1px;<br>}<br><br>.subtitle {<br>  color: var(--text-muted);<br>  font-size: 18px;<br>  font-weight: 400;<br>  max-width: 600px;<br>  margin: 0 auto;<br>}<br><br>.tab-nav {<br>  margin-bottom: 40px;<br>  display: flex;<br>  justify-content: center;<br>}<br><br>.tab-container {<br>  background: var(--bg-card);<br>  border: 1px solid var(--border);<br>  border-radius: 12px;<br>  padding: 6px;<br>  display: flex;<br>}<br><br>.tab {<br>  padding: 12px 32px;<br>  border: none;<br>  background: transparent;<br>  color: var(--text-muted);<br>  cursor: pointer;<br>  font-size: 14px;<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  font-weight: 600;<br>  text-transform: uppercase;<br>  letter-spacing: 1px;<br>  border-radius: 8px;<br>  transition: all 0.3s ease;<br>}<br><br>.tab.active {<br>  background: var(--primary);<br>  color: white;<br>}<br><br>/* Loading styles */<br>.loading-container {<br>  text-align: center;<br>  padding: 60px;<br>  color: var(--text);<br>}<br><br>.spinner {<br>  width: 40px;<br>  height: 40px;<br>  border: 3px solid var(--border);<br>  border-top: 3px solid var(--primary);<br>  border-radius: 50%;<br>  margin: 0 auto 20px;<br>  animation: spin 1s linear infinite;<br>}<br><br>.loading-text {<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  font-size: 16px;<br>}<br><br>@keyframes spin {<br>  0% { transform: rotate(0deg); }<br>  100% { transform: rotate(360deg); }<br>}<br><br>/* Insights grid */<br>.insights-grid {<br>  display: grid;<br>  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));<br>  gap: 24px;<br>}<br><br>.insight-card {<br>  background: var(--bg-card);<br>  border: 1px solid var(--border);<br>  border-radius: 12px;<br>  padding: 24px;<br>  position: relative;<br>  overflow: hidden;<br>  transition: all 0.3s ease;<br>  cursor: pointer;<br>}<br><br>.insight-card:hover {<br>  transform: translateY(-4px);<br>  border-color: var(--primary);<br>  box-shadow: 0 10px 40px rgba(41, 181, 232, 0.2);<br>}<br><br>.card-accent {<br>  position: absolute;<br>  top: 0;<br>  left: 0;<br>  right: 0;<br>  height: 3px;<br>  background: var(--gradient);<br>}<br><br>.metric-label {<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  font-size: 12px;<br>  color: var(--text-muted);<br>  margin-bottom: 12px;<br>  text-transform: uppercase;<br>  letter-spacing: 1px;<br>}<br><br>.metric-value {<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  font-size: 28px;<br>  font-weight: 700;<br>  margin-bottom: 8px;<br>  color: var(--text);<br>  background: var(--gradient);<br>  -webkit-background-clip: text;<br>  -webkit-text-fill-color: transparent;<br>}<br><br>.metric-trend {<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  font-size: 13px;<br>  color: var(--success);<br>  display: flex;<br>  align-items: center;<br>  gap: 6px;<br>}<br><br>/* Analysis chat styles */<br>.analysis-container {<br>  display: flex;<br>  flex-direction: column;<br>  gap: 24px;<br>}<br><br>.query-box {<br>  background: var(--bg-card);<br>  border: 1px solid var(--border);<br>  border-radius: 12px;<br>  padding: 24px;<br>}<br><br>.input-group {<br>  display: flex;<br>  gap: 12px;<br>  align-items: center;<br>}<br><br>.query-input {<br>  flex: 1;<br>  padding: 16px 20px;<br>  background: var(--bg);<br>  border: 2px solid var(--border);<br>  border-radius: 8px;<br>  font-size: 16px;<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  color: var(--text);<br>  outline: none;<br>  transition: border-color 0.3s ease;<br>}<br><br>.query-input:focus {<br>  border-color: var(--primary);<br>}<br><br>.analyze-btn {<br>  padding: 16px 32px;<br>  background: var(--gradient);<br>  color: white;<br>  border: none;<br>  border-radius: 8px;<br>  cursor: pointer;<br>  font-size: 14px;<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  font-weight: 600;<br>  text-transform: uppercase;<br>  letter-spacing: 1px;<br>  transition: all 0.3s ease;<br>}<br><br>.analyze-btn:hover:not(.loading) {<br>  transform: scale(1.05);<br>  box-shadow: 0 8px 25px rgba(41, 181, 232, 0.4);<br>}<br><br>.analyze-btn.loading {<br>  background: var(--text-muted);<br>  cursor: not-allowed;<br>}<br><br>.btn-loading {<br>  display: flex;<br>  align-items: center;<br>  gap: 8px;<br>}<br><br>.btn-spinner {<br>  width: 16px;<br>  height: 16px;<br>  border: 2px solid rgba(255,255,255,0.3);<br>  border-top: 2px solid white;<br>  border-radius: 50%;<br>  animation: spin 1s linear infinite;<br>}<br><br>.error-box {<br>  padding: 16px 20px;<br>  background: rgba(239, 68, 68, 0.1);<br>  border: 1px solid rgba(239, 68, 68, 0.3);<br>  border-radius: 8px;<br>  color: #ef4444;<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  font-size: 14px;<br>  display: flex;<br>  align-items: center;<br>  gap: 8px;<br>}<br><br>.results-panel {<br>  background: var(--bg-card);<br>  border: 1px solid var(--border);<br>  border-radius: 12px;<br>  overflow: hidden;<br>}<br><br>.results-header {<br>  background: var(--gradient);<br>  padding: 16px 24px;<br>  display: flex;<br>  justify-content: space-between;<br>  align-items: center;<br>}<br><br>.query-title {<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  font-size: 14px;<br>  font-weight: 600;<br>  color: white;<br>}<br><br>.status-badge {<br>  padding: 4px 12px;<br>  background: rgba(255,255,255,0.2);<br>  border-radius: 20px;<br>  font-size: 11px;<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  color: white;<br>  text-transform: uppercase;<br>  letter-spacing: 1px;<br>}<br><br>.results-content {<br>  padding: 24px;<br>  display: flex;<br>  flex-direction: column;<br>  gap: 24px;<br>}<br><br>.result-section h3 {<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  font-size: 12px;<br>  font-weight: 600;<br>  margin-bottom: 12px;<br>  color: var(--primary);<br>  text-transform: uppercase;<br>  letter-spacing: 1px;<br>}<br><br>.result-text {<br>  white-space: pre-wrap;<br>  font-family: &#39;Inter&#39;, system-ui, sans-serif;<br>  font-size: 15px;<br>  line-height: 1.6;<br>  color: var(--text);<br>  background: var(--bg);<br>  padding: 20px;<br>  border-radius: 8px;<br>  border: 1px solid var(--border);<br>}<br><br>.raw-data {<br>  background: var(--bg);<br>  padding: 20px;<br>  border-radius: 8px;<br>  border: 1px solid var(--border);<br>  max-height: 300px;<br>  overflow: auto;<br>}<br><br>.raw-data pre {<br>  margin: 0;<br>  font-size: 13px;<br>  font-family: &#39;JetBrains Mono&#39;, monospace;<br>  color: var(--text-muted);<br>  line-height: 1.4;<br>}<br><br>/* Scrollbar styles */<br>::-webkit-scrollbar {<br>  width: 8px;<br>}<br><br>::-webkit-scrollbar-track {<br>  background: var(--bg);<br>}<br><br>::-webkit-scrollbar-thumb {<br>  background: var(--border);<br>  border-radius: 4px;<br>}<br><br>::-webkit-scrollbar-thumb:hover {<br>  background: var(--primary);<br>}</pre><p>4. Replace src/index.tsx:</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import App from &#39;./App.tsx&#39;;<br><br>const root = ReactDOM.createRoot(<br>  document.getElementById(&#39;root&#39;) as HTMLElement<br>);<br><br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p>5. Follow the directory structure at the start of the implementation section and the Git repository to ensure you have the right files in place.</p><p>6. Start the frontend and make sure main.py is also running:</p><pre>npm start</pre><p>6. Go to <a href="http://localhost:3000/">http://localhost:3000/</a> and explore the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkBqe2wKY6RSW_KF-I8JVA.png" /><figcaption>Quick Insights UI</figcaption></figure><p><strong>Note:</strong> This data was generated using synthetic or randomized methods from ECOM Phase 1. As a result, the figures may appear unrealistically high due to challenges in fine-tuning the underlying patterns to better reflect real-world scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTaaxXP6gWjEv-N3ZzURvg.png" /><figcaption>AI Analysis UI</figcaption></figure><p><strong>Note:</strong> The results are entirely based on analysis using Claude 3 Sonnet (2024–02–29). No data science expertise or manual validation was applied.</p><h3>VI. Testing and Integration</h3><h4>1. Component Testing</h4><p><strong>Steps:</strong></p><ol><li>Test each component individually:</li></ol><pre># Test Snowflake connection<br>cd backend<br>python test_snowflake.py<br><br># Test data tools<br>python tool_snowflake.py<br><br># Test AI agents<br>python langgraph_agents.py<br><br># Test API<br>python main.py</pre><p>2. Test the complete flow:</p><ul><li>Start the backend: python main.py</li><li>Start the frontend: npm start</li><li>Open <a href="http://localhost:3000/">http://localhost:3000</a></li></ul><h4>2. Integration Testing</h4><p><strong>Steps:</strong></p><ol><li>Create backend/tests/test_integration.py:</li></ol><pre>import pytest<br>import requests<br>import time<br><br>BASE_URL = &quot;http://localhost:8000&quot;<br>def test_health_endpoint():<br>    response = requests.get(f&quot;{BASE_URL}/health&quot;)<br>    assert response.status_code == 200<br>    assert response.json()[&quot;status&quot;] == &quot;healthy&quot;<br>def test_quick_insights():<br>    response = requests.get(f&quot;{BASE_URL}/quick-insights&quot;)<br>    assert response.status_code == 200<br>    data = response.json()<br>    assert &quot;insights&quot; in data<br>    assert len(data[&quot;insights&quot;]) &gt; 0<br>def test_analyze_endpoint():<br>    query = &quot;What are our top selling products?&quot;<br>    response = requests.post(f&quot;{BASE_URL}/analyze&quot;, json={&quot;query&quot;: query})<br>    assert response.status_code == 200<br>    data = response.json()<br>    assert &quot;analysis_id&quot; in data<br>    assert &quot;results&quot; in data<br>    assert data[&quot;query&quot;] == query<br>if __name__ == &quot;__main__&quot;:<br>    # Make sure your API is running before running these tests<br>    test_health_endpoint()<br>    test_quick_insights() <br>    test_analyze_endpoint()<br>    print(&quot;All integration tests passed!&quot;)</pre><p>2. Run integration tests:</p><pre>python backend/test_integration.py</pre><h3>VII. Docker Setup</h3><h4>1. Simple Docker Configuration</h4><p><strong>Steps:</strong></p><ol><li>Create backend/Dockerfile:</li></ol><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br><br># Install system dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    gcc \<br>    g++ \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># Copy requirements from root directory<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Copy backend code<br>COPY backend/ .<br><br># Set Python path<br>ENV PYTHONPATH=/app<br><br># Expose port<br>EXPOSE 8000<br><br># Command to run the application<br>CMD [&quot;python&quot;, &quot;-m&quot;, &quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>2. Create frontend/Dockerfile:</p><pre>FROM node:18-alpine<br><br>WORKDIR /app<br><br># Copy package files<br>COPY package*.json ./<br><br># Install dependencies<br>RUN npm install<br><br># Copy source code<br>COPY . .<br><br># Build the app<br>RUN npm run build<br><br># Install serve to run the build<br>RUN npm install -g serve<br><br># Expose port<br>EXPOSE 3000<br><br># Serve the build<br>CMD [&quot;serve&quot;, &quot;-s&quot;, &quot;build&quot;, &quot;-l&quot;, &quot;3000&quot;]</pre><p><strong>Note:</strong> You may also add .dockerignore as documented on the repository</p><p>3. Create root docker-compose.yml:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  backend:<br>    build:<br>      context: .  # Root directory as build context<br>      dockerfile: backend/Dockerfile<br>    container_name: ecom_ai_backend<br>    ports:<br>      - &quot;8000:8000&quot;<br>    environment:<br>      - SNOWFLAKE_USER=${SNOWFLAKE_USER}<br>      - SNOWFLAKE_PASSWORD=${SNOWFLAKE_PASSWORD}<br>      - SNOWFLAKE_ACCOUNT=${SNOWFLAKE_ACCOUNT}<br>      - SNOWFLAKE_WAREHOUSE=${SNOWFLAKE_WAREHOUSE}<br>      - SNOWFLAKE_DATABASE=${SNOWFLAKE_DATABASE}<br>      - SNOWFLAKE_RAW_SCHEMA=${SNOWFLAKE_RAW_SCHEMA}<br>      - SNOWFLAKE_ROLE=${SNOWFLAKE_ROLE}<br>      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}<br><br>  frontend:<br>    build: ./frontend<br>    container_name: ecom_ai_frontend<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - backend<br><br>networks:<br>  default:<br>    name: ecom_ai_network</pre><h4>2. Environment Setup</h4><p><strong>Steps:</strong></p><ol><li>Make sure your .env file is in the root directory:</li></ol><pre># Snowflake Configuration<br>SNOWFLAKE_USER=your_username<br>SNOWFLAKE_PASSWORD=your_password<br>SNOWFLAKE_ACCOUNT=your_account_id<br>SNOWFLAKE_WAREHOUSE=ECOM_WH<br>SNOWFLAKE_DATABASE=ECOM_DB<br>SNOWFLAKE_RAW_SCHEMA=ECOM_RAW<br>SNOWFLAKE_ROLE=ECOM_ROLE<br><br># Anthropic Configuration<br>ANTHROPIC_API_KEY=your_anthropic_api_key</pre><p>2. Create frontend/.env file for React:</p><pre>HOST=0.0.0.0</pre><h4>3. Running with Docker</h4><p><strong>Steps:</strong></p><ol><li>Start everything and ensure <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> is running:</li></ol><pre># Build and start containers<br>docker-compose up --build<br><br># Start in background<br>docker-compose up -d --build<br><br># Stop services<br>docker-compose down</pre><p>2. Access the Application:</p><ul><li>Frontend: <a href="http://localhost:3000/">http://localhost:3000</a></li><li>Backend API: <a href="http://localhost:8000/">http://localhost:8000</a></li><li>API Documentation: <a href="http://localhost:8000/docs">http://localhost:8000/docs</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRMRGFWBJ7HrRbRXXV5MwQ.png" /><figcaption>Docker Desktop Logs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-vUwFqKl5Ak9yUmU42Yxg.png" /><figcaption>Dockerized Backend and Frontend (Quick Insights)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYB2BwElKBX6nfDMFkEI_Q.png" /><figcaption>Dockerized Backend and Frontend (AI Analysis)</figcaption></figure><h4>4. Common Docker Commands</h4><p><strong>Steps:</strong></p><ol><li>View logs:</li></ol><pre># All services<br>docker-compose logs<br># Specific service<br>docker-compose logs backend<br>docker-compose logs frontend</pre><p>2. Restart services:</p><pre>docker-compose restart backend<br>docker-compose restart frontend</pre><p>2. Clean up:</p><pre># Remove containers and networks<br>docker-compose down<br># Remove everything including volumes<br>docker-compose down -v</pre><h3>VIII. Usage Examples and Testing</h3><h4>1. Example Queries</h4><p><strong>Test these queries in your application:</strong></p><ol><li><strong>Sales Analysis:</strong></li></ol><ul><li>“How are the sales trending this month?”</li><li>“What’s the revenue performance compared to last month?”</li></ul><p><strong>2. Product Analysis:</strong></p><ul><li>“Which products are the best sellers?”</li><li>“What products should be promoted more?”</li></ul><p><strong>3. Customer Analysis:</strong></p><ul><li>“How are the customer segments performing?”</li><li>“What can be improved for customer retention?”</li></ul><p><strong>4. General Business:</strong></p><ul><li>“Give me an overview of the business performance”</li><li>“What opportunities should be focused on?”</li></ul><h4>2. Expected Results</h4><p><strong>For each query, you should get:</strong></p><ul><li><strong>Data</strong>: Raw metrics from Snowflake</li><li><strong>Analysis</strong>: AI-powered insights about patterns and trends</li><li><strong>Recommendations</strong>: Actionable business advice</li></ul><h3>Architecture Summary</h3><p><strong>Data Flow:</strong></p><pre>Query → React UI → FastAPI → LangGraph Agents ↔ Snowflake ↔ Claude Analysis → Recommendations → LangGraph Agents → FastAPI → React UI → Results</pre><p><strong>Key Components:</strong></p><ul><li><strong>React Frontend</strong>: Modern interface for user interactions</li><li><strong>FastAPI Backend</strong>: REST API handling requests</li><li><strong>LangGraph Orchestrator</strong>: Manages agent workflow</li><li><strong>AI Agents</strong>: Specialized data collection, analysis, and consulting</li><li><strong>Snowflake Integration</strong>: Real-time data warehouse connectivity</li><li><strong>Claude AI</strong>: Advanced analysis and recommendation generation</li></ul><h3>Conclusion</h3><p>You now have a complete AI-powered business intelligence system that can:</p><ol><li><strong>Answer questions in plain English</strong> about your e-commerce data</li><li><strong>Provide intelligent analysis</strong> beyond simple metrics</li><li><strong>Generate actionable recommendations</strong> for business growth</li><li><strong>Connect directly to Snowflake</strong> for real-time insights</li></ol><p>The system transforms the Phase 1 data infrastructure into an interactive business advisor that can be utilized to democratize data access across teams or organization.</p><p>This completes Phase 4 of the e-commerce modern data stack, providing the intelligence layer that makes your data truly actionable.</p><figure><a href="https://buymeacoffee.com/sai_documents"><img alt="" src="https://cdn-images-1.medium.com/max/300/0*4Sh5csygXJEf1Zd1.png" /></a></figure><p>Or connect with me on the following:</p><p><a href="https://www.linkedin.com/in/sandy-lauguico/">https://www.linkedin.com/in/sandy-lauguico/</a></p><p><a href="https://github.com/sclauguico">https://github.com/sclauguico</a></p><p><a href="https://www.facebook.com/sandy.c.lauguico/">https://www.facebook.com/sandy.c.lauguico/</a></p><p><a href="https://www.instagram.com/sai_documents/">https://www.instagram.com/sai_documents/</a></p><p>And please give a clap (or claps) below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd1b2471482d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECOM Phase 3 - Part 1: Unlocking Business Value with SQL]]></title>
            <link>https://medium.com/@sclauguico/ecom-phase-3-part-1-unlocking-business-value-with-sql-8ad1642107d9?source=rss-47876a26005------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ad1642107d9</guid>
            <dc:creator><![CDATA[Sandy Lauguico]]></dc:creator>
            <pubDate>Sat, 03 May 2025 08:50:52 GMT</pubDate>
            <atom:updated>2025-05-03T08:50:52.474Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven e-commerce landscape, understanding customer behavior, product performance, and sales and revenue trends is critical for business success. SQL has emerged as the language of choice for data analysts looking to extract meaningful insights from vast amounts of transaction data. In this article, I’ll walk through several powerful e-commerce analytics techniques using SQL, explaining what each analysis does, why it’s essential, how to implement it, and the valuable insights it can reveal.</p><p>This article is built on top of <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a> (<a href="https://github.com/sclauguico/ecommerce-modern-data-stack">GitHub Repository</a>), with a specific focus on the section highlighted by the dashed red box in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIlU9lpCu5ExL1P5TZ4Bow.jpeg" /><figcaption>End-to-end Data Pipeline Diagram</figcaption></figure><p>As such, the SQL queries showcased here are run against the <a href="https://dbdiagram.io/d/ecom_int_schema-676a832f5406798ef78acaf7">intermediate model</a> created in that phase. You can find the SQL files referenced in this article in the accompanying <a href="https://github.com/sclauguico/ecommerce-sql-business-analysis">GitHub repository</a>. The data used in this article are entirely fictional, generated using the <a href="https://faker.readthedocs.io/en/master/">Faker Python package</a> and statistical distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqaFnNZTvoqIO-otRgQx_Q.png" /><figcaption>Entity Relationship Diagram: Intermediate Data Model</figcaption></figure><h3>I. Customer Behavior Analysis</h3><p>Understanding customer behavior is essential for any e-commerce business looking to grow and retain its user base. By analyzing how customers interact with your platform, what they purchase, and when they engage, you can develop targeted marketing strategies, improve customer experiences, and ultimately increase revenue.</p><p>The following three analyses dive deep into customer behavior patterns, segmenting users based on their purchase habits, understanding demographic influences, and identifying customer demographic purchase patterns that drive sales.</p><h4><strong>1. RFM Analysis: Segmenting Customers for Targeted Marketing</strong></h4><p><strong>What is RFM Analysis?</strong><br>RFM (Recency, Frequency, Monetary) analysis is a customer segmentation technique that groups customers based on three key purchasing behaviors:</p><ul><li><strong>Recency:</strong> How recently a customer made a purchase</li><li><strong>Frequency:</strong> How often a customer makes purchases</li><li><strong>Monetary:</strong> How much money a customer spends</li></ul><p>The analysis assigns scores to customers in each dimension and combines them to create meaningful segments like “Champions,” “Loyal Customers,” “At Risk,” and more.</p><p><strong>Why Do We Need RFM Analysis?</strong><br>Understanding different customer segments allows businesses to:</p><ul><li>Target marketing efforts more effectively</li><li>Personalize communications based on customer value</li><li>Allocate resources efficiently to high-value segments</li><li>Identify customers at risk of churn</li><li>Develop strategies to move customers into more valuable segments</li></ul><p>Rather than treating all customers the same, RFM analysis lets you tailor your approach based on actual customer behavior and value.</p><p><strong>How to Implement RFM Analysis in SQL?</strong><br>The implementation involves calculating customer purchase metrics and segmenting based on behavioral scores:</p><ul><li>Calculate recency, frequency, and monetary metrics per customer using aggregation functions</li><li>Assign quintile scores (1–5) for each dimension using NTILE window functions</li><li>Create segments using CASE statements based on score combinations</li><li>Calculate percentile ranks within segments for further granularity</li></ul><pre>-- Recency, Frequency, Monetary (RFM) Analysis<br>-- Step 1: Calculate customer purchase metrics<br>WITH customer_purchase_metrics AS (<br>    SELECT<br>        c.customer_id,<br>        c.email,<br>        c.first_name,<br>        c.last_name,<br>        c.signup_date,<br>        c.age,<br>        c.gender,<br>        c.annual_income,<br>        l.city,<br>        l.state,<br>        et.education_type AS education,<br>        DATEDIFF(DAY, MAX(o.order_date), CURRENT_DATE()) AS recency_days,<br>        COUNT(DISTINCT o.order_id) AS frequency,<br>        SUM(o.total_amount) AS monetary,<br>        AVG(o.total_amount) AS avg_order_value<br>    FROM ecom_db.ecom_intermediate.customers_enriched c<br>    LEFT JOIN ecom_db.ecom_intermediate.orders o ON c.customer_id = o.customer_id<br>    LEFT JOIN ecom_db.ecom_intermediate.education_types et ON c.education_id = et.education_id<br>    LEFT JOIN ecom_db.ecom_intermediate.locations l ON c.location_id = l.location_id<br>    GROUP BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11<br>),<br>-- Step 2: Assign RFM scores (1-5 scale)<br>rfm_scores AS (<br>    SELECT<br>        *,<br>        NTILE(5) OVER (ORDER BY recency_days) AS r_score_reversed,<br>        NTILE(5) OVER (ORDER BY frequency) AS f_score,<br>        NTILE(5) OVER (ORDER BY monetary) AS m_score,<br>        6 - NTILE(5) OVER (ORDER BY recency_days) AS r_score<br>    FROM customer_purchase_metrics<br>),<br>-- Step 3: Create meaningful segments<br>rfm_segments AS (<br>    SELECT<br>        *,<br>        r_score + f_score + m_score AS rfm_total,<br>        CASE<br>            WHEN r_score &gt;= 4 AND f_score &gt;= 4 AND m_score &gt;= 4 THEN &#39;Champions&#39;<br>            WHEN r_score &gt;= 4 AND f_score &gt;= 3 AND m_score &gt;= 3 THEN &#39;Loyal Customers&#39;<br>            WHEN r_score &gt;= 3 AND f_score &gt;= 1 AND m_score &gt;= 2 THEN &#39;Potential Loyalists&#39;<br>            WHEN r_score &gt;= 4 AND f_score &lt;= 2 AND m_score &lt;= 2 THEN &#39;New Customers&#39;<br>            WHEN r_score &gt;= 3 AND f_score &lt;= 2 AND m_score &lt;= 2 THEN &#39;Promising&#39;<br>            WHEN r_score &gt;= 2 AND f_score &gt;= 2 AND m_score &gt;= 2 THEN &#39;Customers Needing Attention&#39;<br>            WHEN r_score &gt;= 2 AND f_score &gt;= 2 AND m_score &lt; 2 THEN &#39;At Risk&#39;<br>            WHEN r_score &lt; 2 AND f_score &gt;= 3 AND m_score &gt;= 3 THEN &#39;Can&#39;&#39;t Lose Them&#39;<br>            WHEN r_score &lt; 2 AND f_score &gt;= 2 AND m_score &gt;= 2 THEN &#39;Hibernating&#39;<br>            WHEN r_score &lt; 2 AND f_score &lt; 2 AND m_score &lt; 2 THEN &#39;Lost&#39;<br>            ELSE &#39;Others&#39;<br>        END AS customer_segment<br>    FROM rfm_scores<br>)<br>-- Final query to view segmented customers with percentile<br>SELECT <br>    *,<br>    PERCENT_RANK() OVER (PARTITION BY customer_segment ORDER BY rfm_total) AS segment_percentile<br>FROM rfm_segments<br>ORDER BY customer_segment, rfm_total DESC</pre><p>This approach segments customers by analyzing their purchase recency, frequency, and monetary value, using quantile scoring to create a comprehensive customer segmentation matrix that helps businesses prioritize relationship management. This analysis segments customers based on their purchasing behavior using three key dimensions:</p><ul><li>Recency — how recently a customer made a purchase</li><li>Frequency — how often a customer makes purchases</li><li>Monetary — how much a customer spends</li></ul><p>These dimensions are combined to categorize customers into segments like “Champions,” “Loyal Customers,” “At Risk,” and “Lost.”</p><p><strong>Results and Insights</strong><br>RFM analysis typically reveals patterns like:</p><p><strong>Champions (5–10% of customers):</strong> These are your best customers who bought recently, buy often, and spend a lot. They may represent up to 50–70% of total revenue.</p><p>Action: Reward them, engage them as ambassadors, and solicit feedback.</p><p><strong>Loyal Customers (10–15% of customers):</strong> Regular spenders who purchase recently but not as frequent and as high monetary value as Champions.</p><p>Action: Upsell higher-value products, increase purchase frequency with limited-time offers.</p><p><strong>At Risk (10–15% of customers):</strong> Previously good customers showing declining activity.</p><p>Action: Reactivation campaigns, special “we miss you” promotions.</p><p><strong>Lost (15–20% of customers): </strong>Haven’t purchased in a long time despite previous activity.</p><p>Action: Last-attempt win-back campaigns or exclude from marketing to save costs.</p><p>By identifying these segments, you can create tailored marketing strategies for each, maximizing ROI on marketing spend and improving customer retention.</p><p><strong>Sample Query Results:</strong></p><p>Disclaimer: As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mi5Ma4JqPgJYEAS8hkT3hg.png" /><figcaption>RFM Analysis: Sample Query Result Part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwMRpvjT9o2Vvmmuug4UCw.png" /><figcaption>RFM Analysis: Sample Query Result Part 2</figcaption></figure><h4><strong>2. Customer Lifetime Value: Predicting Long-Term Customer Worth</strong></h4><p><strong>What is Customer Lifetime Value Analysis?</strong><br>Customer Lifetime Value (CLV/LTV) analysis estimates the total revenue a business can expect from a customer throughout their relationship. This predictive metric helps businesses understand the long-term value of acquiring and retaining different customer segments by analyzing their historical purchase patterns, frequency, monetary value, and engagement over time.</p><p><strong>Why Do We Need Customer Lifetime Value Analysis?</strong><br>CLV analysis is essential for several key business functions to:</p><ul><li>Optimize customer acquisition costs (CAC) relative to expected lifetime value</li><li>Identify high-value customer segments for focused retention efforts</li><li>Allocate marketing budgets more effectively across customer segments</li><li>Develop personalized retention strategies based on potential future value</li><li>Make data-driven decisions about loyalty programs and customer service investments</li></ul><p>By understanding which customers are likely to generate the most value over time, businesses can make smarter investments in acquisition and retention.</p><p><strong>How to Implement Customer Lifetime Value Analysis in SQL?</strong><br>The implementation projects future customer value based on historical purchase patterns and estimated retention:</p><ul><li>Calculate comprehensive customer purchase history metrics (orders, spend, frequency)</li><li>Determine purchase intervals to understand individual buying cadence</li><li>Estimate churn probability based on purchase recency and typical purchase intervals</li><li>Project future value across different time horizons (1-year, 3-year) incorporating churn risk</li></ul><pre>-- Customer Lifetime Value (LTV) Analysis<br>-- Step 1: Calculate comprehensive customer purchase history<br>WITH customer_order_history AS (<br>    SELECT<br>        c.customer_id,<br>        c.email,<br>        c.first_name,<br>        c.last_name,<br>        c.signup_date,<br>        c.age,<br>        c.gender,<br>        c.annual_income,<br>        l.city,<br>        l.state,<br>        DATEDIFF(DAY, c.signup_date, CURRENT_DATE()) AS customer_tenure_days,<br>        COUNT(DISTINCT o.order_id) AS total_orders,<br>        SUM(o.total_amount) AS total_spent,<br>        MAX(o.order_date) AS last_order_date,<br>        MIN(o.order_date) AS first_order_date,<br>        AVG(o.total_amount) AS avg_order_value,<br>        DATEDIFF(DAY, MIN(o.order_date), MAX(o.order_date)) AS days_between_first_last_order,<br>        COUNT(DISTINCT o.order_id) / <br>            NULLIF(DATEDIFF(MONTH, c.signup_date, CURRENT_DATE()), 0) AS monthly_purchase_rate<br>    FROM ecom_db.ecom_intermediate.customers_enriched c<br>    LEFT JOIN ecom_db.ecom_intermediate.locations l ON c.location_id = l.location_id<br>    LEFT JOIN ecom_db.ecom_intermediate.orders o ON c.customer_id = o.customer_id<br>    GROUP BY <br>        c.customer_id,<br>        c.email,<br>        c.first_name,<br>        c.last_name,<br>        c.signup_date,<br>        c.age,<br>        c.gender,<br>        c.annual_income,<br>        l.city,<br>        l.state,<br>        customer_tenure_days<br>),<br>-- Step 2: Calculate intervals between purchases for repeat customers<br>purchase_intervals AS (<br>    SELECT<br>        o1.customer_id,<br>        AVG(DATEDIFF(DAY, o1.order_date, o2.order_date)) AS avg_days_between_orders<br>    FROM ecom_db.ecom_intermediate.orders o1<br>    JOIN ecom_db.ecom_intermediate.orders o2 <br>        ON o1.customer_id = o2.customer_id AND o1.order_date &lt; o2.order_date<br>    GROUP BY 1<br>    HAVING COUNT(*) &gt; 1<br>),<br>-- Step 3: Estimate churn probability based on purchase recency and cadence<br>churn_probability AS (<br>    SELECT<br>        coh.customer_id,<br>        CASE <br>            WHEN coh.total_orders = 0 THEN 1.0<br>            WHEN DATEDIFF(DAY, coh.last_order_date, CURRENT_DATE()) &gt; 2 * COALESCE(pi.avg_days_between_orders, 60) THEN 0.8<br>            WHEN DATEDIFF(DAY, coh.last_order_date, CURRENT_DATE()) &gt; COALESCE(pi.avg_days_between_orders, 60) THEN 0.5<br>            ELSE 0.2<br>        END AS churn_probability<br>    FROM customer_order_history coh<br>    LEFT JOIN purchase_intervals pi ON coh.customer_id = pi.customer_id<br>)<br>-- Step 4: Calculate CLV projections for different time horizons<br>SELECT<br>    coh.*,<br>    COALESCE(pi.avg_days_between_orders, 0) AS avg_days_between_orders,<br>    cp.churn_probability,<br>    -- Historical CLV<br>    coh.total_spent AS historical_clv,<br>    -- Projected 12-month CLV<br>    coh.total_spent + (<br>        coh.avg_order_value * <br>        coh.monthly_purchase_rate * <br>        12 * <br>        (1 - cp.churn_probability)<br>    ) AS projected_annual_clv,<br>    -- Projected 3-year CLV with retention decay<br>    coh.total_spent + (<br>        coh.avg_order_value * <br>        coh.monthly_purchase_rate * <br>        36 * <br>        POWER((1 - cp.churn_probability), 3)<br>    ) AS projected_3year_clv,<br>    -- Customer value tier<br>    CASE<br>        WHEN coh.total_spent = 0 THEN &#39;No Value&#39;<br>        WHEN coh.total_spent &lt; 100 THEN &#39;Low Value&#39;<br>        WHEN coh.total_spent &lt; 500 THEN &#39;Medium Value&#39;<br>        WHEN coh.total_spent &lt; 2000 THEN &#39;High Value&#39;<br>        ELSE &#39;VIP&#39;<br>    END AS value_tier<br>FROM customer_order_history coh<br>LEFT JOIN purchase_intervals pi ON coh.customer_id = pi.customer_id<br>LEFT JOIN churn_probability cp ON coh.customer_id = cp.customer_id</pre><p>This approach calculates CLV by combining historical spending with projected future value, incorporating purchase frequency and sophisticated churn probability estimates based on individual customer purchase patterns. This analysis builds on purchase history to predict future customer value:</p><ul><li>Uses historical purchase patterns and intervals to estimate long-term customer worth</li><li>Incorporates churn probability based on purchase recency relative to typical purchase cadence</li><li>Projects value across multiple time horizons with retention decay factors</li><li>Categorizes customers into value tiers for strategic relationship management</li></ul><p><strong>Results and Insights</strong><br>CLV analysis typically reveals insights like:</p><p><strong>VIP customer profiles:</strong> Customers in the “VIP” segment with high predicted 5-year CLV of $2,000+ often share demographic characteristics (age 35–45, income &gt;$75K) that can be targeted in acquisition campaigns.</p><p>Action: Allocate higher acquisition budgets for customers matching these profiles.</p><p><strong>Value development timelines: </strong>New customers might have a negative ROI for the first 3–6 months before becoming profitable, but those who make a second purchase within 30 days typically have 3x higher lifetime value.</p><p>Action: Focus on early engagement strategies to accelerate the second purchase.</p><p><strong>Retention value:</strong> Improving retention rate by just 5% can increase CLV by 25–95% depending on the customer segment.</p><p>Action: Implement targeted retention programs for high-CLV customers showing early churn signals.</p><p><strong>ROI optimization:</strong> “Loyal Customers” segment shows the highest ROI on customer acquisition costs (15:1 over 24 months), while “Promising” customers show fastest ROI recovery (within 3 months).</p><p>Action: Balance acquisition spending between immediate ROI and long-term value segments.</p><p>These insights enable more precise customer acquisition and retention strategies, allowing businesses to focus resources on customers with the highest long-term value potential.</p><p><strong>Sample Query Results</strong></p><p>Disclaimer: As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGeiuDi0PccArz-6uG1kFw.png" /><figcaption>CLV/LTV Analysis: Sample Query Result Part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j3c_FZD0lLHvdLy6BRYjVA.png" /><figcaption>CLV/LTV Analysis: Sample Query Result Part 2</figcaption></figure><h4>3. Demographic Purchase Patterns: Understanding Customer Preferences</h4><p><strong>What is Demographic Purchase Analysis</strong>?</p><p>Demographic purchase analysis examines how different customer segments (based on age, income, gender, education, location, etc.) interact with your products and services. It reveals which customer groups are most valuable for different product categories and how purchasing behaviors vary across demographics.</p><p><strong>Why Do We Need Demographic Purchase Analysis?</strong></p><p>This analysis provides essential insights to:</p><ul><li>Target marketing and personalization</li><li>Align product development with customer preferences</li><li>Identify underserved high-potential segments</li><li>Optimize marketing spend across customer groups</li><li>Inform expansion into new markets or customer segments</li></ul><p>Understanding demographic patterns helps businesses tailor their offerings to the specific needs and preferences of different customer groups.</p><p><strong>How to Implement Demographic Purchase Analysis in SQL?</strong></p><p>The implementation involves segmenting customers by demographics and analyzing their purchasing behaviors:</p><ul><li>Create demographic segments based on age, income, gender, and other attributes</li><li>Calculate purchase metrics for each customer across segments</li><li>Analyze category preferences by demographic segment</li><li>Aggregate metrics by segment to identify patterns and trends</li></ul><pre>-- Purchase Patterns by Demographics<br>-- Step 1: Create demographic segments<br>WITH demographic_segments AS (<br>    SELECT<br>        customer_id,<br>        -- Age segments<br>        CASE<br>            WHEN age &lt; 30 THEN &#39;Gen Z (18-29)&#39;<br>            WHEN age BETWEEN 30 AND 39 THEN &#39;Millennials (30-39)&#39;<br>            WHEN age BETWEEN 40 AND 49 THEN &#39;Xennials (40-49)&#39;<br>            WHEN age BETWEEN 50 AND 59 THEN &#39;Gen X (50-59)&#39;<br>            WHEN age BETWEEN 60 AND 69 THEN &#39;Younger Boomers (60-69)&#39;<br>            WHEN age &gt;= 70 THEN &#39;Older Boomers (70+)&#39;<br>            ELSE &#39;Unknown Age&#39;<br>        END AS age_segment,<br>        -- Income segments<br>        CASE<br>            WHEN annual_income &lt; 30000 THEN &#39;Low Income (&lt;$30K)&#39;<br>            WHEN annual_income BETWEEN 30000 AND 59999 THEN &#39;Lower-Middle ($30K-$60K)&#39;<br>            WHEN annual_income BETWEEN 60000 AND 99999 THEN &#39;Upper-Middle ($60K-$100K)&#39;<br>            WHEN annual_income &gt;= 100000 THEN &#39;High Income ($100K+)&#39;<br>            ELSE &#39;Unknown Income&#39;<br>        END AS income_segment,<br>        gender,<br>        et.education_type AS education,<br>        l.city,<br>        l.state,<br>        ms.status_type AS marital_status<br>    FROM ecom_db.ecom_intermediate.customers_enriched c<br>    LEFT JOIN ecom_db.ecom_intermediate.education_types et ON c.education_id = et.education_id<br>    LEFT JOIN ecom_db.ecom_intermediate.locations l ON c.location_id = l.location_id<br>    LEFT JOIN ecom_db.ecom_intermediate.marital_statuses ms ON c.marital_status_id = ms.marital_status_id<br>),<br>-- Step 2: Calculate purchase metrics for each customer<br>purchase_metrics AS (<br>    SELECT<br>        ds.*,<br>        COUNT(DISTINCT o.order_id) AS total_orders,<br>        SUM(o.total_amount) AS total_spent,<br>        AVG(o.total_amount) AS avg_order_value,<br>        MAX(o.order_date) AS last_order_date,<br>        COUNT(DISTINCT o.order_id) / NULLIF(COUNT(DISTINCT EXTRACT(MONTH FROM o.order_date)), 0) AS monthly_purchase_frequency<br>    FROM demographic_segments ds<br>    LEFT JOIN ecom_db.ecom_intermediate.orders o ON ds.customer_id = o.customer_id<br>    GROUP BY ds.customer_id, ds.age_segment, ds.income_segment, ds.gender, <br>             ds.education, ds.city, ds.state, ds.marital_status<br>),<br>-- Step 3: Create category preferences by demographic segment<br>category_preferences AS (<br>    SELECT<br>        pm.customer_id,<br>        pm.age_segment,<br>        pm.income_segment,<br>        pm.gender,<br>        c.category_name,<br>        COUNT(DISTINCT oi.order_id) AS category_orders,<br>        SUM(oi.total_price) AS category_spent<br>    FROM purchase_metrics pm<br>    JOIN ecom_db.ecom_intermediate.order_items oi ON pm.customer_id = oi.customer_id<br>    JOIN ecom_db.ecom_intermediate.products_enriched p ON oi.product_id = p.product_id<br>    JOIN ecom_db.ecom_intermediate.categories_enriched c ON p.category_id = c.category_id<br>    GROUP BY 1, 2, 3, 4, 5<br>),<br>-- Combined demographic aggregations<br>-- Step 4: Aggregate metrics by demographic segments<br>demographic_aggregations AS (<br>    -- Aggregate by Age Segment<br>    SELECT<br>        &#39;Age: &#39; || age_segment AS segment_name,<br>        COUNT(DISTINCT customer_id) AS customer_count,<br>        SUM(total_orders) AS total_orders,<br>        SUM(total_spent) AS total_revenue,<br>        AVG(avg_order_value) AS avg_order_value,<br>        AVG(monthly_purchase_frequency) AS avg_monthly_frequency,<br>        AVG(total_spent) / COUNT(DISTINCT customer_id) AS revenue_per_customer<br>    FROM purchase_metrics<br>    GROUP BY age_segment<br>    <br>    UNION ALL<br>    <br>    -- Aggregate by Income Segment<br>    SELECT<br>        &#39;Income: &#39; || income_segment AS segment_name,<br>        COUNT(DISTINCT customer_id) AS customer_count,<br>        SUM(total_orders) AS total_orders,<br>        SUM(total_spent) AS total_revenue,<br>        AVG(avg_order_value) AS avg_order_value,<br>        AVG(monthly_purchase_frequency) AS avg_monthly_frequency,<br>        AVG(total_spent) / COUNT(DISTINCT customer_id) AS revenue_per_customer<br>    FROM purchase_metrics<br>    GROUP BY income_segment<br>    <br>    UNION ALL<br>    <br>    -- Aggregate by State<br>    SELECT<br>        &#39;State: &#39; || state AS segment_name,<br>        COUNT(DISTINCT customer_id) AS customer_count,<br>        SUM(total_orders) AS total_orders,<br>        SUM(total_spent) AS total_revenue,<br>        AVG(avg_order_value) AS avg_order_value,<br>        AVG(monthly_purchase_frequency) AS avg_monthly_frequency,<br>        AVG(total_spent) / COUNT(DISTINCT customer_id) AS revenue_per_customer<br>    FROM purchase_metrics<br>    GROUP BY state<br>),<br>-- Category preferences by age segment, income segment, and gender<br>category_aggregations AS (<br>    -- Category preferences by age segment<br>    SELECT <br>        &#39;Age: &#39; || age_segment AS segment_name,<br>        category_name,<br>        COUNT(DISTINCT customer_id) AS customer_count,<br>        SUM(category_orders) AS total_orders,<br>        SUM(category_spent) AS total_spent,<br>        RATIO_TO_REPORT(SUM(category_spent)) OVER (PARTITION BY age_segment) AS category_share_of_wallet<br>    FROM category_preferences<br>    GROUP BY age_segment, category_name<br>    <br>    UNION ALL<br>    <br>    -- Category preferences by income segment<br>    SELECT <br>        &#39;Income: &#39; || income_segment AS segment_name,<br>        category_name,<br>        COUNT(DISTINCT customer_id) AS customer_count,<br>        SUM(category_orders) AS total_orders,<br>        SUM(category_spent) AS total_spent,<br>        RATIO_TO_REPORT(SUM(category_spent)) OVER (PARTITION BY income_segment) AS category_share_of_wallet<br>    FROM category_preferences<br>    GROUP BY income_segment, category_name<br>    <br>    UNION ALL<br>    <br>    -- Category preferences by gender<br>    SELECT <br>        &#39;Gender: &#39; || gender AS segment_name,<br>        category_name,<br>        COUNT(DISTINCT customer_id) AS customer_count,<br>        SUM(category_orders) AS total_orders,<br>        SUM(category_spent) AS total_spent,<br>        RATIO_TO_REPORT(SUM(category_spent)) OVER (PARTITION BY gender) AS category_share_of_wallet<br>    FROM category_preferences<br>    GROUP BY gender, category_name<br>)<br><br>-- Select from the first query. Comment out for the second query<br>SELECT * FROM demographic_aggregations<br>ORDER BY segment_name, total_revenue DESC<br><br>-- Run this separately (by uncommenting) for the the category preferences <br>-- SELECT * FROM category_aggregations<br>-- ORDER BY segment_name, category_share_of_wallet DESC</pre><p>This approach correlates customer demographic attributes with purchasing behaviors, creating meaningful segments that reveal how factors like age, income, and location influence product preferences and spending habits. This analysis reveals how different customer segments shop:</p><ul><li>Age-based cohorts show distinct product preferences and spending patterns</li><li>Income segments highlight price sensitivity and premium product adoption</li><li>Geographic analysis identifies regional trends and opportunities<br>Education and marital status correlations with purchasing behaviors</li></ul><p><strong>Results and Insights</strong></p><p>Demographic purchase analysis typically reveals insights like:</p><p><strong>Age-based patterns</strong>: Millennials (30–39) may show the highest average order value and purchase frequency for technology products, while Gen X (50–59) might spend more on premium home goods.</p><p>Action: Tailor product recommendations and marketing messaging to age-specific preferences.</p><p><strong>Income-level insights</strong>: High-income customers ($100K+) might purchase less frequently but spend significantly more per order, making them prime targets for luxury products.</p><p>Action:<strong> </strong>Develop premium product lines and personalized services for high-value segments.</p><p><strong>Regional differences</strong>: Customers in coastal states might show stronger preferences for eco-friendly products compared to other regions.</p><p>Action: Adjust inventory and marketing campaigns based on regional preferences.</p><p><strong>Education-based trends</strong>: Customers with advanced degrees might show higher conversion rates for educational content and detailed product information.</p><p>Action: Create more detailed product documentation and educational content for this segment.</p><p>These insights enable highly targeted marketing campaigns, product development priorities, and customer experience improvements that resonate with specific customer segments.</p><p><strong>Sample Query Results</strong></p><p>Disclaimer: As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Dg-3igp3jnCBxt4kpBmIQ.png" /><figcaption>Demographic Purchase Patterns Analysis: Sample Query Result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJtqSxjFBngDcv0ZjUWEXQ.png" /><figcaption>Demographic Category Preferences Analysis: Sample Query Result</figcaption></figure><h3>II. Product Performance Analysis</h3><p>Understanding which products drive your business performance is critical for inventory planning, marketing focus, and business growth. Product performance analysis helps you identify top sellers, understand product relationships, recognize seasonal patterns, and optimize your product catalog.</p><p>The next three analyses examine different aspects of product performance: how products are purchased together, how product categories perform over time, and how seasonality affects different product types. These insights enable data-driven decisions for product positioning, inventory management, and promotional planning.</p><h4>4. Market Basket Analysis: Understanding Product Associations</h4><p><strong>What is Market Basket Analysis?</strong><br>Market basket analysis examines customer purchase patterns to discover which products are frequently bought together. It identifies relationships between products that might not be immediately obvious, using metrics like support, confidence, and lift to quantify these relationships.</p><p><strong>Why Do We Need Market Basket Analysis?</strong><br>This analysis offers several business advantages:</p><ul><li>Improve web store layouts and product placements</li><li>Create effective cross-selling strategies</li><li>Design more appealing product bundles</li><li>Optimize recommendation engines</li><li>Inform inventory management decisions</li></ul><p>By understanding which products complement each other, businesses can significantly increase average order value and conversion rates.</p><p><strong>How to Implement Market Basket Analysis in SQL?</strong><br>The implementation finds product relationships and quantifies their association strength:</p><ul><li>Identify product pairs that appear together in orders</li><li>Calculate co-occurrence frequency for each product pair</li><li>Compute association metrics (support, confidence, lift) between products</li><li>Filter for significant relationships based on minimum thresholds</li></ul><pre>-- Market Basket Analysis<br>-- Step 1: Identify products in each order<br>WITH order_products AS (<br>    SELECT <br>        o.order_id,<br>        oi.product_id,<br>        p.product_name,<br>        c.category_name,<br>        sc.subcategory_name<br>    FROM ecom_db.ecom_intermediate.orders o<br>    JOIN ecom_db.ecom_intermediate.order_items oi ON o.order_id = oi.order_id<br>    JOIN ecom_db.ecom_intermediate.products_enriched p ON oi.product_id = p.product_id<br>    JOIN ecom_db.ecom_intermediate.categories_enriched c ON p.category_id = c.category_id<br>    JOIN ecom_db.ecom_intermediate.subcategories_enriched sc ON p.subcategory_id = sc.subcategory_id<br>),<br>-- Step 2: Create all possible product pairs within orders<br>product_pairs AS (<br>    SELECT<br>        a.product_id AS product_a_id,<br>        a.product_name AS product_a_name,<br>        a.category_name AS product_a_category,<br>        a.subcategory_name AS product_a_subcategory,<br>        b.product_id AS product_b_id,<br>        b.product_name AS product_b_name,<br>        b.category_name AS product_b_category,<br>        b.subcategory_name AS product_b_subcategory,<br>        COUNT(DISTINCT a.order_id) AS co_occurrence_count<br>    FROM order_products a<br>    JOIN order_products b ON a.order_id = b.order_id AND a.product_id &lt; b.product_id<br>    GROUP BY 1, 2, 3, 4, 5, 6, 7, 8<br>),<br>-- Step 3: Calculate individual product frequencies<br>product_frequencies AS (<br>    SELECT<br>        product_id,<br>        product_name,<br>        COUNT(DISTINCT order_id) AS frequency<br>    FROM order_products<br>    GROUP BY 1, 2<br>),<br>-- Step 4: Get total order count for calculations<br>total_orders AS (<br>    SELECT COUNT(DISTINCT order_id) AS total_order_count<br>    FROM ecom_db.ecom_intermediate.orders<br>)<br>-- Final query with association metrics<br>SELECT<br>    pp.product_a_id,<br>    pp.product_a_name,<br>    pp.product_a_category,<br>    pp.product_a_subcategory,<br>    pp.product_b_id,<br>    pp.product_b_name,<br>    pp.product_b_category,<br>    pp.product_b_subcategory,<br>    pp.co_occurrence_count,<br>    pf_a.frequency AS product_a_frequency,<br>    pf_b.frequency AS product_b_frequency,<br>    t.total_order_count,<br>    <br>    -- Support (frequency of pair divided by total orders)<br>    pp.co_occurrence_count / t.total_order_count AS support,<br>    <br>    -- Confidence (how often B is purchased when A is purchased)<br>    pp.co_occurrence_count / pf_a.frequency AS confidence_a_to_b,<br>    pp.co_occurrence_count / pf_b.frequency AS confidence_b_to_a,<br>    <br>    -- Lift (how much more likely B is purchased when A is purchased)<br>    (pp.co_occurrence_count * t.total_order_count) / <br>    (pf_a.frequency * pf_b.frequency) AS lift,<br>    <br>    -- Jaccard similarity (intersection over union)<br>    pp.co_occurrence_count / (pf_a.frequency + pf_b.frequency - pp.co_occurrence_count) AS jaccard_similarity,<br>    <br>    -- Cross category purchase flag<br>    CASE WHEN pp.product_a_category != pp.product_b_category THEN 1 ELSE 0 END AS cross_category_flag<br>FROM product_pairs pp<br>JOIN product_frequencies pf_a ON pp.product_a_id = pf_a.product_id<br>JOIN product_frequencies pf_b ON pp.product_b_id = pf_b.product_id<br>CROSS JOIN total_orders t<br>WHERE pp.co_occurrence_count &gt;= 10  -- Filter for meaningful associations<br>ORDER BY lift DESC, co_occurrence_count DESC;</pre><p>This approach uses association rule mining techniques to identify product relationships, calculating metrics like support, confidence, and lift to quantify the strength of relationships between products purchased together. This analysis uncovers product relationships and purchasing patterns:</p><ul><li>Product pairs commonly purchased together (co-occurrence)</li><li>Strength of product associations through support, confidence, and lift metrics</li><li>Cross-category purchase behavior highlighting complementary products</li><li>Opportunity identification for bundling, promotions, and recommendations</li></ul><p><strong>Results and Insights</strong><br>Market basket analysis typically reveals insights like:</p><p><strong>Complementary products</strong>: Discover that customers who buy protein powder frequently also purchase shaker bottles (high lift value &gt; 3).</p><p>Action: Create bundle offers or “frequently bought together” recommendations.</p><p><strong>Surprising associations</strong>: Find unexpected relationships, like customers who buy running shoes also often purchasing fitness trackers (relationships you might not have anticipated).</p><p>Action: Place these items near each other in physical stores or feature them together online.</p><p><strong>Cross-category insights:</strong> Identify products from different categories that are frequently purchased together, such as yoga mats and meditation apps.</p><p>Action: Create cross-department promotions or themed collections.</p><p><strong>Substitute products:</strong> Identify products with low co-occurrence but similar individual purchase frequencies (low lift values &lt; 1).</p><p>Action: Avoid bundling these together as they may cannibalize each other’s sales.</p><p>These insights directly inform merchandising, marketing, and product development strategies, leading to increased average order value and customer satisfaction.</p><p><strong>Sample Query Results</strong></p><p>Disclaimer: As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D39TkO7SLI7Y012nAUd7Qw.png" /><figcaption>Market Basket Analysis: Sample Query Result Part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgIaPl8-GXGeIDfFKxVU_A.png" /><figcaption>Market Basket Analysis: Sample Query Result Part 2</figcaption></figure><h4>5. Category Performance Trends: Tracking Product Category Dynamics</h4><p><strong>What is Category Performance Analysis?</strong><br>Category performance analysis tracks how different product categories perform over time, examining metrics like revenue, units sold, average selling price, customer count, and review scores on a monthly or quarterly basis. It helps identify growing or declining categories and understand seasonal patterns.</p><p><strong>Why Do We Need Category Performance Analysis?</strong><br>This analysis is essential to:</p><ul><li>Plan and optimize inventory</li><li>Identify emerging trends and opportunities</li><li>Allocate marketing budget to high-potential categories</li><li>Develop product prioritization</li><li>Discontinue underperforming product lines</li></ul><p>Regular monitoring of category performance ensures that your product mix stays aligned with customer demands and market trends.</p><p><strong>How to Implement Category Performance Analysis in SQL?</strong><br>The implementation tracks category metrics over time to identify performance patterns:</p><ul><li>Aggregate sales data by category and time period</li><li>Calculate key performance metrics (orders, revenue, units)</li><li>Compute growth rates using window functions (LAG)</li><li>Rank categories within each time period to track relative performance</li></ul><pre>-- Category Performance Trends<br>-- Step 1: Calculate sales metrics by category and month<br>WITH category_sales_by_period AS (<br>    SELECT<br>        c.category_id,<br>        c.category_name,<br>        DATE_TRUNC(&#39;MONTH&#39;, o.order_date) AS sales_month,<br>        COUNT(DISTINCT o.order_id) AS order_count,<br>        COUNT(DISTINCT o.customer_id) AS customer_count,<br>        SUM(oi.quantity) AS units_sold,<br>        SUM(oi.total_price) AS revenue,<br>        SUM(oi.quantity * p.base_price) AS gross_merchandise_value,<br>        SUM(oi.total_price) / SUM(oi.quantity) AS avg_selling_price,<br>        SUM(oi.total_price) / COUNT(DISTINCT o.order_id) AS avg_order_value,<br>        AVG(r.review_score) AS avg_review_score,<br>        COUNT(DISTINCT r.review_id) AS review_count<br>    FROM ecom_db.ecom_intermediate.categories_enriched c<br>    JOIN ecom_db.ecom_intermediate.products_enriched p ON c.category_id = p.category_id<br>    JOIN ecom_db.ecom_intermediate.order_items oi ON p.product_id = oi.product_id<br>    JOIN ecom_db.ecom_intermediate.orders o ON oi.order_id = o.order_id<br>    LEFT JOIN ecom_db.ecom_intermediate.reviews_enriched r ON p.product_id = r.product_id<br>        AND o.order_id = r.order_id<br>    GROUP BY 1, 2, 3<br>),<br>-- Step 2: Calculate monthly total revenue for share calculation<br>monthly_totals AS (<br>    SELECT <br>        sales_month,<br>        SUM(revenue) AS total_revenue<br>    FROM category_sales_by_period<br>    GROUP BY 1<br>),<br>-- Step 3: Calculate growth metrics and category share<br>category_growth AS (<br>    SELECT<br>        cs.*,<br>        mt.total_revenue AS monthly_revenue,<br>        cs.revenue / mt.total_revenue AS category_share,<br>        LAG(cs.revenue) OVER (PARTITION BY cs.category_id ORDER BY cs.sales_month) AS prev_month_revenue,<br>        LAG(cs.units_sold) OVER (PARTITION BY cs.category_id ORDER BY cs.sales_month) AS prev_month_units<br>    FROM category_sales_by_period cs<br>    JOIN monthly_totals mt ON cs.sales_month = mt.sales_month<br>)<br>-- Final query with growth metrics and rankings<br>SELECT<br>    category_id,<br>    category_name,<br>    sales_month,<br>    order_count,<br>    customer_count,<br>    units_sold,<br>    revenue,<br>    gross_merchandise_value,<br>    avg_selling_price,<br>    avg_order_value,<br>    avg_review_score,<br>    review_count,<br>    category_share,<br>    <br>    -- MoM Growth Metrics<br>    (revenue - prev_month_revenue) / NULLIF(prev_month_revenue, 0) AS revenue_growth_mom,<br>    (units_sold - prev_month_units) / NULLIF(prev_month_units, 0) AS units_growth_mom,<br>    <br>    -- Rolling metrics<br>    SUM(revenue) OVER (PARTITION BY category_id ORDER BY sales_month <br>                      ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS rolling_3month_revenue,<br>    <br>    -- Rank within month<br>    RANK() OVER (PARTITION BY sales_month ORDER BY revenue DESC) AS revenue_rank,<br>    RANK() OVER (PARTITION BY sales_month ORDER BY units_sold DESC) AS units_rank<br>FROM category_growth<br>ORDER BY category_name, sales_month;</pre><p>This approach monitors category performance over time, tracking key metrics like revenue growth, market share, and customer engagement to identify winning and underperforming product categories. This analysis tracks product category metrics over time:</p><ul><li>Month-over-month growth rates in revenue and units sold</li><li>Seasonal fluctuations in category performance</li><li>Share of wallet analysis showing category contribution to total sales</li><li>Customer engagement metrics like average order value and review scores</li></ul><p><strong>Results and Insights</strong><br>Category performance analysis typically reveals insights like:</p><p><strong>Growth categories:</strong> Identify categories growing at 15%+ month-over-month, signaling increasing customer interest.</p><p>Action: Increase inventory levels and marketing spend for these categories.</p><p><strong>Seasonal patterns:</strong> Discover that outdoor equipment sales peak in spring months with 30% higher revenue than average.</p><p>Action: Plan seasonal promotions and inventory buildups ahead of peak periods.</p><p><strong>Category share shifts:</strong> Notice electronics increasing from 15% to 25% of total revenue over six months.</p><p>Action: Expand product selection in growing categories while potentially reducing investment in declining ones.</p><p><strong>Price elasticity:</strong> Observe that a 10% price reduction in kitchen appliances resulted in a 30% increase in units sold.</p><p>Action: Optimize pricing strategies by category based on observed elasticity.</p><p><strong>Customer expansion:</strong> See that the home office category is attracting the most first-time customers.</p><p>Action: Use this category as an entry point for customer acquisition campaigns.</p><p>These insights inform strategic decisions across merchandising, pricing, marketing, and inventory management, ensuring optimal resource allocation and maximizing revenue growth.</p><p><strong>Sample Query Results</strong></p><p>Disclaimer: As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwIwK4_7oVTjVtrwJ_zPSw.png" /><figcaption>Category Performance Analysis: Sample Query Result Part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xktOnAbRcJ1gN3X_a53xWg.png" /><figcaption>Category Performance Analysis: Sample Query Result Part 2</figcaption></figure><h4>6. Seasonal Analysis: Understanding Timing Patterns in Sales</h4><p><strong>What is Seasonal Analysis?</strong><br>Seasonal analysis examines how sales patterns fluctuate throughout the year, identifying daily, weekly, monthly, and seasonal trends. It also recognizes the impact of special shopping periods like Black Friday, holiday seasons, and back-to-school periods on overall sales and category-specific performance.</p><p><strong>Why Do We Need Seasonal Analysis?</strong><br>Understanding seasonal patterns is crucial to:</p><ul><li>Plan inventory to prevent stockouts during peak periods</li><li>Optimize marketing spend timing and messaging</li><li>Plan staffing and resource allocation</li><li>Plan sales forecasting and financial</li><li>Optimize campaign and promotion timing</li></ul><p>Proper seasonal analysis ensures businesses are prepared for predictable fluctuations in demand throughout the year.</p><p><strong>How to Implement Seasonal Analysis in SQL?</strong><br>The implementation involves aggregating sales data by various time periods and calculating seasonal indices:</p><ul><li>Aggregate sales data by date attributes (month, quarter, season)</li><li>Calculate seasonal indices comparing period performance to averages</li><li>Analyze category-specific seasonal patterns</li><li>Identify significant shopping periods and their impact on sales</li></ul><pre>-- Seasonal Analysis<br>-- Step 1: Aggregate sales metrics by day with time period classifications<br>WITH daily_sales AS (<br>    SELECT<br>        DATE_TRUNC(&#39;DAY&#39;, o.order_date) AS sale_date,<br>        EXTRACT(YEAR FROM o.order_date) AS year,<br>        EXTRACT(MONTH FROM o.order_date) AS month,<br>        EXTRACT(DAY FROM o.order_date) AS day,<br>        EXTRACT(DAYOFWEEK FROM o.order_date) AS day_of_week,<br>        EXTRACT(QUARTER FROM o.order_date) AS quarter,<br>        CASE <br>            WHEN EXTRACT(MONTH FROM o.order_date) IN (12, 1, 2) THEN &#39;Winter&#39;<br>            WHEN EXTRACT(MONTH FROM o.order_date) IN (3, 4, 5) THEN &#39;Spring&#39;<br>            WHEN EXTRACT(MONTH FROM o.order_date) IN (6, 7, 8) THEN &#39;Summer&#39;<br>            ELSE &#39;Fall&#39;<br>        END AS season,<br>        CASE<br>            WHEN EXTRACT(MONTH FROM o.order_date) = 11 AND EXTRACT(DAY FROM o.order_date) &gt;= 26 THEN &#39;Black Friday/Cyber Monday&#39;<br>            WHEN EXTRACT(MONTH FROM o.order_date) = 12 AND EXTRACT(DAY FROM o.order_date) &gt;= 10 AND EXTRACT(DAY FROM o.order_date) &lt;= 24 THEN &#39;Holiday Shopping&#39;<br>            WHEN EXTRACT(MONTH FROM o.order_date) = 2 AND EXTRACT(DAY FROM o.order_date) &gt;= 1 AND EXTRACT(DAY FROM o.order_date) &lt;= 14 THEN &#39;Valentine&#39;&#39;s Day&#39;<br>            WHEN EXTRACT(MONTH FROM o.order_date) = 7 AND EXTRACT(DAY FROM o.order_date) &gt;= 1 AND EXTRACT(DAY FROM o.order_date) &lt;= 31 THEN &#39;Summer Sale&#39;<br>            WHEN EXTRACT(MONTH FROM o.order_date) = 8 AND EXTRACT(DAY FROM o.order_date) &gt;= 15 AND EXTRACT(DAY FROM o.order_date) &lt;= 31 THEN &#39;Back to School&#39;<br>            WHEN EXTRACT(MONTH FROM o.order_date) = 5 AND EXTRACT(DAY FROM o.order_date) &gt;= 1 AND EXTRACT(DAY FROM o.order_date) &lt;= 10 THEN &#39;Mother&#39;&#39;s Day&#39;<br>            WHEN EXTRACT(MONTH FROM o.order_date) = 6 AND EXTRACT(DAY FROM o.order_date) &gt;= 10 AND EXTRACT(DAY FROM o.order_date) &lt;= 20 THEN &#39;Father&#39;&#39;s Day&#39;<br>            WHEN EXTRACT(MONTH FROM o.order_date) = 4 AND EXTRACT(DAY FROM o.order_date) &gt;= 10 AND EXTRACT(DAY FROM o.order_date) &lt;= 25 THEN &#39;Spring Sale&#39;<br>            ELSE &#39;Regular Period&#39;<br>        END AS shopping_period,<br>        -- Sales metrics<br>        COUNT(DISTINCT o.order_id) AS order_count,<br>        SUM(o.total_amount) AS daily_revenue,<br>        COUNT(DISTINCT o.customer_id) AS customer_count<br>    FROM ecom_db.ecom_intermediate.orders o<br>    GROUP BY 1, 2, 3, 4, 5, 6, 7, 8<br>),<br>-- Step 2: Calculate moving averages and period benchmarks<br>rolling_aggregates AS (<br>    SELECT<br>        sale_date,<br>        year,<br>        month,<br>        day,<br>        day_of_week,<br>        quarter,<br>        season,<br>        shopping_period,<br>        order_count,<br>        daily_revenue,<br>        customer_count,<br>        -- 7-day moving average<br>        AVG(daily_revenue) OVER (ORDER BY sale_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7_revenue,<br>        -- 28-day moving average (approximating monthly)<br>        AVG(daily_revenue) OVER (ORDER BY sale_date ROWS BETWEEN 27 PRECEDING AND CURRENT ROW) AS ma28_revenue,<br>        -- Day of week average<br>        AVG(daily_revenue) OVER (PARTITION BY day_of_week) AS avg_day_of_week_revenue,<br>        -- Month average<br>        AVG(daily_revenue) OVER (PARTITION BY month) AS avg_month_revenue<br>    FROM daily_sales<br>)<br><br>SELECT <br>    month,<br>    season,<br>    AVG(daily_revenue) AS avg_daily_revenue,<br>    SUM(daily_revenue) AS total_revenue,<br>    SUM(order_count) AS total_orders,<br>    SUM(customer_count) AS total_customers,<br>    AVG(daily_revenue) / AVG(avg_month_revenue) AS seasonal_index<br>FROM rolling_aggregates<br>GROUP BY month, season<br>ORDER BY month, season;<br><br><br>-- Category Seasonal Patterns<br>WITH category_daily_sales AS (<br>    SELECT<br>        DATE_TRUNC(&#39;DAY&#39;, o.order_date) AS sale_date,<br>        c.category_name,<br>        sc.subcategory_name,<br>        COUNT(DISTINCT o.order_id) AS order_count,<br>        SUM(oi.total_price) AS category_revenue,<br>        SUM(oi.quantity) AS units_sold<br>    FROM ecom_db.ecom_intermediate.orders o<br>    JOIN ecom_db.ecom_intermediate.order_items oi ON o.order_id = oi.order_id<br>    JOIN ecom_db.ecom_intermediate.products_enriched p ON oi.product_id = p.product_id<br>    JOIN ecom_db.ecom_intermediate.categories_enriched c ON p.category_id = c.category_id<br>    JOIN ecom_db.ecom_intermediate.subcategories_enriched sc ON p.subcategory_id = sc.subcategory_id<br>    GROUP BY sale_date, c.category_name, sc.subcategory_name<br>)<br><br>SELECT<br>    month_number,<br>    season_name,<br>    category_name,<br>    SUM(category_revenue) AS total_revenue,<br>    SUM(units_sold) AS total_units,<br>    AVG(category_revenue) AS avg_daily_revenue,<br>    -- Category seasonal index<br>    SUM(category_revenue) / <br>      (SELECT AVG(cat_revenue) <br>       FROM (SELECT DATE_TRUNC(&#39;MONTH&#39;, sale_date) AS month, <br>                    category_name, <br>                    SUM(category_revenue) AS cat_revenue <br>             FROM category_daily_sales <br>             GROUP BY month, category_name) x <br>       WHERE x.category_name = category_daily_sales.category_name) AS category_seasonal_index<br>FROM <br>    (SELECT<br>        EXTRACT(MONTH FROM sale_date) AS month_number,<br>        CASE <br>            WHEN EXTRACT(MONTH FROM sale_date) IN (12, 1, 2) THEN &#39;Winter&#39;<br>            WHEN EXTRACT(MONTH FROM sale_date) IN (3, 4, 5) THEN &#39;Spring&#39;<br>            WHEN EXTRACT(MONTH FROM sale_date) IN (6, 7, 8) THEN &#39;Summer&#39;<br>            ELSE &#39;Fall&#39;<br>        END AS season_name,<br>        category_name,<br>        category_revenue,<br>        units_sold<br>    FROM category_daily_sales) category_daily_sales<br>GROUP BY month_number, season_name, category_name<br>ORDER BY category_name, month_number;</pre><p>This approach identifies cyclical patterns in sales data across different time periods, creating seasonal indices that quantify the impact of time-based factors on purchasing behavior by product category. This analysis examines time-based patterns in shopping behavior:</p><ul><li>Monthly and quarterly sales patterns across different product categories</li><li>Seasonal indices highlighting peak periods for specific product types</li><li>Shopping period performance during holidays and promotional events</li><li>Day-of-week patterns revealing optimal times for marketing activities</li></ul><p><strong>Results and Insights</strong><br>Seasonal analysis typically reveals patterns like:</p><p><strong>Day-of-week patterns:</strong> Revenue on weekends is typically 40% higher than on weekdays, with Sunday evening showing the highest conversion rates.</p><p>Action: Schedule email campaigns and new product releases for high-engagement periods.</p><p><strong>Monthly seasonality:</strong> December showing 2.5x the average monthly revenue due to holiday shopping.</p><p>Action: Prepare inventory and logistics for handling the increased volume.</p><p><strong>Category seasonality:</strong> Winter apparel peaks in October-November (seasonal index of 2.3), while fitness equipment spikes in January (seasonal index of 1.8).</p><p>Action: Adjust category promotion timing to align with natural demand cycles.</p><p><strong>Shopping period impact:</strong> Black Friday/Cyber Monday period generates 4x normal daily revenue but with 15% lower average order values due to discounting.</p><p>Action: Plan bundle strategies to maintain margins during high-discount periods.</p><p><strong>Year-over-year patterns:</strong> Back-to-school spending starting earlier each year, shifting from August to late July.</p><p>Action: Adjust campaign timing based on evolving consumer behavior.</p><p>These insights enable businesses to optimize inventory, marketing, staffing, and promotional calendars around predictable demand fluctuations, maximizing revenue while minimizing costs.</p><p><strong>Sample Query Results</strong></p><p>Disclaimer: As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dz2-u6u_w6siCd1g_bI1Xw.png" /><figcaption>Seasonal Analysis: Sample Query Result</figcaption></figure><h3>III. Sales and Revenue Analysis</h3><p>Effective sales and revenue analysis is the backbone of strategic business planning for e-commerce companies. By examining historical sales patterns, customer cohort behavior, and conversion metrics, businesses can forecast future performance, allocate resources efficiently, and identify opportunities for growth.</p><p>The following three analyses focus on critical revenue dynamics: predicting future revenue trends, understanding how customer cohorts contribute to revenue over time, and analyzing the sales funnel to identify conversion bottlenecks. These insights provide the foundation for financial planning, marketing optimization, and overall business strategy development.</p><h4>7. Revenue Forecasting: Predicting Future Sales</h4><p><strong>What is Revenue Forecasting?</strong><br>Revenue forecasting uses historical sales data to predict future revenue. It employs various techniques like trend analysis, growth rate calculations, moving averages, and seasonal adjustments to create reliable projections for business planning. By analyzing patterns in historical sales data, businesses can estimate future performance with a reasonable degree of accuracy and confidence.</p><p><strong>Why Do We Need Revenue Forecasting?</strong><br>Accurate revenue forecasting is critical to:</p><ul><li>Make data-driven financial plans and budgets</li><li>Optimize inventory levels and supply chain operations to meet anticipated demand without excess</li><li>Allocate human resources and operational capacity strategically</li><li>Establish achievable sales targets that motivate teams while remaining grounded in historical performance patterns</li><li>Confidently make long-term strategic investments with a clear understanding of expected cash flow and ROI timing</li></ul><p>Good forecasting reduces uncertainty and enables more confident business decisions across all departments.</p><p><strong>How to Implement Revenue Forecasting in SQL?</strong><br>The implementation uses historical patterns to predict future revenue:</p><ul><li>Aggregate revenue by time period (daily, monthly)</li><li>Calculate growth rates and moving averages using window functions</li><li>Implement multiple forecasting methods (trend-based, growth-based, hybrid)</li><li>Compare forecast accuracy against actual values to determine best method</li></ul><pre>-- Revenue Forecasting with Window Functions<br>-- Step 1: Aggregate daily sales to monthly level<br>WITH daily_revenue AS (<br>    SELECT<br>        DATE_TRUNC(&#39;DAY&#39;, order_date) AS sale_date,<br>        SUM(total_amount) AS daily_revenue<br>    FROM ecom_db.ecom_intermediate.orders<br>    GROUP BY 1<br>),<br>monthly_revenue AS (<br>    SELECT<br>        DATE_TRUNC(&#39;MONTH&#39;, sale_date) AS month,<br>        SUM(daily_revenue) AS monthly_revenue<br>    FROM daily_revenue<br>    GROUP BY 1<br>),<br>-- Step 2: Calculate growth rates and moving averages<br>revenue_with_growth AS (<br>    SELECT<br>        month,<br>        monthly_revenue,<br>        LAG(monthly_revenue) OVER (ORDER BY month) AS prev_month_revenue,<br>        monthly_revenue / NULLIF(LAG(monthly_revenue) OVER (ORDER BY month), 0) - 1 AS mom_growth_rate,<br>        monthly_revenue / NULLIF(LAG(monthly_revenue, 12) OVER (ORDER BY month), 0) - 1 AS yoy_growth_rate,<br>        AVG(monthly_revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ma3,<br>        AVG(monthly_revenue) OVER (ORDER BY month ROWS BETWEEN 11 PRECEDING AND CURRENT ROW) AS ma12,<br>        ROW_NUMBER() OVER (ORDER BY month) AS month_index<br>    FROM monthly_revenue<br>),<br>-- Step 3: Calculate trend-based forecasts<br>simple_growth_trends AS (<br>    SELECT<br>        month,<br>        monthly_revenue,<br>        mom_growth_rate,<br>        yoy_growth_rate,<br>        -- Average growth rate over last 6 months<br>        AVG(mom_growth_rate) OVER (ORDER BY month ROWS BETWEEN 5 PRECEDING AND CURRENT ROW) AS avg_growth_6m,<br>        -- Average YoY growth rate<br>        AVG(yoy_growth_rate) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS avg_yoy_growth_3m,<br>        ma3,<br>        ma12,<br>        month_index<br>    FROM revenue_with_growth<br>    WHERE mom_growth_rate IS NOT NULL<br>),<br>-- Step 4: Generate forecasts using different methods<br>forecast_data AS (<br>    SELECT<br>        month,<br>        monthly_revenue AS actual_revenue,<br>        LEAD(monthly_revenue, 1) OVER (ORDER BY month) AS next_month_actual,<br>        LEAD(monthly_revenue, 3) OVER (ORDER BY month) AS three_month_actual,<br>        -- Simple trend-based forecasts<br>        monthly_revenue * (1 + mom_growth_rate) AS trend_forecast_1m,<br>        monthly_revenue * POWER(1 + mom_growth_rate, 3) AS trend_forecast_3m,<br>        -- Moving average forecast<br>        ma3 AS ma3_forecast,<br>        -- Growth-based forecast<br>        monthly_revenue * (1 + avg_growth_6m) AS growth_forecast_1m,<br>        monthly_revenue * POWER(1 + avg_growth_6m, 3) AS growth_forecast_3m,<br>        -- Seasonal forecast (combining YoY with recent trend)<br>        monthly_revenue * (1 + (avg_yoy_growth_3m + avg_growth_6m) / 2) AS seasonal_forecast_1m,<br>        -- Hybrid forecast (average of methods)<br>        (monthly_revenue * (1 + mom_growth_rate) + <br>         ma3 + <br>         monthly_revenue * (1 + avg_growth_6m)) / 3 AS hybrid_forecast_1m<br>    FROM simple_growth_trends<br>)<br>-- Final query with forecast accuracy<br>SELECT<br>    month,<br>    actual_revenue,<br>    next_month_actual,<br>    three_month_actual,<br>    trend_forecast_1m,<br>    growth_forecast_1m,<br>    seasonal_forecast_1m,<br>    hybrid_forecast_1m,<br>    trend_forecast_3m,<br>    growth_forecast_3m,<br>    <br>    -- Forecast accuracy (comparing to actual)<br>    ABS(trend_forecast_1m - next_month_actual) / NULLIF(next_month_actual, 0) AS trend_1m_error,<br>    ABS(growth_forecast_1m - next_month_actual) / NULLIF(next_month_actual, 0) AS growth_1m_error,<br>    ABS(seasonal_forecast_1m - next_month_actual) / NULLIF(next_month_actual, 0) AS seasonal_1m_error,<br>    ABS(hybrid_forecast_1m - next_month_actual) / NULLIF(next_month_actual, 0) AS hybrid_1m_error,<br>    <br>    -- 3-month forecast accuracy<br>    ABS(trend_forecast_3m - three_month_actual) / NULLIF(three_month_actual, 0) AS trend_3m_error,<br>    ABS(growth_forecast_3m - three_month_actual) / NULLIF(three_month_actual, 0) AS growth_3m_error<br>FROM forecast_data<br>WHERE next_month_actual IS NOT NULL<br>ORDER BY month;</pre><p>This approach combines time series analysis with multiple forecasting methodologies, evaluating their historical accuracy to create reliable revenue projections that account for both trends and seasonal factors. This analysis predicts future revenue using multiple modeling approaches:</p><ul><li>Trend-based forecasts using recent growth patterns</li><li>Moving averages to smooth out short-term fluctuations</li><li>Seasonal adjustments accounting for cyclical patterns</li><li>Hybrid models combining multiple forecasting techniques</li><li>Accuracy comparison to determine the most reliable prediction method</li></ul><p><strong>Results and Insights</strong><br>Revenue forecasting analysis typically reveals insights like:</p><p><strong>Forecast accuracy comparison:</strong> The hybrid forecasting method that combines multiple approaches (trend, growth rate, and moving averages) often achieves 10–15% better accuracy than any single method.</p><p>Action: Implement ensemble forecasting techniques rather than relying on a single prediction method.</p><p><strong>Seasonality impacts:</strong> Certain business periods like Q4 consistently show prediction errors 25% higher than other quarters due to holiday promotions and sales events.</p><p>Action: Apply seasonal adjustment factors to improve forecast accuracy during high-volatility periods.</p><p><strong>Growth pattern recognition:</strong> New product categories often follow a predictable growth curve, with 40–50% monthly growth in the first quarter that gradually stabilizes to 5–10% by month six.</p><p>Action: Use category lifecycle stage to adjust forecasting models for newly launched categories.</p><p><strong>External factor correlations:</strong> Marketing campaign periods show systematic revenue increases that distort time-series forecasts by 15–30%.</p><p>Action: Incorporate marketing calendar events as adjustment factors in forecasting models.</p><p>These insights help improve forecast accuracy and allow businesses to make more confident inventory, staffing, and financial planning decisions.</p><p><strong>Sample Query Results</strong></p><p>Disclaimer: As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAGAZsXT8W3PaQYg7mK9hQ.png" /><figcaption>Revenue Forecasting: Sample Query Result Part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3x_DBEI9dvCF8TEf7olCKg.png" /><figcaption>Revenue Forecasting: Sample Query Result Part 2</figcaption></figure><h3>8. Customer Cohort Analysis: Tracking Customer Performance Over Time</h3><p><strong>What is Customer Cohort Analysis?</strong><br>Customer cohort analysis groups customers based on shared acquisition periods (typically months) and tracks their behavior over time. This analysis examines how metrics like retention rates, purchase frequency, and revenue per customer evolve for each cohort as they mature in their customer lifecycle. By organizing customers into cohorts, businesses can isolate the impact of timing, compare the long-term performance of different customer groups, and identify trends in customer behavior patterns.</p><p><strong>Why Do We Need Customer Cohort Analysis?</strong><br>Cohort analysis provides critical insights that aggregate metrics often miss:</p><ul><li>Understand how customer retention changes over time for different acquisition groups</li><li>Track how customer value evolves over their lifetime</li><li>Compare the long-term performance of customers acquired in different periods</li><li>Measure the impact of specific acquisition campaigns on customer quality</li><li>Identify declining retention or spend in recent cohorts that might signal problems</li></ul><p>This analysis helps businesses understand whether customer quality is improving or deteriorating over time, which acquisition channels deliver the best long-term customers, and how changes to the product or experience affect customer behavior.</p><p><strong>How to Implement Customer Cohort Analysis in SQL?</strong><br>The implementation tracks customer groups from first purchase through their lifecycle:</p><ul><li>Group customers by cohort (first purchase month)</li><li>Track activity and spending over time using month number from cohort start</li><li>Calculate retention rates and revenue metrics for each cohort period</li><li>Analyze cohort performance patterns to evaluate customer lifetime development</li></ul><pre>-- Customer Cohort Analysis<br>-- Step 1: Identify first purchase date for each customer<br>WITH first_purchases AS (<br>    SELECT<br>        c.customer_id,<br>        c.first_name,<br>        c.last_name,<br>        c.email,<br>        c.age,<br>        c.gender,<br>        c.annual_income,<br>        l.city,<br>        l.state,<br>        DATE_TRUNC(&#39;MONTH&#39;, MIN(o.order_date)) AS cohort_month,<br>        MIN(o.order_date) AS first_purchase_date<br>    FROM ecom_db.ecom_intermediate.customers_enriched c<br>    LEFT JOIN ecom_db.ecom_intermediate.locations l ON c.location_id = l.location_id<br>    JOIN ecom_db.ecom_intermediate.orders o ON c.customer_id = o.customer_id<br>    GROUP BY 1, 2, 3, 4, 5, 6, 7, 8, 9<br>),<br>-- Step 2: Calculate activity by month for each customer<br>customer_monthly_activity AS (<br>    SELECT<br>        fp.customer_id,<br>        fp.cohort_month,<br>        DATE_TRUNC(&#39;MONTH&#39;, o.order_date) AS activity_month,<br>        DATEDIFF(&#39;MONTH&#39;, fp.cohort_month, DATE_TRUNC(&#39;MONTH&#39;, o.order_date)) AS cohort_month_number,<br>        COUNT(DISTINCT o.order_id) AS orders,<br>        SUM(o.total_amount) AS spend<br>    FROM first_purchases fp<br>    JOIN ecom_db.ecom_intermediate.orders o ON fp.customer_id = o.customer_id<br>    GROUP BY 1, 2, 3, 4<br>),<br>-- Step 3: Calculate cohort sizes<br>cohort_sizes AS (<br>    SELECT<br>        cohort_month,<br>        COUNT(DISTINCT customer_id) AS cohort_customers<br>    FROM first_purchases<br>    GROUP BY 1<br>),<br>-- Step 4: Calculate retention and revenue metrics<br>retention_analysis AS (<br>    SELECT<br>        a.cohort_month,<br>        a.cohort_month_number,<br>        cs.cohort_customers,<br>        COUNT(DISTINCT a.customer_id) AS active_customers,<br>        COUNT(DISTINCT a.customer_id) / cs.cohort_customers AS retention_rate,<br>        SUM(a.spend) AS total_revenue,<br>        SUM(a.spend) / COUNT(DISTINCT a.customer_id) AS revenue_per_customer,<br>        SUM(a.spend) / cs.cohort_customers AS revenue_per_cohort_customer<br>    FROM customer_monthly_activity a<br>    JOIN cohort_sizes cs ON a.cohort_month = cs.cohort_month<br>    GROUP BY 1, 2, 3<br>),<br>-- Step 5: Calculate cohort summary metrics<br>cohort_metrics_by_month AS (<br>    SELECT<br>        cohort_month,<br>        cohort_customers,<br>        -- Retention after N months<br>        MAX(CASE WHEN cohort_month_number = 1 THEN retention_rate ELSE NULL END) AS m1_retention,<br>        MAX(CASE WHEN cohort_month_number = 2 THEN retention_rate ELSE NULL END) AS m2_retention,<br>        MAX(CASE WHEN cohort_month_number = 3 THEN retention_rate ELSE NULL END) AS m3_retention,<br>        MAX(CASE WHEN cohort_month_number = 6 THEN retention_rate ELSE NULL END) AS m6_retention,<br>        MAX(CASE WHEN cohort_month_number = 12 THEN retention_rate ELSE NULL END) AS m12_retention,<br>        -- Cumulative revenue per customer<br>        SUM(CASE WHEN cohort_month_number &lt;= 1 THEN total_revenue ELSE 0 END) / cohort_customers AS m1_cumulative_revenue,<br>        SUM(CASE WHEN cohort_month_number &lt;= 3 THEN total_revenue ELSE 0 END) / cohort_customers AS m3_cumulative_revenue,<br>        SUM(CASE WHEN cohort_month_number &lt;= 6 THEN total_revenue ELSE 0 END) / cohort_customers AS m6_cumulative_revenue,<br>        SUM(CASE WHEN cohort_month_number &lt;= 12 THEN total_revenue ELSE 0 END) / cohort_customers AS m12_cumulative_revenue,<br>        -- Average revenue per active customer by period <br>        AVG(CASE WHEN cohort_month_number &lt;= 3 THEN revenue_per_customer ELSE NULL END) AS m3_avg_revenue_per_active,<br>        AVG(CASE WHEN cohort_month_number &gt; 3 AND cohort_month_number &lt;= 6 THEN revenue_per_customer ELSE NULL END) AS m4_6_avg_revenue_per_active,<br>        AVG(CASE WHEN cohort_month_number &gt; 6 THEN revenue_per_customer ELSE NULL END) AS m7plus_avg_revenue_per_active<br>    FROM retention_analysis<br>    GROUP BY 1, 2<br>)<br><br>-- Change the value of this parameter to switch between the two analyses<br>-- Set to 1 for Cohort Retention Matrix, 2 for Cohort Performance Summary<br>SELECT * FROM (SELECT 2 AS analysis_type) t<br>CROSS JOIN LATERAL (<br>    -- Analysis Type 1: Cohort Retention Matrix<br>    SELECT<br>        cohort_month,<br>        cohort_month_number,<br>        active_customers,<br>        retention_rate,<br>        total_revenue,<br>        revenue_per_customer,<br>        revenue_per_cohort_customer,<br>        NULL AS cohort_classification,<br>        -- Indexing to first month<br>        retention_rate / FIRST_VALUE(retention_rate) OVER (PARTITION BY cohort_month ORDER BY cohort_month_number) AS indexed_retention,<br>        revenue_per_customer / FIRST_VALUE(revenue_per_customer) OVER (PARTITION BY cohort_month ORDER BY cohort_month_number) AS indexed_revenue_per_customer,<br>        total_revenue / FIRST_VALUE(total_revenue) OVER (PARTITION BY cohort_month ORDER BY cohort_month_number) AS indexed_total_revenue<br>    FROM retention_analysis<br>    WHERE t.analysis_type = 1<br>    <br>    UNION ALL<br>    <br>    -- Analysis Type 2: Cohort Performance Summary<br>    SELECT<br>        cohort_month,<br>        NULL AS cohort_month_number,<br>        cohort_customers AS active_customers,<br>        m1_retention AS retention_rate,<br>        m3_cumulative_revenue AS total_revenue,<br>        m3_avg_revenue_per_active AS revenue_per_customer,<br>        m3_cumulative_revenue / cohort_customers AS revenue_per_cohort_customer,<br>        CASE<br>            WHEN m3_retention &gt; 0.3 AND m3_cumulative_revenue &gt; 7000 THEN &#39;High Value Cohort&#39;<br>            WHEN m3_retention &gt; 0.3 THEN &#39;High Retention Cohort&#39;<br>            WHEN m3_cumulative_revenue &gt; 7000 THEN &#39;High Revenue Cohort&#39;<br>            ELSE &#39;Standard Cohort&#39;<br>        END AS cohort_classification,<br>        m2_retention AS indexed_retention,<br>        m3_retention AS indexed_revenue_per_customer,<br>        m6_retention AS indexed_total_revenue<br>    FROM cohort_metrics_by_month<br>    WHERE t.analysis_type = 2<br>) result<br>ORDER BY cohort_month, COALESCE(cohort_month_number, 0);</pre><p>This approach groups customers by their acquisition period and tracks their behavior over time, revealing how retention, spending, and engagement evolve throughout the customer lifecycle for different customer vintages. This analysis tracks customer groups over time from their first purchase:</p><ul><li>Retention rates showing how well cohorts maintain engagement</li><li>Revenue progression revealing cohort value development over time</li><li>Cohort classification based on retention and spending patterns</li><li>Comparison between acquisition periods to evaluate marketing effectiveness</li></ul><p><strong>Results and Insights</strong><br>Customer cohort analysis typically reveals insights like:</p><p><strong>Retention drop-off patterns: </strong>Most cohorts show a similar retention curve, with a 40–50% drop after the first month, another 20% drop by month three, then a gradual stabilization of the active customer base.</p><p>Action: Focus retention efforts on the critical first 90 days of the customer lifecycle.</p><p><strong>Cohort quality trends:</strong> Recent cohorts (last 6 months) show 15–20% better 3-month retention rates than cohorts from the previous year, indicating improved customer acquisition or product experience.</p><p>Action: Identify changes in acquisition strategy or product features that might explain the improvement.</p><p><strong>Seasonal acquisition effects:</strong> Customers acquired during promotional periods (Black Friday, holiday season) typically show 25–30% lower retention rates but 40% higher initial spending.</p><p>Action: Adjust expectations and retention strategies for customers acquired during high-promotion periods.</p><p><strong>Revenue maturation:</strong> The average revenue per active customer typically increases by 35–45% after the sixth month, indicating that retained customers become more valuable over time.</p><p>Action: Calculate the ROI of retention initiatives based on the increased value of long-term customers.</p><p>These insights help businesses understand the long-term value of different customer acquisition efforts and focus retention strategies on the most critical periods in the customer lifecycle.</p><p><strong>Sample Query Results</strong></p><p>Disclaimer: As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AGIzgKWAuJ4l1jw6-jzJA.png" /><figcaption>Cohort Retention Matrix: Sample Query Result Part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amLqUEYeubU6D5UQU-IPng.png" /><figcaption>Cohort Retention Matrix: Sample Query Result Part 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQSRbeZUb_GEuZJ6TFgZkA.png" /><figcaption>Cohort Performance Summary: Sample Query Result Part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LUFVQpYeT7VwXrBkfxDCA.png" /><figcaption>Cohort Performance Summary: Sample Query Result Part 2</figcaption></figure><h3><strong>9. Sales Funnel Conversion Analysis: Understanding the Customer Journey</strong></h3><p><strong>What is Sales Funnel Conversion Analysis?</strong><br>Sales funnel conversion analysis examines how customers move through each stage of the purchase process, from initial product discovery to final purchase. It tracks metrics like conversion rates between funnel stages, drop-off points, and stage-by-stage progression for different product categories, customer segments, and time periods. This analysis helps businesses understand where, why, and how many potential customers are lost during the purchase journey.</p><p><strong>Why Do We Need Sales Funnel Conversion Analysis?</strong><br>Understanding the sales funnel is critical for several reasons:</p><ul><li>Identify bottlenecks and high drop-off points in the customer journey</li><li>Focus optimization efforts on stages with the greatest impact on final conversion</li><li>Understand friction points that prevent customers from completing purchases</li><li>Evaluate which products, campaigns, or customer segments show better progression through the funnel</li><li>Determine which funnel stages should be prioritized for testing and improvement</li></ul><p>By tracking funnel metrics, businesses can systematically improve the customer journey, increase conversion rates, and maximize return on marketing investments.</p><p><strong>How to Implement Sales Funnel Conversion Analysis in SQL?</strong><br>The implementation maps customer journey stages and calculates conversion rates:</p><ul><li>Identify key events in the customer journey (view, cart add, purchase)</li><li>Calculate stage progression flags for each customer-product interaction</li><li>Aggregate funnel metrics by time period, product category, or device type</li><li>Compute conversion rates between consecutive funnel stages</li></ul><pre>-- Sales Funnel Conversion Analysis<br>-- Step 1: Identify customer interactions and purchase events<br>WITH customer_journey_stages AS (<br>    SELECT<br>        ci.customer_id,<br>        ci.product_id,<br>        ci.event_type,<br>        ci.event_date,<br>        ci.device_type,<br>        ci.session_id,<br>        p.product_name,<br>        p.category_id,<br>        c.category_name,<br>        -- Flag product purchases from order data<br>        CASE WHEN o.order_id IS NOT NULL THEN 1 ELSE 0 END AS purchased_flag<br>    FROM ecom_db.ecom_intermediate.customer_interactions ci<br>    JOIN ecom_db.ecom_intermediate.products_enriched p ON ci.product_id = p.product_id<br>    JOIN ecom_db.ecom_intermediate.categories_enriched c ON p.category_id = c.category_id<br>    LEFT JOIN ecom_db.ecom_intermediate.order_items oi ON ci.product_id = oi.product_id <br>        AND ci.customer_id = oi.customer_id<br>    LEFT JOIN ecom_db.ecom_intermediate.orders o ON oi.order_id = o.order_id <br>        AND ci.customer_id = o.customer_id<br>        AND o.order_date &gt;= ci.event_date<br>),<br>-- Step 2: Aggregate events by funnel stage<br>funnel_events AS (<br>    SELECT<br>        customer_id,<br>        DATE_TRUNC(&#39;DAY&#39;, event_date) AS event_day,<br>        session_id,<br>        product_id,<br>        category_id,<br>        category_name,<br>        device_type,<br>        -- Identify customer stage in the funnel<br>        MAX(CASE WHEN event_type = &#39;view&#39; THEN 1 ELSE 0 END) AS view_flag,<br>        MAX(CASE WHEN event_type = &#39;search&#39; THEN 1 ELSE 0 END) AS search_flag,<br>        MAX(CASE WHEN event_type = &#39;cart_add&#39; THEN 1 ELSE 0 END) AS cart_add_flag,<br>        MAX(CASE WHEN event_type = &#39;cart_remove&#39; THEN 1 ELSE 0 END) AS cart_remove_flag,<br>        MAX(purchased_flag) AS purchase_flag,<br>        -- Calculate adjusted cart adds (cart adds minus cart removes)<br>        MAX(CASE WHEN event_type = &#39;cart_add&#39; THEN 1 ELSE 0 END) - <br>            MAX(CASE WHEN event_type = &#39;cart_remove&#39; THEN 1 ELSE 0 END) AS net_cart_adds<br>    FROM customer_journey_stages<br>    GROUP BY 1, 2, 3, 4, 5, 6, 7<br>),<br>-- Step 3: Calculate daily conversion rates by funnel stage<br>funnel_progression AS (<br>    SELECT<br>        event_day,<br>        category_name,<br>        device_type,<br>        COUNT(DISTINCT CASE WHEN search_flag = 1 THEN session_id END) AS unique_searches,<br>        COUNT(DISTINCT CASE WHEN view_flag = 1 THEN session_id END) AS unique_views,<br>        COUNT(DISTINCT CASE WHEN cart_add_flag = 1 THEN session_id END) AS unique_cart_adds,<br>        COUNT(DISTINCT CASE WHEN net_cart_adds &gt; 0 THEN session_id END) AS unique_net_cart_adds,<br>        COUNT(DISTINCT CASE WHEN purchase_flag = 1 THEN session_id END) AS unique_purchases,<br>        -- Conversion rates by session<br>        COUNT(DISTINCT CASE WHEN view_flag = 1 THEN session_id END) / <br>            NULLIF(COUNT(DISTINCT CASE WHEN search_flag = 1 THEN session_id END), 0) AS search_to_view_rate,<br>        COUNT(DISTINCT CASE WHEN cart_add_flag = 1 THEN session_id END) / <br>            NULLIF(COUNT(DISTINCT CASE WHEN view_flag = 1 THEN session_id END), 0) AS view_to_cart_rate,<br>        COUNT(DISTINCT CASE WHEN net_cart_adds &gt; 0 THEN session_id END) / <br>            NULLIF(COUNT(DISTINCT CASE WHEN cart_add_flag = 1 THEN session_id END), 0) AS cart_retention_rate,<br>        COUNT(DISTINCT CASE WHEN purchase_flag = 1 THEN session_id END) / <br>            NULLIF(COUNT(DISTINCT CASE WHEN net_cart_adds &gt; 0 THEN session_id END), 0) AS cart_to_purchase_rate,<br>        -- End-to-end funnel conversion<br>        COUNT(DISTINCT CASE WHEN purchase_flag = 1 THEN session_id END) / <br>            NULLIF(COUNT(DISTINCT session_id), 0) AS session_conversion_rate<br>    FROM funnel_events<br>    GROUP BY 1, 2, 3<br>),<br>-- Step 4: Calculate customer-level funnel metrics<br>customer_level_funnel AS (<br>    SELECT<br>        customer_id,<br>        -- Calculate progress through the funnel for each customer<br>        MAX(search_flag) AS reached_search,<br>        MAX(view_flag) AS reached_view,<br>        MAX(cart_add_flag) AS reached_cart_add,<br>        MAX(CASE WHEN net_cart_adds &gt; 0 THEN 1 ELSE 0 END) AS reached_net_cart_add,<br>        MAX(purchase_flag) AS reached_purchase,<br>        -- Count interactions<br>        SUM(search_flag) AS search_count,<br>        SUM(view_flag) AS view_count,<br>        SUM(cart_add_flag) AS cart_add_count,<br>        SUM(net_cart_adds) AS net_cart_adds_count,<br>        SUM(purchase_flag) AS purchase_count,<br>        -- Calculate drop-off stage<br>        CASE<br>            WHEN MAX(purchase_flag) = 1 THEN &#39;Completed Purchase&#39;<br>            WHEN MAX(CASE WHEN net_cart_adds &gt; 0 THEN 1 ELSE 0 END) = 1 THEN &#39;Abandoned Cart&#39;<br>            WHEN MAX(cart_add_flag) = 1 THEN &#39;Removed from Cart&#39;<br>            WHEN MAX(view_flag) = 1 THEN &#39;Viewed Only&#39;<br>            WHEN MAX(search_flag) = 1 THEN &#39;Searched Only&#39;<br>            ELSE &#39;No Engagement&#39;<br>        END AS funnel_stage<br>    FROM funnel_events<br>    GROUP BY 1<br>)<br><br>-- To switch between analyses, uncomment the one you want to run and comment out the others<br><br>-- Analysis 1: Daily Funnel Performance<br>SELECT<br>    event_day,<br>    unique_searches,<br>    unique_views,<br>    unique_cart_adds,<br>    unique_net_cart_adds,<br>    unique_purchases,<br>    search_to_view_rate,<br>    view_to_cart_rate,<br>    cart_retention_rate,<br>    cart_to_purchase_rate,<br>    session_conversion_rate,<br>    -- Calculate overall funnel effectiveness<br>    (search_to_view_rate * view_to_cart_rate * cart_retention_rate * cart_to_purchase_rate) AS funnel_efficiency<br>FROM funnel_progression<br>WHERE unique_searches &gt; 0<br>GROUP BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11<br>ORDER BY event_day;<br><br>-- Analysis 2: Category Funnel Performance<br>-- SELECT<br>--     category_name,<br>--     SUM(unique_searches) AS unique_searches,<br>--     SUM(unique_views) AS unique_views,<br>--     SUM(unique_cart_adds) AS unique_cart_adds,<br>--     SUM(unique_net_cart_adds) AS unique_net_cart_adds,<br>--     SUM(unique_purchases) AS unique_purchases,<br>--     SUM(unique_views) / NULLIF(SUM(unique_searches), 0) AS search_to_view_rate,<br>--     SUM(unique_cart_adds) / NULLIF(SUM(unique_views), 0) AS view_to_cart_rate,<br>--     SUM(unique_net_cart_adds) / NULLIF(SUM(unique_cart_adds), 0) AS cart_retention_rate,<br>--     SUM(unique_purchases) / NULLIF(SUM(unique_net_cart_adds), 0) AS cart_to_purchase_rate,<br>--     SUM(unique_purchases) / NULLIF(SUM(unique_searches), 0) AS session_conversion_rate,<br>--     (SUM(unique_views) / NULLIF(SUM(unique_searches), 0)) * <br>--     (SUM(unique_cart_adds) / NULLIF(SUM(unique_views), 0)) * <br>--     (SUM(unique_net_cart_adds) / NULLIF(SUM(unique_cart_adds), 0)) * <br>--     (SUM(unique_purchases) / NULLIF(SUM(unique_net_cart_adds), 0)) AS funnel_efficiency<br>-- FROM funnel_progression<br>-- GROUP BY 1<br>-- ORDER BY funnel_efficiency DESC;<br><br>-- Analysis 3: Customer Funnel Distribution<br>-- SELECT<br>--     funnel_stage,<br>--     COUNT(DISTINCT customer_id) AS customer_count,<br>--     COUNT(DISTINCT customer_id) / SUM(COUNT(DISTINCT customer_id)) OVER () AS customer_percentage,<br>--     AVG(search_count) AS avg_searches,<br>--     AVG(view_count) AS avg_views,<br>--     AVG(cart_add_count) AS avg_cart_adds,<br>--     AVG(net_cart_adds_count) AS avg_net_cart_adds,<br>--     AVG(purchase_count) AS avg_purchases<br>-- FROM customer_level_funnel<br>-- GROUP BY 1<br>-- ORDER BY customer_count DESC;</pre><p>This approach maps the customer journey from initial engagement to purchase, calculating conversion rates between stages and identifying drop-off points where potential customers abandon the path to purchase. This analysis creates a comprehensive view of the sales funnel across different dimensions:</p><ul><li>Daily performance showing overall conversion trends</li><li>Category performance highlighting product types with better or worse conversion</li><li>Customer-level analysis to identify different customer journey patterns</li><li>Drop-off points in the customer journey from search to purchase</li></ul><p><strong>Results and Insights</strong><br>Sales funnel conversion analysis typically reveals insights like:</p><p><strong>Critical drop-off points:</strong> The largest conversion drop typically occurs at the view-to-cart stage (only 15–20% of product views result in cart additions) and cart-to-purchase stage (40–60% of items added to cart are ultimately purchased).</p><p>Action: Focus UX improvements on product pages to increase add-to-cart rates and streamline checkout to reduce cart abandonment.</p><p><strong>Device-specific patterns:</strong> Mobile sessions often show 30–40% lower cart-to-purchase conversion rates compared to desktop, despite similar view-to-cart rates.</p><p>Action: Optimize the mobile checkout experience to address mobile-specific friction points.</p><p><strong>Category differences: </strong>Electronics products show 25% higher view-to-cart rates but 15% lower cart-to-purchase rates compared to apparel products.</p><p>Action: Enhance product descriptions and specifications for electronics to set better expectations and reduce purchase hesitation.</p><p><strong>Time-based variations:</strong> Conversion rates across all funnel stages are typically 20–30% higher during business hours (9am-5pm) compared to evening hours.</p><p>Action: Schedule customer service availability and promotional campaigns during high-conversion periods.</p><p>These insights inform targeted improvements to the user experience, marketing strategy, and product presentation that can significantly increase overall conversion rates and revenue.</p><p><strong>Sample Query Results</strong></p><p>Disclaimer: As this data was generated using synthetic or random methods documented in this article: <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, some of the events and results do not reflect real-life patterns. The approaches and analytical methods demonstrated here can still be effectively utilized in real-life business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_creY5bX7ImPJNJhw-Mdg.png" /><figcaption>Daily Funnel Performance: Sample Query Result Part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNK3kIvwdh1pZY41KSwbRw.png" /><figcaption>Daily Funnel Performance: Sample Query Result Part 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1Xpm7UsbcAIpf_eJDwHsA.png" /><figcaption>Category Funnel Performance: Sample Query Result Part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1hU87pJx4pU7nNs0yiK8g.png" /><figcaption>Category Funnel Performance: Sample Query Result Part 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLJyW5I5f2YXL_l28kUUxQ.png" /><figcaption>Customer Funnel Distribution: Sample Query Result</figcaption></figure><h3>Wrapping Up</h3><p>These SQL frameworks collectively transform raw e-commerce data into strategic insights, enabling businesses to understand customer behavior, optimize product offerings, and identify growth opportunities without guesswork. By implementing these analyses, companies can transition from reactive to proactive decision-making, creating personalized experiences that drive customer loyalty and sustained revenue growth. Ultimately, mastering these analytical techniques gives e-commerce businesses a competitive edge in an increasingly data-driven marketplace.<br>This concludes the business analysis using SQL for the e-commerce data engineering solution. I hope you found this article insightful and inspiring for your own projects!</p><p>If you have suggestions for improvement, ideas to enhance the solution, or creative ways to expand its functionality, feel free to contribute by creating pull requests (PRs). Collaboration and feedback are always welcome to refine and evolve this solution further.</p><figure><a href="https://buymeacoffee.com/sai_documents"><img alt="" src="https://cdn-images-1.medium.com/max/300/0*vii_qYQF0q4h3bQU.png" /></a></figure><p>Or connect with me on the following:</p><p><a href="https://www.linkedin.com/in/sandy-lauguico/">https://www.linkedin.com/in/sandy-lauguico/</a></p><p><a href="https://github.com/sclauguico">https://github.com/sclauguico</a></p><p><a href="https://www.facebook.com/sandy.c.lauguico/">https://www.facebook.com/sandy.c.lauguico/</a></p><p><a href="https://www.instagram.com/sai_documents/">https://www.instagram.com/sai_documents/</a></p><p>And please give a clap (or claps) below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ad1642107d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECOM Phase 2: Migrate from Snowflake to DuckDB and MotherDuck: A Guide for an eCommerce End-to-End…]]></title>
            <link>https://medium.com/@sclauguico/migrate-from-snowflake-to-duckdb-and-motherduck-a-guide-for-an-ecommerce-end-to-end-data-41fadae1da1b?source=rss-47876a26005------2</link>
            <guid isPermaLink="false">https://medium.com/p/41fadae1da1b</guid>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Sandy Lauguico]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 07:26:23 GMT</pubDate>
            <atom:updated>2025-04-20T04:31:54.624Z</atom:updated>
            <content:encoded><![CDATA[<h3>ECOM Phase 2: Migrate from Snowflake to DuckDB and MotherDuck: A Guide for an eCommerce End-to-End Data Engineering Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*re9qkeAxfZ0703h9k6AEIg.png" /><figcaption>Project Diagram</figcaption></figure><h3>Introduction</h3><p>When my Snowflake 30-day trial expired shortly after publishing Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack, I decided to migrate from Snowflake to an open-source solution: DuckDB for development and MotherDuck for production. This article focuses solely on the migration process. For details on the initial setup, refer to the original <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">article</a>.</p><h3>Project Vision and Scope</h3><p>The project aims to simulate a complete e-commerce data ecosystem, tackling real-world challenges like:</p><ul><li>Migrating from a paid data warehouse to an open-source solution</li><li>Handling both structured and semi-structured data</li><li>Managing incremental data loads</li><li>Implementing proper data modeling practices</li></ul><h3>Data Flow</h3><h3>1. Data Generation</h3><p>The data flow begins with two parallel streams of synthetic data generation:</p><p><strong>Historical Synthetic Data Generation (Initial Load):</strong></p><ul><li><strong>JSON Data</strong>: Customers, products, orders, and reviews data are generated in JSON format and stored in AWS S3.</li><li><strong>Structured Data</strong>: Product categories, subcategories, order items, and interaction data are generated in a structured format and stored in <strong>Postgres</strong> (managed via pgAdmin on Docker).</li></ul><p><strong>Latest (30-day) Synthetic Data Generation (Ongoing Operations):</strong></p><ul><li><strong>JSON Data</strong>: Customers, products, orders, and reviews data are generated in JSON format and stored in AWS S3.</li><li><strong>Structured Data</strong>: Product categories, subcategories, order items, and interaction data are generated in a structured format and stored in <strong>Postgres</strong> (managed via pgAdmin on Docker).</li></ul><h3>2. Data Ingestion</h3><ul><li><strong>JSON Data from S3</strong>: Apache Airflow orchestrates the <strong>ETL (Extract, Transform, Load)</strong> process, appending new JSON records from S3 to historical data, and loading them to the historical data in S3 and DuckDB and MotherDuck raw schema.</li><li><strong>Structured Data from Postgres</strong>: Airflow also orchestrates the <strong>ETL</strong> process, appending new structured records from Postgres to historical data, and loading to the historical data in S3 and DuckDB and MotherDuck raw schema.</li></ul><h3>3. Data Transformation</h3><p>The ingested data is processed with dbt (data build tool) and stored in DuckDB and MotherDuck through different layers:</p><ul><li><strong>Raw Layer</strong>: Data is first dumped in its raw form.</li><li><strong>Staging Layer</strong>: Data is casted into appropriate data types and formats.</li><li><strong>Intermediate Layer</strong>: Data is normalized to remove redundancy and ensure consistency.</li><li><strong>Marts Layer</strong>: Data is aggregated and structured into data marts for specific business use cases.</li></ul><h3>4. Orchestration</h3><ul><li>Orchestrates the latest (last 30 days) synthetic data generation and ingestion</li><li>Orchestrates the transformations across the DuckDB and MotherDuck layers, ensuring proper lineage and documentation.</li></ul><h3>5. Data Serving (Next Project)</h3><p>The processed and aggregated data is served to different downstream systems:</p><ul><li><strong>Business Intelligence</strong>: Aggregated data marts are consumed by Power BI for reporting and dashboards.</li><li><strong>Data Science</strong>: Processed data is used in Jupyter Notebooks for machine learning, statistics, and AI operations.</li></ul><h3>I. Data Infrastructure Setup</h3><ol><li>Create a MotherDuck account here: <a href="https://motherduck.com/docs/getting-started/">https://motherduck.com/docs/getting-started/</a></li></ol><p>2. Go to Settings &gt; General. Create acces token.</p><p>3. Add the access token on .env</p><pre>MOTHERDUCK_TOKEN=samplemotherduckaccesstoken</pre><p>4. Follow steps 1 to 9 and 11 from this article, <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack</a>, skipping the Snowflake step.</p><h3>II. Data Generation</h3><h3>1. Historic Data Generation</h3><p>Steps:</p><ol><li>Create the following folders and files following the directory tree:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*mjAL2vQBaOM_S31H2-EyJQ.png" /></figure><p>2. Copy and paste the following script for 0_generate_historic_synthetic_data.py. Review the script and modify as needed.</p><pre>import os<br>import pandas as pd<br>import numpy as np<br>from datetime import datetime, timedelta<br>import random<br>from faker import Faker<br>import boto3<br>import psycopg2<br>from io import StringIO<br>import pandas as pd<br>import json<br>from sqlalchemy import create_engine<br>from dotenv import load_dotenv<br>from pathlib import Path<br><br>load_dotenv()<br><br>class EcommerceDataGenerator:<br>    def __init__(self, start_date=datetime(2023, 1, 1), end_date=datetime(2025, 1, 15)):<br>        self.start_date = start_date<br>        self.end_date = end_date<br>        self.fake = Faker()<br>        np.random.seed(42)<br>        random.seed(42)<br>        <br>        self.review_templates = {<br>            &#39;positive&#39;: [<br>                &quot;Great {product_type}! {positive_aspect}. Highly recommend!&quot;,<br>                &quot;Really happy with this purchase. {positive_aspect} and {another_positive}.&quot;,<br>                &quot;Excellent quality {product_type}. {positive_aspect}.&quot;,<br>                &quot;Best {product_type} I&#39;ve bought. {positive_aspect}.&quot;,<br>                &quot;{positive_aspect}. Worth every penny!&quot;<br>            ],<br>            &#39;neutral&#39;: [<br>                &quot;Decent {product_type}. {positive_aspect}, but {negative_aspect}.&quot;,<br>                &quot;Average {product_type}. {neutral_comment}.&quot;,<br>                &quot;Good enough for the price. {neutral_comment}.&quot;,<br>                &quot;{positive_aspect}, however {negative_aspect}.&quot;,<br>                &quot;Not bad, but not great. {neutral_comment}.&quot;<br>            ],<br>            &#39;negative&#39;: [<br>                &quot;Disappointed with this {product_type}. {negative_aspect}.&quot;,<br>                &quot;Not worth the price. {negative_aspect}.&quot;,<br>                &quot;Had issues with {negative_aspect}.&quot;,<br>                &quot;Wouldn&#39;t recommend. {negative_aspect}.&quot;,<br>                &quot;Poor quality {product_type}. {negative_aspect}.&quot;<br>            ]<br>        }<br>        <br>        self.positive_aspects = [<br>            &quot;Excellent build quality&quot;,<br>            &quot;Fast shipping&quot;,<br>            &quot;Great customer service&quot;,<br>            &quot;Perfect fit&quot;,<br>            &quot;Amazing features&quot;,<br>            &quot;Beautiful design&quot;,<br>            &quot;Easy to use&quot;,<br>            &quot;Incredible value&quot;,<br>            &quot;Superior performance&quot;,<br>            &quot;Long battery life&quot;<br>        ]<br>        <br>        self.negative_aspects = [<br>            &quot;Poor build quality&quot;,<br>            &quot;Slow delivery&quot;,<br>            &quot;Unresponsive customer service&quot;,<br>            &quot;Doesn&#39;t fit well&quot;,<br>            &quot;Missing features&quot;,<br>            &quot;Unappealing design&quot;,<br>            &quot;Complicated to use&quot;,<br>            &quot;Overpriced&quot;,<br>            &quot;Underperforms&quot;,<br>            &quot;Short battery life&quot;<br>        ]<br>        <br>        self.neutral_comments = [<br>            &quot;Meets basic expectations&quot;,<br>            &quot;Standard quality&quot;,<br>            &quot;Average performance&quot;,<br>            &quot;Fair for the price&quot;,<br>            &quot;Could be better&quot;<br>        ]<br><br>    def generate_product_categories(self):<br>        &quot;&quot;&quot;Generate product categories and subcategories&quot;&quot;&quot;<br>        categories = {<br>            &#39;Electronics&#39;: [&#39;Smartphones&#39;, &#39;Laptops&#39;, &#39;Accessories&#39;, &#39;Tablets&#39;, &#39;Wearables&#39;],<br>            &#39;Fashion&#39;: [&#39;Men\&#39;s Clothing&#39;, &#39;Women\&#39;s Clothing&#39;, &#39;Children\&#39;s Clothing&#39;, &#39;Shoes&#39;, &#39;Accessories&#39;],<br>            &#39;Home &amp; Living&#39;: [&#39;Furniture&#39;, &#39;Kitchen&#39;, &#39;Decor&#39;, &#39;Bedding&#39;, &#39;Storage&#39;],<br>            &#39;Beauty&#39;: [&#39;Skincare&#39;, &#39;Makeup&#39;, &#39;Haircare&#39;, &#39;Fragrances&#39;, &#39;Tools&#39;],<br>            &#39;Sports&#39;: [&#39;Exercise Equipment&#39;, &#39;Sportswear&#39;, &#39;Outdoor Gear&#39;, &#39;Accessories&#39;, &#39;Footwear&#39;]<br>        }<br>        <br>        category_data = []<br>        subcategory_data = []<br>        <br>        for cat_id, (category, subcategories) in enumerate(categories.items(), 1):<br>            category_data.append({<br>                &#39;category_id&#39;: cat_id,<br>                &#39;category_name&#39;: category,<br>                &#39;created_at&#39;: self.start_date<br>            })<br>            <br>            for sub_id, subcategory in enumerate(subcategories, 1):<br>                subcategory_data.append({<br>                    &#39;subcategory_id&#39;: (cat_id * 100) + sub_id,<br>                    &#39;category_id&#39;: cat_id,<br>                    &#39;subcategory_name&#39;: subcategory,<br>                    &#39;created_at&#39;: self.start_date<br>                })<br>        <br>        return pd.DataFrame(category_data), pd.DataFrame(subcategory_data)<br><br>    def generate_products(self, n_products=1000):<br>        &quot;&quot;&quot;Generate product catalog&quot;&quot;&quot;<br>        categories_df, subcategories_df = self.generate_product_categories()<br>        <br>        products = []<br>        for product_id in range(1, n_products + 1):<br>            category_id = random.randint(1, len(categories_df))<br>            valid_subcats = subcategories_df[subcategories_df[&#39;category_id&#39;] == category_id]<br>            subcategory_id = random.choice(valid_subcats[&#39;subcategory_id&#39;].values)<br>            <br>            base_price = random.uniform(10, 1000)<br>            <br>            products.append({<br>                &#39;product_id&#39;: product_id,<br>                &#39;category_id&#39;: category_id,<br>                &#39;subcategory_id&#39;: subcategory_id,<br>                &#39;product_name&#39;: f&quot;{self.fake.company()} {self.fake.word().title()}&quot;,<br>                &#39;description&#39;: self.fake.text(max_nb_chars=200),<br>                &#39;base_price&#39;: round(base_price, 2),<br>                &#39;sale_price&#39;: round(base_price * random.uniform(0.8, 1.0), 2),<br>                &#39;stock_quantity&#39;: random.randint(0, 1000),<br>                &#39;weight_kg&#39;: round(random.uniform(0.1, 20.0), 2),<br>                &#39;is_active&#39;: random.random() &gt; 0.1,<br>                &#39;created_at&#39;: self.start_date + timedelta(days=random.randint(0, 30)),<br>                &#39;brand&#39;: self.fake.company(),<br>                &#39;sku&#39;: f&quot;SKU-{random.randint(10000, 99999)}&quot;,<br>                &#39;rating&#39;: round(random.uniform(3.0, 5.0), 1),<br>                &#39;review_count&#39;: random.randint(0, 1000)<br>            })<br>        <br>        return pd.DataFrame(products), categories_df, subcategories_df<br><br>    def generate_customers(self, n_customers=1000):<br>        &quot;&quot;&quot;Generate customer data&quot;&quot;&quot;<br>        customers = []<br>        for customer_id in range(1, n_customers + 1):<br>            age = np.random.normal(45, 15)<br>            age = max(18, min(90, int(age)))<br>            signup_date = self.start_date + timedelta(days=random.randint(0, (self.end_date - self.start_date).days))<br>            <br>            customers.append({<br>                &#39;customer_id&#39;: customer_id,<br>                &#39;email&#39;: self.fake.email(),<br>                &#39;first_name&#39;: self.fake.first_name(),<br>                &#39;last_name&#39;: self.fake.last_name(),<br>                &#39;age&#39;: age,<br>                &#39;gender&#39;: random.choice([&#39;M&#39;, &#39;F&#39;, &#39;Other&#39;]),<br>                &#39;annual_income&#39;: max(15000, int(np.random.normal(65000, 30000))),<br>                &#39;marital_status&#39;: random.choice([&#39;Single&#39;, &#39;Married&#39;, &#39;Divorced&#39;, &#39;Widowed&#39;]),<br>                &#39;education&#39;: random.choice([&#39;High School&#39;, &#39;Some College&#39;, &#39;Bachelor&#39;, &#39;Master&#39;, &#39;PhD&#39;]),<br>                &#39;location_type&#39;: random.choice([&#39;Urban&#39;, &#39;Suburban&#39;, &#39;Rural&#39;]),<br>                &#39;city&#39;: self.fake.city(),<br>                &#39;state&#39;: self.fake.state(),<br>                &#39;country&#39;: &#39;USA&#39;,<br>                &#39;signup_date&#39;: signup_date,<br>                &#39;last_login&#39;: signup_date + timedelta(days=random.randint(0, 30)),<br>                &#39;preferred_channel&#39;: random.choice([&#39;Web&#39;, &#39;Mobile App&#39;, &#39;Email&#39;]),<br>                &#39;is_active&#39;: random.random() &gt; 0.1<br>            })<br>        <br>        return pd.DataFrame(customers)<br><br>    def generate_orders(self, customers_df, products_df):<br>        &quot;&quot;&quot;Generate order data&quot;&quot;&quot;<br>        orders = []<br>        order_items = []<br>        order_id = 1<br>        <br>        for _, customer in customers_df.iterrows():<br>            # Number of orders influenced by customer demographics<br>            income_factor = min(2.0, max(0.5, customer[&#39;annual_income&#39;] / 65000))<br>            num_orders = np.random.poisson(5 * income_factor)<br>            <br>            for _ in range(num_orders):<br>                # Ensure order_date is within the date range<br>                max_days = (self.end_date - customer[&#39;signup_date&#39;]).days<br>                if max_days &lt;= 0:<br>                    order_date = customer[&#39;signup_date&#39;]<br>                else:<br>                    order_date = customer[&#39;signup_date&#39;] + timedelta(days=random.randint(0, max_days))<br>                <br>                # Order status flow<br>                if order_date + timedelta(days=7) &gt; self.end_date:<br>                    status = random.choice([&#39;Pending&#39;, &#39;Processing&#39;, &#39;Shipped&#39;])<br>                else:<br>                    status = &#39;Delivered&#39;<br>                <br>                shipping_cost = round(random.uniform(5, 20), 2)<br>                <br>                # Generate order items<br>                num_items = np.random.poisson(2) + 1<br>                order_products = products_df.sample(n=min(num_items, len(products_df)), replace=True)<br>                <br>                total_amount = shipping_cost<br>                for _, product in order_products.iterrows():<br>                    quantity = random.randint(1, 3)<br>                    price = product[&#39;sale_price&#39;]<br>                    item_total = quantity * price<br>                    total_amount += item_total<br>                    <br>                    order_items.append({<br>                        &#39;order_item_id&#39;: len(order_items) + 1,<br>                        &#39;order_id&#39;: order_id,<br>                        &#39;product_id&#39;: product[&#39;product_id&#39;],<br>                        &#39;quantity&#39;: quantity,<br>                        &#39;unit_price&#39;: price,<br>                        &#39;total_price&#39;: item_total,<br>                        &#39;created_at&#39;: order_date<br>                    })<br>                <br>                orders.append({<br>                    &#39;order_id&#39;: order_id,<br>                    &#39;customer_id&#39;: customer[&#39;customer_id&#39;],<br>                    &#39;order_date&#39;: order_date,<br>                    &#39;status&#39;: status,<br>                    &#39;total_amount&#39;: round(total_amount, 2),<br>                    &#39;shipping_cost&#39;: shipping_cost,<br>                    &#39;payment_method&#39;: random.choice([&#39;Credit Card&#39;, &#39;PayPal&#39;, &#39;Debit Card&#39;]),<br>                    &#39;shipping_address&#39;: self.fake.street_address(),<br>                    &#39;billing_address&#39;: self.fake.street_address(),<br>                    &#39;created_at&#39;: order_date,<br>                    &#39;updated_at&#39;: order_date + timedelta(days=random.randint(0, 5))<br>                })<br>                <br>                order_id += 1<br>        <br>        return pd.DataFrame(orders), pd.DataFrame(order_items)<br><br>    def generate_customer_interactions(self, customers_df, products_df):<br>        &quot;&quot;&quot;Generate customer interaction events&quot;&quot;&quot;<br>        events = []<br>        <br>        for _, customer in customers_df.iterrows():<br>            num_interactions = np.random.poisson(20)<br>            <br>            for _ in range(num_interactions):<br>                # Ensure event_date is within the date range<br>                max_days = (self.end_date - customer[&#39;signup_date&#39;]).days<br>                if max_days &lt;= 0:<br>                    event_date = customer[&#39;signup_date&#39;]<br>                else:<br>                    event_date = customer[&#39;signup_date&#39;] + timedelta(days=random.randint(0, max_days))<br>                <br>                product = products_df.sample(n=1).iloc[0]<br>                <br>                event_type = random.choice([&#39;view&#39;, &#39;cart_add&#39;, &#39;cart_remove&#39;, &#39;wishlist_add&#39;, &#39;search&#39;, &#39;purchase&#39;])<br><br>                events.append({<br>                    &#39;event_id&#39;: len(events) + 1,<br>                    &#39;customer_id&#39;: customer[&#39;customer_id&#39;],<br>                    &#39;product_id&#39;: product[&#39;product_id&#39;],<br>                    &#39;event_type&#39;: event_type,<br>                    &#39;event_date&#39;: event_date,<br>                    &#39;device_type&#39;: random.choice([&#39;desktop&#39;, &#39;mobile&#39;, &#39;tablet&#39;]),<br>                    &#39;session_id&#39;: f&quot;session_{random.randint(10000, 99999)}&quot;,<br>                    &#39;created_at&#39;: event_date<br>                })<br>        <br>        return pd.DataFrame(events)<br><br>    def generate_review_text(self, rating, product_type):<br>        &quot;&quot;&quot;Generate realistic review text based on rating&quot;&quot;&quot;<br>        if rating &gt;= 4:<br>            template = random.choice(self.review_templates[&#39;positive&#39;])<br>            aspect = random.choice(self.positive_aspects)<br>            another = random.choice(self.positive_aspects)<br>            return template.format(<br>                product_type=product_type,<br>                positive_aspect=aspect,<br>                another_positive=another<br>            )<br>        elif rating &gt;= 3:<br>            template = random.choice(self.review_templates[&#39;neutral&#39;])<br>            return template.format(<br>                product_type=product_type,<br>                positive_aspect=random.choice(self.positive_aspects),<br>                negative_aspect=random.choice(self.negative_aspects),<br>                neutral_comment=random.choice(self.neutral_comments)<br>            )<br>        else:<br>            template = random.choice(self.review_templates[&#39;negative&#39;])<br>            return template.format(<br>                product_type=product_type,<br>                negative_aspect=random.choice(self.negative_aspects)<br>            )<br><br>    def generate_reviews(self, orders_df, order_items_df, products_df, customers_df):<br>        &quot;&quot;&quot;<br>        Generate synthetic reviews for products based on order and customer data.<br>        <br>        Parameters:<br>            orders_df (DataFrame): DataFrame containing order details.<br>            order_items_df (DataFrame): DataFrame containing order items.<br>            products_df (DataFrame): DataFrame containing product details.<br>            customers_df (DataFrame): DataFrame containing customer details.<br><br>        Returns:<br>            reviews_df (DataFrame): DataFrame containing generated reviews.<br>            updated_products_df (DataFrame): DataFrame with updated product review counts.<br>        &quot;&quot;&quot;<br>        # Ensure &#39;review_count&#39; exists in products_df<br>        if &#39;review_count&#39; not in products_df.columns:<br>            products_df[&#39;review_count&#39;] = 0<br>            print(&quot;Added &#39;review_count&#39; column to products_df with default value 0.&quot;)<br><br>        # Ensure &#39;review_count&#39; column is properly filled and cast to int<br>        products_df[&#39;review_count&#39;] = products_df[&#39;review_count&#39;].fillna(0).astype(int)<br><br>        # Logic to generate synthetic reviews<br>        reviews_data = []<br>        for _, row in orders_df.iterrows():<br>            order_id = row[&#39;order_id&#39;]<br>            customer_id = row[&#39;customer_id&#39;]<br>            # Get items for this order<br>            order_items = order_items_df[order_items_df[&#39;order_id&#39;] == order_id]<br><br>            for _, item in order_items.iterrows():<br>                product_id = item[&#39;product_id&#39;]<br>                # Create synthetic review (e.g., random score and text)<br>                review_score = np.random.randint(1, 6)  # Random score between 1 and 5<br>                review_text = f&quot;Review for product {product_id}&quot;  # Placeholder text<br><br>                reviews_data.append({<br>                    &#39;product_id&#39;: product_id,<br>                    &#39;order_id&#39;: order_id,<br>                    &#39;customer_id&#39;: customer_id,<br>                    &#39;review_score&#39;: review_score,<br>                    &#39;review_text&#39;: review_text<br>                })<br><br>                # Increment review count for the product<br>                products_df.loc[products_df[&#39;product_id&#39;] == product_id, &#39;review_count&#39;] += 1<br><br>        # Create DataFrame for reviews<br>        reviews_df = pd.DataFrame(reviews_data)<br><br>        # Return reviews and updated products DataFrame<br>        return reviews_df, products_df<br><br>    def format_datetime(self, dt):<br>        &quot;&quot;&quot;Format datetime objects for JSON serialization&quot;&quot;&quot;<br>        return dt.isoformat() if isinstance(dt, datetime) else dt<br><br>    def df_to_json_records(self, df):<br>        &quot;&quot;&quot;Convert DataFrame to JSON-serializable records with datetime handling&quot;&quot;&quot;<br>        return json.loads(df.to_json(orient=&#39;records&#39;, date_format=&#39;iso&#39;))<br><br>    def generate_all_data(self, n_customers=1000, n_products=1000):<br>        &quot;&quot;&quot;Generate all e-commerce data with specified output formats&quot;&quot;&quot;<br>        # Define output format for each table<br>        output_formats = {<br>            &#39;customers&#39;: &#39;json&#39;,  # Complex nested data, good for JSON<br>            &#39;products&#39;: &#39;json&#39;,   # Product details often needed in API format<br>            &#39;orders&#39;: &#39;json&#39;,     # Order details benefit from JSON structure<br>            &#39;reviews&#39;: &#39;json&#39;,    # Review text better handled in JSON<br>            &#39;categories&#39;: &#39;csv&#39;,  # Simple structural data good for CSV<br>            &#39;subcategories&#39;: &#39;csv&#39;,<br>            &#39;order_items&#39;: &#39;csv&#39;, # Transactional data good for CSV<br>            &#39;interactions&#39;: &#39;csv&#39; # High-volume data better in CSV<br>        }<br>        <br>        print(&quot;Generating products...&quot;)<br>        products_df, categories_df, subcategories_df = self.generate_products(n_products)<br>        <br>        print(&quot;Generating customers...&quot;)<br>        customers_df = self.generate_customers(n_customers)<br>        <br>        print(&quot;Generating orders...&quot;)<br>        orders_df, order_items_df = self.generate_orders(customers_df, products_df)<br>        <br>        print(&quot;Generating reviews...&quot;)<br>        reviews_df, updated_products_df = self.generate_reviews(orders_df, order_items_df, products_df, customers_df)<br>        <br>        print(&quot;Generating customer interactions...&quot;)<br>        interactions_df = self.generate_customer_interactions(customers_df, updated_products_df)<br>        <br>        # Prepare data dictionary<br>        data_dict = {<br>            &#39;customers&#39;: customers_df,<br>            &#39;products&#39;: updated_products_df,<br>            &#39;categories&#39;: categories_df,<br>            &#39;subcategories&#39;: subcategories_df,<br>            &#39;orders&#39;: orders_df,<br>            &#39;order_items&#39;: order_items_df,<br>            &#39;reviews&#39;: reviews_df,<br>            &#39;interactions&#39;: interactions_df<br>        }<br>        <br>        # # Save data in appropriate formats<br>        # print(&quot;Saving data in specified formats...&quot;)<br>        # self.save_data(data_dict, output_formats)<br>        <br>        return data_dict<br>    <br>class EcommerceDataLoader:<br>    def __init__(self, aws_access_key_id, aws_secret_access_key, bucket_name, <br>                 pg_host, pg_port, pg_user, <br>                 pg_password, pg_database):<br>        &quot;&quot;&quot;Initialize connections to S3 and PostgreSQL&quot;&quot;&quot;<br>        # Validate required parameters<br>        if not all([aws_access_key_id, aws_secret_access_key, bucket_name]):<br>            raise ValueError(&quot;AWS credentials and bucket name are required&quot;)<br><br>        # S3 client setup<br>        self.s3_client = boto3.client(<br>            &#39;s3&#39;,<br>            aws_access_key_id=aws_access_key_id,<br>            aws_secret_access_key=aws_secret_access_key<br>        )<br>        self.bucket_name = bucket_name<br><br>        # PostgreSQL connection setup<br>        self.pg_conn_string = f&quot;postgresql://{pg_user}:{pg_password}@{pg_host}:{pg_port}/{pg_database}&quot;<br>        self.engine = create_engine(self.pg_conn_string)<br><br>    def upload_json_to_s3(self, data_df, table_name):<br>        &quot;&quot;&quot;Upload JSON data directly to S3&quot;&quot;&quot;<br>        if not isinstance(data_df, pd.DataFrame):<br>            raise ValueError(&quot;data_df must be a pandas DataFrame&quot;)<br><br>        try:<br>            # Convert DataFrame to JSON format with metadata<br>            json_data = {<br>                &quot;metadata&quot;: {<br>                    &quot;table&quot;: table_name,<br>                    &quot;recordCount&quot;: len(data_df),<br>                    &quot;generatedAt&quot;: pd.Timestamp.now().isoformat(),<br>                    &quot;version&quot;: &quot;1.0&quot;<br>                },<br>                &quot;data&quot;: json.loads(data_df.to_json(orient=&#39;records&#39;, date_format=&#39;iso&#39;))<br>            }<br>            <br>            # Convert to JSON string<br>            json_str = json.dumps(json_data)<br>            <br>            # Upload to S3<br>            s3_key = f&#39;json/{table_name}.json&#39;<br>            self.s3_client.put_object(<br>                Bucket=self.bucket_name,<br>                Key=s3_key,<br>                Body=json_str,<br>                ContentType=&#39;application/json&#39;<br>            )<br>            print(f&quot;Successfully uploaded {table_name} to S3: s3://{self.bucket_name}/{s3_key}&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error uploading {table_name} to S3: {str(e)}&quot;)<br>            raise<br><br>    def load_csv_to_postgres(self, df, table_name):<br>        &quot;&quot;&quot;Load DataFrame directly to PostgreSQL&quot;&quot;&quot;<br>        if not isinstance(df, pd.DataFrame):<br>            raise ValueError(&quot;df must be a pandas DataFrame&quot;)<br><br>        try:<br>            # Create copy buffer<br>            output = StringIO()<br>            df.to_csv(output, index=False, header=True)<br>            output.seek(0)<br>            <br>            # Create database connection<br>            with self.engine.connect() as connection:<br>                # Create table if it doesn&#39;t exist<br>                df.head(0).to_sql(table_name, connection, if_exists=&#39;replace&#39;, index=False)<br>                <br>                # Copy data<br>                raw_conn = connection.connection<br>                with raw_conn.cursor() as cursor:<br>                    cursor.copy_expert(<br>                        f&quot;COPY {table_name} FROM STDIN WITH CSV HEADER&quot;,<br>                        output<br>                    )<br>                raw_conn.commit()<br>                <br>            print(f&quot;Successfully loaded {len(df)} rows to PostgreSQL table: {table_name}&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error loading {table_name} to PostgreSQL: {str(e)}&quot;)<br>            raise<br><br>def save_data(data_dict):<br>    &quot;&quot;&quot;Save data to S3 and PostgreSQL&quot;&quot;&quot;<br>    # Get AWS credentials from environment variables<br>    aws_access_key_id = os.environ.get(&quot;AWS_S3_ACCESS_KEY_ID&quot;)<br>    aws_secret_access_key = os.environ.get(&quot;AWS_S3_SECRET_ACCESS_KEY&quot;)<br>    bucket_name = os.environ.get(&quot;AWS_S3_HISTORIC_SYNTH&quot;)<br><br>    # Validate AWS credentials<br>    if not all([aws_access_key_id, aws_secret_access_key, bucket_name]):<br>        raise ValueError(&quot;Required AWS environment variables are not set&quot;)<br><br>    # PostgreSQL connection details<br>    pg_config = {<br>        &#39;pg_host&#39;: os.environ.get(&quot;POSTGRES_HOST&quot;),<br>        &#39;pg_port&#39;: int(os.environ.get(&quot;POSTGRES_PORT&quot;)),<br>        &#39;pg_user&#39;: os.environ.get(&quot;POSTGRES_USER&quot;),<br>        &#39;pg_password&#39;: os.environ.get(&quot;POSTGRES_PASSWORD&quot;),<br>        &#39;pg_database&#39;: os.environ.get(&quot;POSTGRES_DB&quot;)<br>    }<br>    # Initialize loader<br>    loader = EcommerceDataLoader(<br>        aws_access_key_id=aws_access_key_id,<br>        aws_secret_access_key=aws_secret_access_key,<br>        bucket_name=bucket_name,<br>        **pg_config<br>    )<br><br>    # Define which tables go to which destination<br>    json_tables = [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;]<br>    csv_tables = [&#39;categories&#39;, &#39;subcategories&#39;, &#39;order_items&#39;, &#39;interactions&#39;]<br><br>    # Validate data_dict<br>    if not isinstance(data_dict, dict):<br>        raise ValueError(&quot;data_dict must be a dictionary containing DataFrames&quot;)<br><br>    # Upload JSON files to S3<br>    for table_name in json_tables:<br>        if table_name in data_dict:<br>            loader.upload_json_to_s3(data_dict[table_name], table_name)<br><br>    # Load CSV files to PostgreSQL<br>    for table_name in csv_tables:<br>        if table_name in data_dict:<br>            loader.load_csv_to_postgres(data_dict[table_name], table_name)<br><br>    output_dir = Path(&#39;generated_historic_data&#39;)<br>    output_dir.mkdir(parents=True, exist_ok=True)<br>    <br>    for table_name, df in data_dict.items():<br>        csv_path = output_dir / f&quot;{table_name}.csv&quot;<br>        df.to_csv(csv_path, index=False)<br>        print(f&quot;Saved {table_name} to {csv_path}&quot;)<br>        <br>    output_dir.mkdir(parents=True, exist_ok=True)<br>    for table_name, df in data_dict.items():<br>        csv_path = os.path.join(output_dir, f&quot;{table_name}.csv&quot;)<br>        df.to_csv(csv_path, index=False)<br>        print(f&quot;Saved {table_name} to {csv_path}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        generator = EcommerceDataGenerator()<br>        data = generator.generate_all_data()<br>        <br>        # Save data directly to S3 and PostgreSQL<br>        save_data(data)        <br>        # Print sample data and format information<br>        print(&quot;\nData Generation Summary:&quot;)<br>        for table_name, df in data.items():<br>            print(f&quot;\n{table_name.upper()} Table:&quot;)<br>            print(f&quot;Total records: {len(df)}&quot;)<br>            print(f&quot;Output format: {&#39;JSON&#39; if table_name in [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;] else &#39;CSV&#39;}&quot;)<br>            print(&quot;\nSample data:&quot;)<br>            print(df.head())<br>            <br>    except Exception as e:<br>        print(f&quot;Error in main execution: {str(e)}&quot;)<br>        raise</pre><p>3. Under the root directory, run:</p><pre>python src/pipeline/0_generate_historic_synthetic_data.py</pre><p>Note: Ensure Docker containers are running</p><p>4. Initially check the generated_historic_data folder for the csv versions of the data. Review the data generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDFufLfPKSnJdntJamgNWA.png" /></figure><p>5. Check section II.2 of this <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">article</a> for the S3 and Postgres data checking.</p><h3>2. Latest Data Generation</h3><p>Steps:</p><ol><li>Copy and paste the following script for generate_latest_synthetic_data.py. Review the script and modify as needed.</li></ol><pre>import os<br>import pandas as pd<br>import numpy as np<br>from datetime import datetime, timedelta<br>import random<br>from faker import Faker<br>import boto3<br>import psycopg2<br>from io import StringIO<br>import pandas as pd<br>import json<br>from sqlalchemy import create_engine<br>from dotenv import load_dotenv<br>from pathlib import Path<br><br>load_dotenv()<br><br>class RecentEcommerceDataGenerator:<br>    def __init__(self, id_offset=1000000):  # Add a large offset to some IDs<br>        # Set end date to today and start date to 30 days ago<br>        self.end_date = datetime.now()<br>        self.start_date = self.end_date - timedelta(days=30)<br>        self.fake = Faker()<br>        self.id_offset = id_offset  # Store the offset<br>        np.random.seed(42)<br>        random.seed(42)<br>        <br>        # Keep existing templates and aspects from the original code<br>        self.review_templates = {<br>            &#39;positive&#39;: [<br>                &quot;Great {product_type}! {positive_aspect}. Highly recommend!&quot;,<br>                &quot;Really happy with this purchase. {positive_aspect} and {another_positive}.&quot;,<br>                &quot;Excellent quality {product_type}. {positive_aspect}.&quot;,<br>                &quot;Best {product_type} I&#39;ve bought. {positive_aspect}.&quot;,<br>                &quot;{positive_aspect}. Worth every penny!&quot;<br>            ],<br>            &#39;neutral&#39;: [<br>                &quot;Decent {product_type}. {positive_aspect}, but {negative_aspect}.&quot;,<br>                &quot;Average {product_type}. {neutral_comment}.&quot;,<br>                &quot;Good enough for the price. {neutral_comment}.&quot;,<br>                &quot;{positive_aspect}, however {negative_aspect}.&quot;,<br>                &quot;Not bad, but not great. {neutral_comment}.&quot;<br>            ],<br>            &#39;negative&#39;: [<br>                &quot;Disappointed with this {product_type}. {negative_aspect}.&quot;,<br>                &quot;Not worth the price. {negative_aspect}.&quot;,<br>                &quot;Had issues with {negative_aspect}.&quot;,<br>                &quot;Wouldn&#39;t recommend. {negative_aspect}.&quot;,<br>                &quot;Poor quality {product_type}. {negative_aspect}.&quot;<br>            ]<br>        }<br>    <br>        self.positive_aspects = [<br>            &quot;Excellent build quality&quot;,<br>            &quot;Fast shipping&quot;,<br>            &quot;Great customer service&quot;,<br>            &quot;Perfect fit&quot;,<br>            &quot;Amazing features&quot;,<br>            &quot;Beautiful design&quot;,<br>            &quot;Easy to use&quot;,<br>            &quot;Incredible value&quot;,<br>            &quot;Superior performance&quot;,<br>            &quot;Long battery life&quot;<br>        ]<br>        <br>        self.negative_aspects = [<br>            &quot;Poor build quality&quot;,<br>            &quot;Slow delivery&quot;,<br>            &quot;Unresponsive customer service&quot;,<br>            &quot;Doesn&#39;t fit well&quot;,<br>            &quot;Missing features&quot;,<br>            &quot;Unappealing design&quot;,<br>            &quot;Complicated to use&quot;,<br>            &quot;Overpriced&quot;,<br>            &quot;Underperforms&quot;,<br>            &quot;Short battery life&quot;<br>        ]<br>        <br>        self.neutral_comments = [<br>            &quot;Meets basic expectations&quot;,<br>            &quot;Standard quality&quot;,<br>            &quot;Average performance&quot;,<br>            &quot;Fair for the price&quot;,<br>            &quot;Could be better&quot;<br>        ]<br><br>    def generate_product_categories(self):<br>        &quot;&quot;&quot;Generate product categories and subcategories&quot;&quot;&quot;<br>        categories = {<br>            &#39;Electronics&#39;: [&#39;Smartphones&#39;, &#39;Laptops&#39;, &#39;Accessories&#39;, &#39;Tablets&#39;, &#39;Wearables&#39;],<br>            &#39;Fashion&#39;: [&#39;Men\&#39;s Clothing&#39;, &#39;Women\&#39;s Clothing&#39;, &#39;Children\&#39;s Clothing&#39;, &#39;Shoes&#39;, &#39;Accessories&#39;],<br>            &#39;Home &amp; Living&#39;: [&#39;Furniture&#39;, &#39;Kitchen&#39;, &#39;Decor&#39;, &#39;Bedding&#39;, &#39;Storage&#39;],<br>            &#39;Beauty&#39;: [&#39;Skincare&#39;, &#39;Makeup&#39;, &#39;Haircare&#39;, &#39;Fragrances&#39;, &#39;Tools&#39;],<br>            &#39;Sports&#39;: [&#39;Exercise Equipment&#39;, &#39;Sportswear&#39;, &#39;Outdoor Gear&#39;, &#39;Accessories&#39;, &#39;Footwear&#39;]<br>        }<br>        <br>        category_data = []<br>        subcategory_data = []<br>        <br>        for cat_id, (category, subcategories) in enumerate(categories.items(), 1):<br>            category_data.append({<br>                &#39;category_id&#39;: cat_id,<br>                &#39;category_name&#39;: category,<br>                &#39;created_at&#39;: self.start_date<br>            })<br>            <br>            for sub_id, subcategory in enumerate(subcategories, 1):<br>                subcategory_data.append({<br>                    &#39;subcategory_id&#39;: (cat_id * 100) + sub_id,<br>                    &#39;category_id&#39;: cat_id,<br>                    &#39;subcategory_name&#39;: subcategory,<br>                    &#39;created_at&#39;: self.start_date<br>                })<br>        <br>        return pd.DataFrame(category_data), pd.DataFrame(subcategory_data)<br><br>    def generate_random_date(self):<br>        &quot;&quot;&quot;Generate a random date within the last 30 days&quot;&quot;&quot;<br>        days_offset = random.randint(0, 30)<br>        return self.end_date - timedelta(days=days_offset)<br><br>    def generate_products(self, n_products=1000):<br>        &quot;&quot;&quot;Generate product catalog with recent dates&quot;&quot;&quot;<br>        categories_df, subcategories_df = self.generate_product_categories()<br>        <br>        products = []<br>        for product_id in range(1, n_products + 1):<br>            category_id = random.randint(1, len(categories_df))<br>            valid_subcats = subcategories_df[subcategories_df[&#39;category_id&#39;] == category_id]<br>            subcategory_id = random.choice(valid_subcats[&#39;subcategory_id&#39;].values)<br>            <br>            base_price = random.uniform(10, 1000)<br>            <br>            # Use recent date for created_at<br>            created_at = self.generate_random_date()<br>            <br>            products.append({<br>                &#39;product_id&#39;: product_id,<br>                &#39;category_id&#39;: category_id,<br>                &#39;subcategory_id&#39;: subcategory_id,<br>                &#39;product_name&#39;: f&quot;{self.fake.company()} {self.fake.word().title()}&quot;,<br>                &#39;description&#39;: self.fake.text(max_nb_chars=200),<br>                &#39;base_price&#39;: round(base_price, 2),<br>                &#39;sale_price&#39;: round(base_price * random.uniform(0.8, 1.0), 2),<br>                &#39;stock_quantity&#39;: random.randint(0, 1000),<br>                &#39;weight_kg&#39;: round(random.uniform(0.1, 20.0), 2),<br>                &#39;is_active&#39;: random.random() &gt; 0.1,<br>                &#39;created_at&#39;: created_at,<br>                &#39;brand&#39;: self.fake.company(),<br>                &#39;sku&#39;: f&quot;SKU-{random.randint(10000, 99999)}&quot;,<br>                &#39;rating&#39;: round(random.uniform(3.0, 5.0), 1),<br>                &#39;review_count&#39;: random.randint(0, 100)<br>            })<br>        <br>        return pd.DataFrame(products), categories_df, subcategories_df<br><br>    def generate_customers(self, n_customers=1000, historic_customers_file=&#39;de-ecommerce/data/customers.csv&#39;):<br>        &quot;&quot;&quot;<br>        Generate customer data with a mix of returning and new customers<br>        <br>        Parameters:<br>            n_customers: Number of total customers to generate<br>            historic_customers_file: Path to historic customers CSV file<br>            <br>        Returns:<br>            DataFrame with customer data<br>        &quot;&quot;&quot;<br>        # Try to load historic customers<br>        try:<br>            historic_df = pd.read_csv(historic_customers_file)<br>            print(f&quot;Loaded {len(historic_df)} historic customers&quot;)<br>            <br>            # Calculate number of returning customers (30% of historic customers)<br>            n_returning = min(int(len(historic_df) * 0.3), n_customers)<br>            n_new = n_customers - n_returning<br>            <br>            print(f&quot;Generating {n_returning} returning customers and {n_new} new customers&quot;)<br>            <br>            # Select random returning customers<br>            returning_customers = historic_df.sample(n=n_returning).copy()<br>            <br>            # Update their activity for the recent period<br>            for idx in returning_customers.index:<br>                # Generate new login date within the last 30 days<br>                last_login = self.generate_random_date()<br>                returning_customers.loc[idx, &#39;last_login&#39;] = last_login<br>                <br>                # Maybe update some other fields that might change<br>                returning_customers.loc[idx, &#39;annual_income&#39;] = max(15000, int(np.random.normal(65000, 30000)))<br>                returning_customers.loc[idx, &#39;marital_status&#39;] = random.choice([&#39;Single&#39;, &#39;Married&#39;, &#39;Divorced&#39;, &#39;Widowed&#39;])<br>                returning_customers.loc[idx, &#39;location_type&#39;] = random.choice([&#39;Urban&#39;, &#39;Suburban&#39;, &#39;Rural&#39;])<br>                returning_customers.loc[idx, &#39;preferred_channel&#39;] = random.choice([&#39;Web&#39;, &#39;Mobile App&#39;, &#39;Email&#39;])<br>                returning_customers.loc[idx, &#39;is_active&#39;] = True  # They&#39;re active since they&#39;re returning<br>            <br>        except FileNotFoundError:<br>            print(&quot;Historic customers file not found. Generating all new customers.&quot;)<br>            n_returning = 0<br>            n_new = n_customers<br>            returning_customers = pd.DataFrame()<br>        <br>        # Generate new customers<br>        new_customers = []<br>        start_id = self.id_offset if not len(returning_customers) else max(returning_customers[&#39;customer_id&#39;]) + 1<br>        <br>        for customer_id in range(start_id, start_id + n_new):<br>            signup_date = self.generate_random_date()<br>            last_login = min(signup_date + timedelta(days=random.randint(0, 5)), self.end_date)<br>            <br>            new_customers.append({<br>                &#39;customer_id&#39;: customer_id,<br>                &#39;email&#39;: self.fake.email(),<br>                &#39;first_name&#39;: self.fake.first_name(),<br>                &#39;last_name&#39;: self.fake.last_name(),<br>                &#39;age&#39;: max(18, min(90, int(np.random.normal(45, 15)))),<br>                &#39;gender&#39;: random.choice([&#39;M&#39;, &#39;F&#39;, &#39;Other&#39;]),<br>                &#39;annual_income&#39;: max(15000, int(np.random.normal(65000, 30000))),<br>                &#39;marital_status&#39;: random.choice([&#39;Single&#39;, &#39;Married&#39;, &#39;Divorced&#39;, &#39;Widowed&#39;]),<br>                &#39;education&#39;: random.choice([&#39;High School&#39;, &#39;Some College&#39;, &#39;Bachelor&#39;, &#39;Master&#39;, &#39;PhD&#39;]),<br>                &#39;location_type&#39;: random.choice([&#39;Urban&#39;, &#39;Suburban&#39;, &#39;Rural&#39;]),<br>                &#39;city&#39;: self.fake.city(),<br>                &#39;state&#39;: self.fake.state(),<br>                &#39;country&#39;: &#39;USA&#39;,<br>                &#39;signup_date&#39;: signup_date,<br>                &#39;last_login&#39;: last_login,<br>                &#39;preferred_channel&#39;: random.choice([&#39;Web&#39;, &#39;Mobile App&#39;, &#39;Email&#39;]),<br>                &#39;is_active&#39;: random.random() &gt; 0.1<br>            })<br>        <br>        # Combine returning and new customers<br>        new_customers_df = pd.DataFrame(new_customers)<br>        final_customers_df = pd.concat([returning_customers, new_customers_df], ignore_index=True)<br>        <br>        print(f&quot;Generated total of {len(final_customers_df)} customers&quot;)<br>        print(f&quot;- Returning customers: {len(returning_customers)}&quot;)<br>        print(f&quot;- New customers: {len(new_customers_df)}&quot;)<br>        <br>        return final_customers_df<br><br>    def generate_orders(self, customers_df, products_df):<br>        &quot;&quot;&quot;Generate order data for the last 30 days&quot;&quot;&quot;<br>        orders = []<br>        order_items = []<br>        order_id = 1<br>        <br>        for _, customer in customers_df.iterrows():<br>            # Reduce number of orders for 30-day period<br>            num_orders = np.random.poisson(2)  # Reduced from 5 to 2<br>            <br>            for _ in range(num_orders):<br>                order_id = order_id + self.id_offset<br>                order_date = max(<br>                    customer[&#39;signup_date&#39;],<br>                    self.generate_random_date()<br>                )<br>                <br>                # Order status based on recent dates<br>                days_since_order = (self.end_date - order_date).days<br>                if days_since_order &lt; 2:<br>                    status = &#39;Pending&#39;<br>                elif days_since_order &lt; 4:<br>                    status = &#39;Processing&#39;<br>                elif days_since_order &lt; 7:<br>                    status = &#39;Shipped&#39;<br>                else:<br>                    status = &#39;Delivered&#39;<br>                <br>                # Generate order items<br>                num_items = np.random.poisson(2) + 1<br>                order_products = products_df.sample(n=min(num_items, len(products_df)))<br>                <br>                shipping_cost = round(random.uniform(5, 20), 2)<br>                total_amount = shipping_cost<br>                <br>                for _, product in order_products.iterrows():<br>                    quantity = random.randint(1, 3)<br>                    price = product[&#39;sale_price&#39;]<br>                    item_total = quantity * price<br>                    total_amount += item_total<br>                    <br>                    order_items.append({<br>                        &#39;order_item_id&#39;: len(order_items) + 1,<br>                        &#39;order_id&#39;: order_id,<br>                        &#39;product_id&#39;: product[&#39;product_id&#39;],<br>                        &#39;quantity&#39;: quantity,<br>                        &#39;unit_price&#39;: price,<br>                        &#39;total_price&#39;: item_total,<br>                        &#39;created_at&#39;: order_date<br>                    })<br>                <br>                orders.append({<br>                    &#39;order_id&#39;: order_id,<br>                    &#39;customer_id&#39;: customer[&#39;customer_id&#39;],<br>                    &#39;order_date&#39;: order_date,<br>                    &#39;status&#39;: status,<br>                    &#39;total_amount&#39;: round(total_amount, 2),<br>                    &#39;shipping_cost&#39;: shipping_cost,<br>                    &#39;payment_method&#39;: random.choice([&#39;Credit Card&#39;, &#39;PayPal&#39;, &#39;Debit Card&#39;]),<br>                    &#39;shipping_address&#39;: self.fake.street_address(),<br>                    &#39;billing_address&#39;: self.fake.street_address(),<br>                    &#39;created_at&#39;: order_date,<br>                    &#39;updated_at&#39;: order_date + timedelta(days=random.randint(0, 2))<br>                })<br>                <br>                order_id += 1<br>        <br>        return pd.DataFrame(orders), pd.DataFrame(order_items)<br><br>    def generate_customer_interactions(self, customers_df, products_df):<br>        &quot;&quot;&quot;Generate customer interactions for the last 30 days&quot;&quot;&quot;<br>        events = []<br>        <br>        for _, customer in customers_df.iterrows():<br>            # Reduce number of interactions for 30-day period<br>            num_interactions = np.random.poisson(10)  # Reduced from 20 to 10<br>            <br>            for _ in range(num_interactions):<br>                event_date = max(<br>                    customer[&#39;signup_date&#39;],<br>                    self.generate_random_date()<br>                )<br>                <br>                product = products_df.sample(n=1).iloc[0]<br>                <br>                events.append({<br>                    &#39;event_id&#39;: len(events) + 1 + self.id_offset,<br>                    &#39;customer_id&#39;: customer[&#39;customer_id&#39;],<br>                    &#39;product_id&#39;: product[&#39;product_id&#39;],<br>                    &#39;event_type&#39;: random.choice([&#39;view&#39;, &#39;cart_add&#39;, &#39;cart_remove&#39;, &#39;wishlist_add&#39;, &#39;search&#39;, &#39;purchase&#39;]),<br>                    &#39;event_date&#39;: event_date,<br>                    &#39;device_type&#39;: random.choice([&#39;desktop&#39;, &#39;mobile&#39;, &#39;tablet&#39;]),<br>                    &#39;session_id&#39;: f&quot;session_{random.randint(10000, 99999)}&quot;,<br>                    &#39;created_at&#39;: event_date<br>                })<br>        <br>        return pd.DataFrame(events)<br>    <br>    def generate_review_text(self, rating, product_type):<br>        &quot;&quot;&quot;Generate realistic review text based on rating&quot;&quot;&quot;<br>        if rating &gt;= 4:<br>            template = random.choice(self.review_templates[&#39;positive&#39;])<br>            aspect = random.choice(self.positive_aspects)<br>            another = random.choice(self.positive_aspects)<br>            return template.format(<br>                product_type=product_type,<br>                positive_aspect=aspect,<br>                another_positive=another<br>            )<br>        elif rating &gt;= 3:<br>            template = random.choice(self.review_templates[&#39;neutral&#39;])<br>            return template.format(<br>                product_type=product_type,<br>                positive_aspect=random.choice(self.positive_aspects),<br>                negative_aspect=random.choice(self.negative_aspects),<br>                neutral_comment=random.choice(self.neutral_comments)<br>            )<br>        else:<br>            template = random.choice(self.review_templates[&#39;negative&#39;])<br>            return template.format(<br>                product_type=product_type,<br>                negative_aspect=random.choice(self.negative_aspects)<br>            )<br><br>    def generate_reviews(self, orders_df, order_items_df, products_df, customers_df):<br>        &quot;&quot;&quot;Generate reviews with new IDs&quot;&quot;&quot;<br>        reviews_data = []<br>        review_id = 1<br>        <br>        for _, row in orders_df.iterrows():<br>            order_items = order_items_df[order_items_df[&#39;order_id&#39;] == row[&#39;order_id&#39;]]<br><br>            for _, item in order_items.iterrows():<br>                reviews_data.append({<br>                    &#39;review_id&#39;: review_id + self.id_offset,<br>                    &#39;product_id&#39;: item[&#39;product_id&#39;],<br>                    &#39;order_id&#39;: row[&#39;order_id&#39;],<br>                    &#39;customer_id&#39;: row[&#39;customer_id&#39;],<br>                    &#39;review_score&#39;: np.random.randint(1, 6),<br>                    &#39;review_text&#39;: self.generate_review_text(<br>                        np.random.randint(1, 6),<br>                        products_df[products_df[&#39;product_id&#39;] == item[&#39;product_id&#39;]].iloc[0][&#39;product_name&#39;]<br>                    )<br>                })<br>                review_id += 1<br><br>                # Update product review count<br>                products_df.loc[products_df[&#39;product_id&#39;] == item[&#39;product_id&#39;], &#39;review_count&#39;] += 1<br><br>        return pd.DataFrame(reviews_data), products_df<br><br>    def generate_all_data(self, n_customers=1000, n_products=1000):<br>        &quot;&quot;&quot;Generate all e-commerce data for the last 30 days&quot;&quot;&quot;<br>        output_formats = {<br>            &#39;customers&#39;: &#39;json&#39;,<br>            &#39;products&#39;: &#39;json&#39;,<br>            &#39;orders&#39;: &#39;json&#39;,<br>            &#39;reviews&#39;: &#39;json&#39;,<br>            &#39;categories&#39;: &#39;csv&#39;,<br>            &#39;subcategories&#39;: &#39;csv&#39;,<br>            &#39;order_items&#39;: &#39;csv&#39;,<br>            &#39;interactions&#39;: &#39;csv&#39;<br>        }<br>        <br>        print(f&quot;Generating data for period: {self.start_date.date()} to {self.end_date.date()}&quot;)<br>        <br>        print(&quot;Generating products...&quot;)<br>        products_df, categories_df, subcategories_df = self.generate_products(n_products)<br>        <br>        print(&quot;Generating customers...&quot;)<br>        customers_df = self.generate_customers(n_customers)<br>        <br>        print(&quot;Generating orders...&quot;)<br>        orders_df, order_items_df = self.generate_orders(customers_df, products_df)<br>        <br>        print(&quot;Generating reviews...&quot;)<br>        reviews_df, updated_products_df = self.generate_reviews(orders_df, order_items_df, products_df, customers_df)<br>        <br>        print(&quot;Generating customer interactions...&quot;)<br>        interactions_df = self.generate_customer_interactions(customers_df, updated_products_df)<br>        <br>        data_dict = {<br>            &#39;customers&#39;: customers_df,<br>            &#39;products&#39;: updated_products_df,<br>            &#39;categories&#39;: categories_df,<br>            &#39;subcategories&#39;: subcategories_df,<br>            &#39;orders&#39;: orders_df,<br>            &#39;order_items&#39;: order_items_df,<br>            &#39;reviews&#39;: reviews_df,<br>            &#39;interactions&#39;: interactions_df<br>        }<br>        <br>        # self.save_data(data_dict, output_formats)<br>        <br>        return data_dict<br>    <br>class EcommerceDataLoader:<br>    def __init__(self, aws_access_key_id, aws_secret_access_key, bucket_name, <br>                 pg_host, pg_port, pg_user, <br>                 pg_password, pg_database):<br>        &quot;&quot;&quot;Initialize connections to S3 and PostgreSQL&quot;&quot;&quot;<br>        # S3 client setup<br>        self.s3_client = boto3.client(<br>            &#39;s3&#39;,<br>            aws_access_key_id=aws_access_key_id,<br>            aws_secret_access_key=aws_secret_access_key<br>        )<br>        self.bucket_name = bucket_name<br><br>        # PostgreSQL connection setup<br>        self.pg_conn_string = f&quot;postgresql://{pg_user}:{pg_password}@{pg_host}:{pg_port}/{pg_database}&quot;<br>        self.engine = create_engine(self.pg_conn_string)<br><br>    def upload_json_to_s3(self, data_dict, table_name):<br>        &quot;&quot;&quot;Upload JSON data directly to S3&quot;&quot;&quot;<br>        try:<br>            # Convert DataFrame to JSON format with metadata<br>            json_data = {<br>                &quot;metadata&quot;: {<br>                    &quot;table&quot;: table_name,<br>                    &quot;recordCount&quot;: len(data_dict),<br>                    &quot;generatedAt&quot;: pd.Timestamp.now().isoformat(),<br>                    &quot;version&quot;: &quot;1.0&quot;<br>                },<br>                &quot;data&quot;: json.loads(data_dict.to_json(orient=&#39;records&#39;, date_format=&#39;iso&#39;))<br>            }<br>            <br>            # Convert to JSON string<br>            json_str = json.dumps(json_data)<br>            <br>            # Upload to S3<br>            s3_key = f&#39;json/{table_name}.json&#39;<br>            self.s3_client.put_object(<br>                Bucket=self.bucket_name,<br>                Key=s3_key,<br>                Body=json_str,<br>                ContentType=&#39;application/json&#39;<br>            )<br>            print(f&quot;Uploaded {table_name} to S3: s3://{self.bucket_name}/{s3_key}&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error uploading {table_name} to S3: {str(e)}&quot;)<br>            raise<br><br>    def load_csv_to_postgres(self, df, table_name):<br>        &quot;&quot;&quot;Load DataFrame directly to PostgreSQL&quot;&quot;&quot;<br>        <br>        if not isinstance(df, pd.DataFrame):<br>            raise ValueError(&quot;df must be a pandas DataFrame&quot;)<br>        try:<br>            # Create copy buffer<br>            output = StringIO()<br>            df.to_csv(output, index=False, header=True)<br>            output.seek(0)<br>            <br>            # Create database connection<br>            with self.engine.connect() as connection:<br>                # Create table if it doesn&#39;t exist<br>                df.head(0).to_sql(table_name, connection, if_exists=&#39;replace&#39;, index=False)<br>                <br>                # Copy data<br>                raw_conn = connection.connection<br>                with raw_conn.cursor() as cursor:<br>                    cursor.copy_expert(<br>                        f&quot;COPY {table_name} FROM STDIN WITH CSV HEADER&quot;,<br>                        output<br>                    )<br>                raw_conn.commit()<br>                <br>            print(f&quot;Loaded {len(df)} rows to PostgreSQL table: {table_name}&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error loading {table_name} to PostgreSQL: {str(e)}&quot;)<br>            raise<br><br>def save_data(data_dict):<br>    &quot;&quot;&quot;Save data to S3 and PostgreSQL&quot;&quot;&quot;<br>    # AWS credentials (replace with your own)<br>    aws_access_key_id = os.environ.get(&quot;AWS_S3_ACCESS_KEY_ID&quot;)<br>    aws_secret_access_key = os.environ.get(&quot;AWS_S3_SECRET_ACCESS_KEY&quot;)<br>    bucket_name = os.environ.get(&quot;AWS_S3_LATEST_SYNTH&quot;)<br><br>    # Validate AWS credentials<br>    if not all([aws_access_key_id, aws_secret_access_key, bucket_name]):<br>        raise ValueError(&quot;Required AWS environment variables are not set&quot;)<br><br>    # PostgreSQL connection details<br>    pg_config = {<br>        &#39;pg_host&#39;: os.environ.get(&quot;POSTGRES_HOST&quot;),<br>        &#39;pg_port&#39;: int(os.environ.get(&quot;POSTGRES_PORT&quot;)),<br>        &#39;pg_user&#39;: os.environ.get(&quot;POSTGRES_USER&quot;),<br>        &#39;pg_password&#39;: os.environ.get(&quot;POSTGRES_PASSWORD&quot;),<br>        &#39;pg_database&#39;: os.environ.get(&quot;POSTGRES_DB&quot;)<br>    }<br><br>    # Initialize loader<br>    loader = EcommerceDataLoader(<br>        aws_access_key_id=aws_access_key_id,<br>        aws_secret_access_key=aws_secret_access_key,<br>        bucket_name=bucket_name,<br>        **pg_config<br>    )<br><br>    # Define which tables go to which destination<br>    json_tables = [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;]<br>    csv_tables_mapping = {<br>        &#39;categories&#39;: &#39;latest_categories&#39;,<br>        &#39;subcategories&#39;: &#39;latest_subcategories&#39;,<br>        &#39;order_items&#39;: &#39;latest_order_items&#39;,<br>        &#39;interactions&#39;: &#39;latest_interactions&#39;<br>    }<br>    <br>    # Upload JSON files to S3<br>    for table_name in json_tables:<br>        if table_name in data_dict:<br>            loader.upload_json_to_s3(data_dict[table_name], table_name)<br><br>    # Load CSV files to PostgreSQL with the &#39;latest_&#39; prefix<br>    for original_name, latest_name in csv_tables_mapping.items():<br>        if original_name in data_dict:<br>            print(f&quot;Loading {original_name} to PostgreSQL as {latest_name}&quot;)<br>            loader.load_csv_to_postgres(data_dict[original_name], latest_name)<br>            <br>    output_dir = Path(&#39;generated_latest_data&#39;)<br>    output_dir.mkdir(parents=True, exist_ok=True)<br>    <br>    for table_name, df in data_dict.items():<br>        csv_path = output_dir / f&quot;{table_name}.csv&quot;<br>        df.to_csv(csv_path, index=False)<br>        print(f&quot;Saved {table_name} to {csv_path}&quot;)<br>        <br>    output_dir.mkdir(parents=True, exist_ok=True)<br>    for table_name, df in data_dict.items():<br>        csv_path = os.path.join(output_dir, f&quot;{table_name}.csv&quot;)<br>        df.to_csv(csv_path, index=False)<br>        print(f&quot;Saved {table_name} to {csv_path}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    # Generate data<br>    generator = RecentEcommerceDataGenerator()<br>    data = generator.generate_all_data()<br>    <br>    # Save data directly to S3 and PostgreSQL<br>    save_data(data)<br>    <br>    # Print summary<br>    print(&quot;\nData Generation and Loading Summary:&quot;)<br>    for table_name, df in data.items():<br>        print(f&quot;\n{table_name.upper()} Table:&quot;)<br>        print(f&quot;Total records: {len(df)}&quot;)<br>        <br>        # Different tables have different date columns<br>        date_columns = {<br>            &#39;customers&#39;: &#39;signup_date&#39;,<br>            &#39;products&#39;: &#39;created_at&#39;,<br>            &#39;orders&#39;: &#39;order_date&#39;,<br>            &#39;latest_order_items&#39;: &#39;created_at&#39;,<br>            &#39;reviews&#39;: &#39;created_at&#39;,<br>            &#39;latest_interactions&#39;: &#39;event_date&#39;,<br>            &#39;latest_categories&#39;: &#39;created_at&#39;,<br>            &#39;latest_subcategories&#39;: &#39;created_at&#39;<br>        }<br>        <br>        # Get the appropriate date column for this table<br>        date_col = date_columns.get(table_name)<br>        if date_col and date_col in df.columns:<br>            print(f&quot;Date range: {df[date_col].min()} to {df[date_col].max()}&quot;)<br>        <br>        destination = &#39;S3&#39; if table_name in [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;] else &#39;PostgreSQL&#39;<br>        print(f&quot;Loaded to: {destination}&quot;)</pre><p>2. Run:</p><pre>python src/pipeline/generate/latest_synthetic_data.py</pre><p>3. Initially check the generated_latest_data folder for the csv versions of the data. Review the data generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhWrivzEwzAVWfxgzGQjYA.png" /></figure><p>4. Check section II. 2 of this <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">article</a> for the S3 and Postgres data checking.</p><h3>III. Data Ingestion</h3><h3>1. Initial Append ETL Ingestion</h3><p>Steps:</p><ol><li>Add the following files under src/pipeline:</li></ol><ul><li>ingested_data</li><li>0_ingest_historic_synthetic_data.py</li><li>generate_latest_synthetic_data.py</li></ul><p>2. Copy and paste the following code to 0_ingest_historic_synthetic_data.py:</p><pre>import os<br>import pandas as pd<br>import boto3<br>import json<br>from sqlalchemy import create_engine<br>from dotenv import load_dotenv<br>import psycopg2<br>import tempfile<br>from pandas import json_normalize<br>from datetime import datetime<br>import uuid<br>import io<br>from pathlib import Path<br><br>load_dotenv()<br><br>class InitialHistoricETL:<br>    def __init__(self):<br>        # Initialize connections<br>        self._init_postgres()<br>        self._init_s3()<br>        <br>        # Define source mappings<br>        self.postgres_tables = [&#39;categories&#39;, &#39;subcategories&#39;, &#39;order_items&#39;, &#39;interactions&#39;]<br>        self.s3_tables = [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;]<br>        <br>        # Track batch information<br>        self.batch_id = str(uuid.uuid4())<br>        self.batch_timestamp = datetime.now()<br>    <br>    def _init_postgres(self):<br>        &quot;&quot;&quot;Initialize PostgreSQL connection&quot;&quot;&quot;<br>        self.pg_conn_string = f&quot;postgresql://{os.getenv(&#39;POSTGRES_USER&#39;)}:{os.getenv(&#39;POSTGRES_PASSWORD&#39;)}@{os.getenv(&#39;POSTGRES_HOST&#39;)}:{os.getenv(&#39;POSTGRES_PORT&#39;)}/{os.getenv(&#39;POSTGRES_DB&#39;)}&quot;<br>        self.pg_engine = create_engine(self.pg_conn_string)<br><br>    def _init_s3(self):<br>        &quot;&quot;&quot;Initialize S3 clients&quot;&quot;&quot;<br>        s3_credentials = {<br>            &#39;aws_access_key_id&#39;: os.getenv(&#39;AWS_S3_ACCESS_KEY_ID&#39;),<br>            &#39;aws_secret_access_key&#39;: os.getenv(&#39;AWS_S3_SECRET_ACCESS_KEY&#39;)<br>        }<br>        <br>        self.s3_client = boto3.client(&#39;s3&#39;, **s3_credentials)<br>        self.historic_bucket = os.getenv(&#39;AWS_S3_HISTORIC_SYNTH&#39;)<br>        self.latest_bucket = os.getenv(&#39;AWS_S3_LATEST_SYNTH&#39;)<br><br>    def extract_from_postgres(self, table_name, data_source):<br>        &quot;&quot;&quot;Extract data from PostgreSQL&quot;&quot;&quot;<br>        try:<br>            table_prefix = &#39;latest_&#39; if data_source == &#39;latest&#39; else &#39;&#39;<br>            query = f&quot;SELECT * FROM {table_prefix}{table_name}&quot;<br>            df = pd.read_sql(query, self.pg_engine)<br>            return df<br>        except Exception as e:<br>            print(f&quot;PostgreSQL extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def extract_from_s3(self, table_name, data_source):<br>        &quot;&quot;&quot;Extract data from S3&quot;&quot;&quot;<br>        try:<br>            bucket = self.latest_bucket if data_source == &#39;latest&#39; else self.historic_bucket<br>            response = self.s3_client.get_object(<br>                Bucket=bucket,<br>                Key=f&#39;json/{table_name}.json&#39;<br>            )<br>            <br>            json_content = json.loads(response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;))<br>            return pd.DataFrame(json_content[&#39;data&#39;])<br>        except Exception as e:<br>            print(f&quot;S3 extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br>        <br>    def get_primary_keys(self, table_name):<br>        &quot;&quot;&quot;Return primary key columns for each table&quot;&quot;&quot;<br>        pk_mapping = {<br>            &#39;customers&#39;: [&#39;CUSTOMER_ID&#39;],<br>            &#39;orders&#39;: [&#39;ORDER_ID&#39;],<br>            &#39;products&#39;: [&#39;PRODUCT_ID&#39;],<br>            &#39;order_items&#39;: [&#39;ORDER_ITEM_ID&#39;],<br>            &#39;categories&#39;: [&#39;CATEGORY_ID&#39;],<br>            &#39;subcategories&#39;: [&#39;SUBCATEGORY_ID&#39;],<br>            &#39;reviews&#39;: [&#39;REVIEW_ID&#39;],<br>            &#39;interactions&#39;: [&#39;EVENT_ID&#39;]<br>        }<br>        return pk_mapping.get(table_name.replace(&#39;latest_&#39;, &#39;&#39;), [&#39;id&#39;])<br><br>    def remove_duplicate_primary_keys(self, df, table_name):<br>        &quot;&quot;&quot;Remove rows with duplicate primary keys, defaulting to the first column if necessary.&quot;&quot;&quot;<br>        try:<br>            # Get primary keys for the table<br>            primary_keys = self.get_primary_keys(table_name)<br><br>            if not primary_keys:<br>                print(f&quot;Warning: No primary keys found or defined for {table_name}. Skipping deduplication.&quot;)<br>                return df<br><br>            # Ensure all primary keys exist in the DataFrame<br>            missing_keys = [key for key in primary_keys if key not in df.columns]<br>            if missing_keys:<br>                print(f&quot;Error: Missing primary keys {missing_keys} in table {table_name}.&quot;)<br>                return df<br><br>            # Deduplicate based on primary keys<br>            if &quot;LOADED_AT&quot; in df.columns:<br>                df = df.sort_values(by=&quot;LOADED_AT&quot;, ascending=False)<br>            else:<br>                print(f&quot;Warning: No valid date column found for {table_name}. Proceeding without sorting.&quot;)<br>            df = df.drop_duplicates(subset=primary_keys, keep=&quot;first&quot;)<br>            return df<br>        except Exception as e:<br>            print(f&quot;Error removing duplicate primary keys for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def transform_data(self, df, table_name):<br>        &quot;&quot;&quot;Transform data with added metadata columns&quot;&quot;&quot;<br>        try:<br>            # Flatten JSON if needed<br>            df = self.flatten_json_df(df, table_name)<br>            <br>            # Add metadata columns<br>            df[&#39;DATA_SOURCE&#39;] = &#39;historic&#39;<br>            df[&#39;BATCH_ID&#39;] = self.batch_id<br>            df[&#39;LOADED_AT&#39;] = self.batch_timestamp<br>            <br>            # Standard transformations<br>            for col in df.select_dtypes(include=[&#39;datetime64&#39;]).columns:<br>                df[col] = df[col].dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>            <br>            df = df.replace({pd.NA: None, pd.NaT: None})<br>            <br>            # Convert column names to uppercase for DuckDB<br>            df.columns = [col.upper() for col in df.columns]<br>            df = self.remove_duplicate_primary_keys(df, table_name)<br>            <br>            return df<br>            <br>        except Exception as e:<br>            print(f&quot;Transform error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def flatten_json_df(self, df, table_name):<br>        &quot;&quot;&quot;Flatten nested JSON structures&quot;&quot;&quot;<br>        try:<br>            json_columns = [<br>                col for col in df.columns <br>                if df[col].dtype == &#39;object&#39; and <br>                isinstance(df[col].dropna().iloc[0] if not df[col].isna().all() else None, (dict, list))<br>            ]<br>            <br>            if not json_columns:<br>                return df<br><br>            flat_df = df.copy()<br>            <br>            for col in json_columns:<br>                try:<br>                    if isinstance(df[col].dropna().iloc[0], dict):<br>                        flattened = pd.json_normalize(df[col].dropna(), sep=&#39;_&#39;)<br>                        flat_df = flat_df.drop(columns=[col])<br>                        for new_col in flattened.columns:<br>                            flat_df[f&quot;{col}_{new_col}&quot;] = flattened[new_col]<br>                    elif isinstance(df[col].dropna().iloc[0], list):<br>                        flat_df[col] = df[col].apply(lambda x: json.dumps(x) if isinstance(x, list) else x)<br>                except Exception as e:<br>                    print(f&quot;Warning: Could not flatten column {col}: {str(e)}&quot;)<br>                    continue<br>            <br>            return flat_df<br>        except Exception as e:<br>            print(f&quot;JSON flattening error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def save_to_s3_historic(self, df, table_name, metadata):<br>        &quot;&quot;&quot;Save transformed data and metadata to S3 historic bucket&quot;&quot;&quot;<br>        try:<br>            <br>            output_dir = Path(&#39;ingested_data&#39;)<br>            output_dir.mkdir(parents=True, exist_ok=True)<br>            <br>            # Save as CSV<br>            csv_buffer = io.StringIO()<br>            df.to_csv(csv_buffer, index=False)<br><br>            # Save to historic data folder<br>            self.s3_client.put_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}.csv&#39;,<br>                Body=csv_buffer.getvalue().encode(&#39;utf-8&#39;)<br>            )<br>            <br>            # Save metadata<br>            self.s3_client.put_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}_metadata.json&#39;,<br>                Body=json.dumps(metadata, default=str)<br>            )<br>            <br>            print(f&quot;Successfully saved {table_name} to historic bucket as CSV with metadata&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error saving to S3 historic bucket: {str(e)}&quot;)<br>            raise<br><br>    def find_valid_date_column(self, df, table_name):<br>        &quot;&quot;&quot;Find the first valid date column from the possible options&quot;&quot;&quot;<br>        possible_columns = self.get_date_column(table_name)<br>        <br>        for col in possible_columns:<br>            if col in df.columns:<br>                return col<br>                <br>        return None<br><br>    def get_date_column(self, table_name):<br>        &quot;&quot;&quot;Return the appropriate date column for each table with fallbacks&quot;&quot;&quot;<br>        date_columns = {<br>            &#39;customers&#39;: [&#39;signup_date&#39;, &#39;last_login&#39;, &#39;created_at&#39;],<br>            &#39;orders&#39;: [&#39;order_date&#39;, &#39;created_at&#39;, &#39;updated_at&#39;],<br>            &#39;products&#39;: [&#39;created_at&#39;],<br>            &#39;order_items&#39;: [&#39;created_at&#39;, &#39;order_date&#39;],<br>            &#39;reviews&#39;: [&#39;created_at&#39;, &#39;order_date&#39;],<br>            &#39;interactions&#39;: [&#39;event_date&#39;, &#39;created_at&#39;],<br>            &#39;categories&#39;: [&#39;created_at&#39;],<br>            &#39;subcategories&#39;: [&#39;created_at&#39;]<br>        }<br>        <br>        clean_table_name = table_name.replace(&#39;latest_&#39;, &#39;&#39;)<br>        return date_columns.get(clean_table_name, [&#39;created_at&#39;])<br><br>    def run_initial_load(self):<br>        &quot;&quot;&quot;Execute ETL process for initial historic data setup&quot;&quot;&quot;<br>        try:<br>            print(&quot;\nStarting initial historic data load...&quot;)<br>            <br>            # Create local directory for CSV files if it doesn&#39;t exist<br>            os.makedirs(&quot;ingested_data&quot;, exist_ok=True)<br>            <br>            for table in self.postgres_tables + self.s3_tables:<br>                print(f&quot;\nProcessing {table}&quot;)<br>                <br>                try:<br>                    # Extract and combine data<br>                    historic_df = (self.extract_from_s3(table, &#39;historic&#39;) <br>                                if table in self.s3_tables <br>                                else self.extract_from_postgres(table, &#39;historic&#39;))<br>                    <br>                    latest_df = (self.extract_from_s3(table, &#39;latest&#39;) <br>                            if table in self.s3_tables <br>                            else self.extract_from_postgres(table, &#39;latest&#39;))<br>                    <br>                    # Find valid date column<br>                    date_column = self.find_valid_date_column(latest_df, table)<br>                    <br>                    if date_column:<br>                        min_latest_date = latest_df[date_column].min()<br>                        print(f&quot;Latest data starts from: {min_latest_date}&quot;)<br>                    else:<br>                        print(f&quot;Warning: No valid date column found for {table}&quot;)<br>                        min_latest_date = None<br>                    <br>                    # Combine and transform data<br>                    combined_df = pd.concat([historic_df, latest_df], ignore_index=True)<br>                    transformed_df = self.transform_data(combined_df, table)<br>                    <br>                    # Save to local CSV<br>                    combined_path = f&quot;ingested_data/{table}_combined.csv&quot;<br>                    transformed_df.to_csv(combined_path, index=False)<br>                    print(f&quot;Saved combined data to {combined_path}&quot;)<br>                    <br>                    # Prepare metadata<br>                    metadata = {<br>                        &#39;table_name&#39;: table,<br>                        &#39;batch_id&#39;: self.batch_id,<br>                        &#39;timestamp&#39;: self.batch_timestamp,<br>                        &#39;historic_records&#39;: len(historic_df),<br>                        &#39;latest_records&#39;: len(latest_df),<br>                        &#39;total_records&#39;: len(combined_df),<br>                        &#39;date_column_used&#39;: date_column,<br>                        &#39;columns&#39;: transformed_df.columns.tolist(),<br>                        &#39;data_types&#39;: transformed_df.dtypes.astype(str).to_dict(),<br>                        &#39;min_date&#39;: min_latest_date if date_column else None<br>                    }<br>                    <br>                    # Save to S3 as historic data<br>                    self.save_to_s3_historic(transformed_df, table, metadata)<br>                    <br>                    <br>                    print(f&quot;&quot;&quot;<br>                    Completed processing for {table}:<br>                    - Historic records: {len(historic_df)}<br>                    - Latest records: {len(latest_df)}<br>                    - Total records processed: {len(combined_df)}<br>                    - Date column used: {date_column if date_column else &#39;None&#39;}<br>                    - Data saved locally to: {combined_path}<br>                    - Data saved to S3 historic bucket<br>                    &quot;&quot;&quot;)<br><br>                except Exception as e:<br>                    print(f&quot;Error processing table {table}: {str(e)}&quot;)<br>                    continue<br><br>        except Exception as e:<br>            print(f&quot;Initial load process error: {str(e)}&quot;)<br>            raise<br>        finally:<br>            print(&quot;\nInitial historic data load completed. Connections closed.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        etl = InitialHistoricETL()<br>        etl.run_initial_load()<br>    except Exception as e:<br>        print(f&quot;Main execution error: {str(e)}&quot;)<br>        raise</pre><p>3. Run:</p><pre>python src/pipeline/0_ingest_historic_synthetic_data.py</pre><p>4. Initially check if the latest data is appended to the historic data in the ingested_data folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1_dCps7O4cLYggHDVhGow.png" /></figure><p>5. Check section III. 1 of this <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">article</a> for the S3 and Postgres data checking.</p><p>6. Check data in ECOM_RAW on MotherDuck and run the sample query to test.</p><p>The ECOM_RAW data follows the following data model. <a href="https://dbdiagram.io/d/ecom_raw_schema-6767d960fc29fb2b3b1475af">See model in detail here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKJh17xnjiMfEvrIfkDL0g.png" /></figure><h3>2. Latest Append ETL Ingestion</h3><p>Steps:</p><ol><li>Copy and paste the following code to ingest_latest_synthetic_data.py.</li></ol><p>Note: The script’s objective is the same as the initial append, but extracts historic data from historic-ecom/csv instead of the original generated historic data.</p><pre>import os<br>import pandas as pd<br>import boto3<br>import json<br>from sqlalchemy import create_engine<br>from dotenv import load_dotenv<br>import psycopg2<br>import tempfile<br>from pandas import json_normalize<br>from datetime import datetime<br>import uuid<br>import io<br>import duckdb<br><br>load_dotenv()<br><br>class IncrementalETL:<br>    def __init__(self, motherduck_token=None):<br>        # Initialize connections<br>        self._init_postgres()<br>        self._init_s3()<br>        self._init_duckdb()<br>        # self._init_motherduck(motherduck_token)<br>        <br>        # Store token for later use after database reset<br>        self.motherduck_token = motherduck_token or os.getenv(&#39;MOTHERDUCK_TOKEN&#39;)<br>        if not self.motherduck_token:<br>            raise ValueError(&quot;MotherDuck token not provided&quot;)<br>        <br>        <br>        # Define source mappings<br>        self.postgres_tables = [&#39;categories&#39;, &#39;subcategories&#39;, &#39;order_items&#39;, &#39;interactions&#39;]<br>        self.s3_tables = [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;]<br>        <br>        # Track batch information<br>        self.batch_id = str(uuid.uuid4())<br>        self.batch_timestamp = datetime.now()<br>        <br>    def _init_postgres(self):<br>        &quot;&quot;&quot;Initialize PostgreSQL connection&quot;&quot;&quot;<br>        self.pg_conn_string = f&quot;postgresql://{os.getenv(&#39;POSTGRES_USER&#39;)}:{os.getenv(&#39;POSTGRES_PASSWORD&#39;)}@{os.getenv(&#39;POSTGRES_HOST&#39;)}:{os.getenv(&#39;POSTGRES_PORT&#39;)}/{os.getenv(&#39;POSTGRES_DB&#39;)}&quot;<br>        self.pg_engine = create_engine(self.pg_conn_string)<br><br>    def _init_s3(self):<br>        &quot;&quot;&quot;Initialize S3 clients&quot;&quot;&quot;<br>        s3_credentials = {<br>            &#39;aws_access_key_id&#39;: os.getenv(&#39;AWS_S3_ACCESS_KEY_ID&#39;),<br>            &#39;aws_secret_access_key&#39;: os.getenv(&#39;AWS_S3_SECRET_ACCESS_KEY&#39;)<br>        }<br>        <br>        self.s3_client = boto3.client(&#39;s3&#39;, **s3_credentials)<br>        self.historic_bucket = os.getenv(&#39;AWS_S3_HISTORIC_SYNTH&#39;)<br>        self.latest_bucket = os.getenv(&#39;AWS_S3_LATEST_SYNTH&#39;)<br><br>    def _init_duckdb(self):<br>        &quot;&quot;&quot;Initialize local DuckDB connection&quot;&quot;&quot;<br>        try:<br>            # Connect to local DuckDB file<br>            self.duck_conn = duckdb.connect(&#39;ecom_db&#39;)<br>            <br>            # Create schema if it doesn&#39;t exist<br>            self.duck_conn.execute(&quot;CREATE SCHEMA IF NOT EXISTS ecom_raw&quot;)<br>            <br>            print(&quot;Successfully connected to local DuckDB&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Local DuckDB initialization error: {str(e)}&quot;)<br>            raise<br><br>    def _init_motherduck(self, token):<br>        &quot;&quot;&quot;Initialize MotherDuck connection&quot;&quot;&quot;<br>        try:<br>            # Use token from parameter or environment variable<br>            md_token = token or os.getenv(&#39;MOTHERDUCK_TOKEN&#39;)<br>            if not md_token:<br>                raise ValueError(&quot;MotherDuck token not provided&quot;)<br><br>            # First connect to MotherDuck without specifying a database<br>            connection_string = f&quot;md:?motherduck_token={md_token}&quot;<br>            self.md_conn = duckdb.connect(connection_string)<br>            <br>            # Create database if it doesn&#39;t exist<br>            self.md_conn.execute(&quot;CREATE DATABASE IF NOT EXISTS ecom_db&quot;)<br>            <br>            # Close initial connection<br>            self.md_conn.close()<br>            <br>            # Now connect specifically to the ecom_db database<br>            connection_string = f&quot;md:ecom_db?motherduck_token={md_token}&quot;<br>            self.md_conn = duckdb.connect(connection_string)<br>            <br>            # Create schema if it doesn&#39;t exist<br>            self.md_conn.execute(&quot;CREATE SCHEMA IF NOT EXISTS ecom_raw&quot;)<br>            <br>            print(&quot;Successfully connected to MotherDuck&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;MotherDuck initialization error: {str(e)}&quot;)<br>            raise<br><br>    def extract_historic_from_s3(self, table_name):<br>        &quot;&quot;&quot;Extract historic data from S3 CSV files&quot;&quot;&quot;<br>        try:<br>            # Get CSV file from historic bucket<br>            response = self.s3_client.get_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}.csv&#39;<br>            )<br>            <br>            # Read CSV content<br>            csv_content = response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>            df = pd.read_csv(io.StringIO(csv_content))<br>            df.columns = [col.upper() for col in df.columns]<br>            return df<br>            <br>        except Exception as e:<br>            print(f&quot;Historic S3 extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def extract_latest_from_postgres(self, table_name):<br>        &quot;&quot;&quot;Extract latest data from PostgreSQL&quot;&quot;&quot;<br>        try:<br>            query = f&quot;SELECT * FROM latest_{table_name}&quot;<br>            df = pd.read_sql(query, self.pg_engine)<br>            df.columns = [col.upper() for col in df.columns]<br>            return df<br>        except Exception as e:<br>            print(f&quot;PostgreSQL extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def extract_latest_from_s3(self, table_name):<br>        &quot;&quot;&quot;Extract latest data from S3&quot;&quot;&quot;<br>        try:<br>            response = self.s3_client.get_object(<br>                Bucket=self.latest_bucket,<br>                Key=f&#39;json/{table_name}.json&#39;<br>            )<br>            <br>            json_content = json.loads(response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;))<br>            df = pd.DataFrame(json_content[&#39;data&#39;])<br>            df.columns = [col.upper() for col in df.columns]<br>            return df<br>        <br>        except Exception as e:<br>            print(f&quot;Latest S3 extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br>        <br>    def get_primary_keys(self, table_name):<br>        &quot;&quot;&quot;Return primary key columns for each table&quot;&quot;&quot;<br>        pk_mapping = {<br>            &#39;CUSTOMERS&#39;: [&#39;CUSTOMER_ID&#39;],<br>            &#39;ORDERS&#39;: [&#39;ORDER_ID&#39;],<br>            &#39;PRODUCTS&#39;: [&#39;PRODUCT_ID&#39;],<br>            &#39;ORDER_ITEMS&#39;: [&#39;ORDER_ITEM_ID&#39;],<br>            &#39;CATEGORIES&#39;: [&#39;CATEGORY_ID&#39;],<br>            &#39;SUBCATEGORIES&#39;: [&#39;SUBCATEGORY_ID&#39;],<br>            &#39;REVIEWS&#39;: [&#39;REVIEW_ID&#39;],<br>            &#39;INTERACTIONS&#39;: [&#39;EVENT_ID&#39;]  # Changed from &#39;id&#39;<br>        }<br>        clean_table = table_name.upper().replace(&#39;LATEST_&#39;, &#39;&#39;)<br>        return pk_mapping.get(clean_table, [&#39;EVENT_ID&#39; if &#39;INTERACTIONS&#39; in clean_table else &#39;id&#39;])<br><br>    def remove_duplicate_primary_keys(self, df, table_name):<br>        &quot;&quot;&quot;Remove rows with duplicate primary keys, handling missing keys&quot;&quot;&quot;<br>        try:<br>            # Get primary keys for the table<br>            primary_keys = self.get_primary_keys(table_name)<br>            <br>            if not primary_keys or primary_keys == [&#39;id&#39;]:<br>                # For interactions table, use EVENT_ID as primary key<br>                if &#39;EVENT_ID&#39; in df.columns:<br>                    primary_keys = [&#39;EVENT_ID&#39;]<br>                else:<br>                    print(f&quot;Warning: No valid primary keys found for {table_name}. Skipping deduplication.&quot;)<br>                    return df<br><br>            # Ensure all primary keys exist in the DataFrame<br>            missing_keys = [key for key in primary_keys if key not in df.columns]<br>            if missing_keys:<br>                print(f&quot;Warning: Missing primary keys {missing_keys} in table {table_name}.&quot;)<br>                return df<br><br>            # Sort by LOADED_AT if exists, keeping most recent<br>            if &#39;LOADED_AT&#39; in df.columns:<br>                df[&#39;LOADED_AT&#39;] = pd.to_datetime(df[&#39;LOADED_AT&#39;], errors=&#39;coerce&#39;)<br>                df = df.sort_values(&#39;LOADED_AT&#39;, ascending=False)<br><br>            # Deduplicate based on primary keys<br>            df = df.drop_duplicates(subset=primary_keys, keep=&#39;first&#39;)<br>            <br>            return df<br>        except Exception as e:<br>            print(f&quot;Error removing duplicate primary keys for {table_name}: {str(e)}&quot;)<br>            raise<br>    <br>    def transform_data(self, df, table_name):<br>        &quot;&quot;&quot;Transform data with enhanced column handling and type conversion&quot;&quot;&quot;<br>        try:<br>            print(f&quot;\nDETAILED COLUMN ANALYSIS FOR {table_name}&quot;)<br>            print(&quot;=&quot; * 50)<br>            <br>            # Force column names to uppercase first<br>            df.columns = [col.upper() for col in df.columns]<br>            <br>            # Handle reviews table special case - add REVIEW_ID if missing<br>            if table_name.upper().startswith(&#39;REVIEWS&#39;) and &#39;REVIEW_ID&#39; not in df.columns:<br>                df[&#39;REVIEW_ID&#39;] = range(1, len(df) + 1)<br>            <br>            # Convert DATA_SOURCE to string type explicitly<br>            if &#39;DATA_SOURCE&#39; in df.columns:<br>                df[&#39;DATA_SOURCE&#39;] = df[&#39;DATA_SOURCE&#39;].astype(str)<br>                <br>            # Handle datetime columns before adding metadata<br>            date_columns = df.select_dtypes(include=[&#39;datetime64&#39;]).columns<br>            for col in date_columns:<br>                try:<br>                    df[col] = pd.to_datetime(df[col], errors=&#39;coerce&#39;)<br>                    df[col] = df[col].dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>                except Exception as e:<br>                    print(f&quot;Warning: Error converting datetime column {col}: {str(e)}&quot;)<br>            <br>            # Add metadata columns with explicit types<br>            df[&#39;DATA_SOURCE&#39;] = df.get(&#39;DATA_SOURCE&#39;, &#39;historic&#39;)<br>            df[&#39;BATCH_ID&#39;] = df.get(&#39;BATCH_ID&#39;, str(self.batch_id))<br>            df[&#39;LOADED_AT&#39;] = df.get(&#39;LOADED_AT&#39;, self.batch_timestamp.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;))<br>            <br>            # Handle NA/NaT values<br>            df = df.replace({pd.NA: None, pd.NaT: None})<br>            <br>            # Convert types based on expected schema<br>            df = self.convert_column_types(df, table_name)<br>            <br>            # Remove duplicate rows based on primary keys<br>            df = self.remove_duplicate_primary_keys(df, table_name)<br>            <br>            print(&quot;\nFinal columns with types:&quot;)<br>            for col in df.columns:<br>                print(f&quot;- {col}: {df[col].dtype}&quot;)<br>            <br>            return df<br>                <br>        except Exception as e:<br>            print(f&quot;Transform error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def flatten_json_df(self, df, table_name):<br>        &quot;&quot;&quot;Flatten nested JSON structures&quot;&quot;&quot;<br>        try:<br>            json_columns = [<br>                col for col in df.columns <br>                if df[col].dtype == &#39;object&#39; and <br>                isinstance(df[col].dropna().iloc[0] if not df[col].isna().all() else None, (dict, list))<br>            ]<br>            <br>            if not json_columns:<br>                return df<br><br>            flat_df = df.copy()<br>            <br>            for col in json_columns:<br>                try:<br>                    if isinstance(df[col].dropna().iloc[0], dict):<br>                        flattened = pd.json_normalize(df[col].dropna(), sep=&#39;_&#39;)<br>                        flat_df = flat_df.drop(columns=[col])<br>                        for new_col in flattened.columns:<br>                            flat_df[f&quot;{col}_{new_col}&quot;] = flattened[new_col]<br>                    elif isinstance(df[col].dropna().iloc[0], list):<br>                        flat_df[col] = df[col].apply(lambda x: json.dumps(x) if isinstance(x, list) else x)<br>                except Exception as e:<br>                    print(f&quot;Warning: Could not flatten column {col}: {str(e)}&quot;)<br>                    continue<br>            <br>            return flat_df<br>        except Exception as e:<br>            print(f&quot;JSON flattening error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def save_to_s3_historic(self, df, table_name, metadata):<br>        &quot;&quot;&quot;Save transformed data and metadata to S3 historic bucket&quot;&quot;&quot;<br>        try:<br>            # Save as CSV<br>            csv_buffer = io.StringIO()<br>            df.to_csv(csv_buffer, index=False)<br>            <br>            # Save to historic data folder<br>            self.s3_client.put_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}.csv&#39;,<br>                Body=csv_buffer.getvalue().encode(&#39;utf-8&#39;)<br>            )<br>            <br>            # Save metadata<br>            self.s3_client.put_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}_metadata.json&#39;,<br>                Body=json.dumps(metadata, default=str)<br>            )<br>            <br>            print(f&quot;Successfully saved {table_name} to historic bucket as CSV with metadata&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error saving to S3 historic bucket: {str(e)}&quot;)<br>            raise<br>        <br>    def get_column_types(self, table_name):<br>        &quot;&quot;&quot;Define expected column types for each table&quot;&quot;&quot;<br>        type_mappings = {<br>            &#39;REVIEWS&#39;: {<br>                &#39;PRODUCT_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;ORDER_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;CUSTOMER_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;REVIEW_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;REVIEW_SCORE&#39;: &#39;BIGINT&#39;,<br>                &#39;REVIEW_TEXT&#39;: &#39;VARCHAR&#39;,<br>                &#39;DATA_SOURCE&#39;: &#39;VARCHAR&#39;,<br>                &#39;BATCH_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;LOADED_AT&#39;: &#39;TIMESTAMP&#39;<br>            },<br>            &#39;ORDERS&#39;: {<br>                &#39;ORDER_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;CUSTOMER_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;STATUS&#39;: &#39;VARCHAR&#39;,<br>                &#39;TOTAL_AMOUNT&#39;: &#39;DOUBLE&#39;,<br>                &#39;SHIPPING_COST&#39;: &#39;DOUBLE&#39;,<br>                &#39;PAYMENT_METHOD&#39;: &#39;VARCHAR&#39;,<br>                &#39;SHIPPING_ADDRESS&#39;: &#39;VARCHAR&#39;,<br>                &#39;BILLING_ADDRESS&#39;: &#39;VARCHAR&#39;,<br>                &#39;ORDER_DATE&#39;: &#39;TIMESTAMP&#39;,<br>                &#39;CREATED_AT&#39;: &#39;TIMESTAMP&#39;,<br>                &#39;UPDATED_AT&#39;: &#39;TIMESTAMP&#39;,<br>                &#39;DATA_SOURCE&#39;: &#39;VARCHAR&#39;,<br>                &#39;BATCH_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;LOADED_AT&#39;: &#39;TIMESTAMP&#39;<br>            },<br>            &#39;ORDER_ITEMS&#39;: {<br>                &#39;ORDER_ITEM_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;ORDER_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;PRODUCT_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;QUANTITY&#39;: &#39;BIGINT&#39;,<br>                &#39;UNIT_PRICE&#39;: &#39;DOUBLE&#39;,<br>                &#39;TOTAL_PRICE&#39;: &#39;DOUBLE&#39;,<br>                &#39;CREATED_AT&#39;: &#39;TIMESTAMP&#39;,<br>                &#39;DATA_SOURCE&#39;: &#39;VARCHAR&#39;,<br>                &#39;BATCH_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;LOADED_AT&#39;: &#39;TIMESTAMP&#39;<br>            },<br>            &#39;PRODUCTS&#39;: {<br>                &#39;PRODUCT_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;CATEGORY_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;SUBCATEGORY_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;PRODUCT_NAME&#39;: &#39;VARCHAR&#39;,<br>                &#39;DESCRIPTION&#39;: &#39;VARCHAR&#39;,<br>                &#39;BASE_PRICE&#39;: &#39;DOUBLE&#39;,<br>                &#39;SALE_PRICE&#39;: &#39;DOUBLE&#39;,<br>                &#39;STOCK_QUANTITY&#39;: &#39;BIGINT&#39;,<br>                &#39;WEIGHT_KG&#39;: &#39;DOUBLE&#39;,<br>                &#39;IS_ACTIVE&#39;: &#39;BOOLEAN&#39;,<br>                &#39;BRAND&#39;: &#39;VARCHAR&#39;,<br>                &#39;SKU&#39;: &#39;VARCHAR&#39;,<br>                &#39;RATING&#39;: &#39;DOUBLE&#39;,<br>                &#39;REVIEW_COUNT&#39;: &#39;BIGINT&#39;,<br>                &#39;CREATED_AT&#39;: &#39;TIMESTAMP&#39;,<br>                &#39;DATA_SOURCE&#39;: &#39;VARCHAR&#39;,<br>                &#39;BATCH_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;LOADED_AT&#39;: &#39;TIMESTAMP&#39;<br>            },<br>            &#39;CUSTOMERS&#39;: {<br>                &#39;CUSTOMER_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;EMAIL&#39;: &#39;VARCHAR&#39;,<br>                &#39;FIRST_NAME&#39;: &#39;VARCHAR&#39;,<br>                &#39;LAST_NAME&#39;: &#39;VARCHAR&#39;,<br>                &#39;AGE&#39;: &#39;BIGINT&#39;,<br>                &#39;GENDER&#39;: &#39;VARCHAR&#39;,<br>                &#39;ANNUAL_INCOME&#39;: &#39;DOUBLE&#39;,<br>                &#39;MARITAL_STATUS&#39;: &#39;VARCHAR&#39;,<br>                &#39;EDUCATION&#39;: &#39;VARCHAR&#39;,<br>                &#39;LOCATION_TYPE&#39;: &#39;VARCHAR&#39;,<br>                &#39;CITY&#39;: &#39;VARCHAR&#39;,<br>                &#39;STATE&#39;: &#39;VARCHAR&#39;,<br>                &#39;COUNTRY&#39;: &#39;VARCHAR&#39;,<br>                &#39;SIGNUP_DATE&#39;: &#39;TIMESTAMP&#39;,<br>                &#39;LAST_LOGIN&#39;: &#39;TIMESTAMP&#39;,<br>                &#39;PREFERRED_CHANNEL&#39;: &#39;VARCHAR&#39;,<br>                &#39;IS_ACTIVE&#39;: &#39;BOOLEAN&#39;,<br>                &#39;DATA_SOURCE&#39;: &#39;VARCHAR&#39;,<br>                &#39;BATCH_ID&#39;: &#39;VARCHAR&#39;,<br>                &#39;LOADED_AT&#39;: &#39;TIMESTAMP&#39;<br>            }<br>        }<br>        return type_mappings.get(table_name.upper().replace(&#39;LATEST_&#39;, &#39;&#39;), {})<br><br>    def convert_column_types(self, df, table_name):<br>        &quot;&quot;&quot;Convert DataFrame columns to appropriate types&quot;&quot;&quot;<br>        expected_types = self.get_column_types(table_name)<br>        <br>        if not expected_types:<br>            return df  # Return unchanged if no type mapping exists<br>        <br>        for column in df.columns:<br>            if column in expected_types:<br>                try:<br>                    dtype = expected_types[column]<br>                    if dtype == &#39;BIGINT&#39;:<br>                        df[column] = pd.to_numeric(df[column], errors=&#39;coerce&#39;).fillna(0).astype(&#39;int64&#39;)<br>                    elif dtype == &#39;DOUBLE&#39;:<br>                        df[column] = pd.to_numeric(df[column], errors=&#39;coerce&#39;).fillna(0.0)<br>                    elif dtype == &#39;VARCHAR&#39;:<br>                        # Special handling for ID columns<br>                        if column.endswith(&#39;_ID&#39;):<br>                            df[column] = df[column].fillna(&#39;&#39;).astype(str)<br>                        else:<br>                            df[column] = df[column].fillna(&#39;&#39;).astype(str)<br>                    elif dtype == &#39;BOOLEAN&#39;:<br>                        df[column] = df[column].fillna(False).astype(bool)<br>                    elif dtype == &#39;TIMESTAMP&#39;:<br>                        df[column] = pd.to_datetime(df[column], errors=&#39;coerce&#39;)<br>                        df[column] = df[column].dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>                except Exception as e:<br>                    print(f&quot;Warning: Error converting column {column} to {dtype}: {str(e)}&quot;)<br>                    # Keep the original data if conversion fails<br>                    continue<br>        <br>        return df<br><br>    def get_duck_type(self, dtype, column_name):<br>        &quot;&quot;&quot;Determine DuckDB column type based on pandas dtype and column name&quot;&quot;&quot;<br>        # Always use VARCHAR for ID columns<br>        if column_name.upper().endswith(&#39;_ID&#39;):<br>            return &#39;VARCHAR&#39;<br>        <br>        # Handle other types<br>        if pd.api.types.is_integer_dtype(dtype):<br>            return &#39;BIGINT&#39;<br>        elif pd.api.types.is_float_dtype(dtype):<br>            return &#39;DOUBLE&#39;<br>        elif pd.api.types.is_bool_dtype(dtype):<br>            return &#39;BOOLEAN&#39;<br>        elif pd.api.types.is_datetime64_any_dtype(dtype):<br>            return &#39;TIMESTAMP&#39;<br>        else:<br>            return &#39;VARCHAR&#39;<br><br>    def load_to_motherduck(self, df, table_name):<br>        &quot;&quot;&quot;Load data to MotherDuck with type handling&quot;&quot;&quot;<br>        try:<br>            full_table_name = f&quot;ecom_raw.{table_name.lower()}&quot;<br>            <br>            # Force string types for metadata columns<br>            metadata_columns = [&#39;DATA_SOURCE&#39;, &#39;BATCH_ID&#39;]<br>            for col in metadata_columns:<br>                if col in df.columns:<br>                    df[col] = df[col].astype(str)<br>            <br>            # Get column definitions with explicit types<br>            column_definitions = []<br>            for col, dtype in df.dtypes.items():<br>                col_type = self.get_duck_type(dtype, col)<br>                if col in metadata_columns:<br>                    col_type = &#39;VARCHAR&#39;  # Force VARCHAR for metadata columns<br>                column_definitions.append(f&#39;&quot;{col}&quot; {col_type}&#39;)<br>            <br>            # Create target table if it doesn&#39;t exist<br>            self.duck_conn.execute(f&quot;&quot;&quot;<br>                CREATE TABLE IF NOT EXISTS {full_table_name} (<br>                    {&#39;, &#39;.join(column_definitions)}<br>                )<br>            &quot;&quot;&quot;)<br>            <br>            # Get primary keys<br>            primary_keys = [pk.upper() for pk in self.get_primary_keys(table_name)]<br>            <br>            # Create view of new data<br>            self.duck_conn.execute(&quot;CREATE TEMPORARY VIEW new_data AS SELECT * FROM df&quot;)<br>            <br>            # Delete existing records that will be updated<br>            if primary_keys:<br>                delete_condition = &quot; AND &quot;.join([<br>                    f&quot;{full_table_name}.\&quot;{pk}\&quot; IN (SELECT \&quot;{pk}\&quot; FROM df)&quot;<br>                    for pk in primary_keys<br>                ])<br>                <br>                self.duck_conn.execute(f&quot;&quot;&quot;<br>                    DELETE FROM {full_table_name}<br>                    WHERE {delete_condition}<br>                &quot;&quot;&quot;)<br>            <br>            # Insert new records directly from DataFrame<br>            self.duck_conn.execute(f&quot;&quot;&quot;<br>                INSERT INTO {full_table_name}<br>                SELECT * FROM df<br>            &quot;&quot;&quot;)<br>            <br>            # Get stats<br>            row_count = self.duck_conn.execute(f&quot;&quot;&quot;<br>                SELECT COUNT(*) FROM {full_table_name}<br>            &quot;&quot;&quot;).fetchone()[0]<br>            <br>            print(f&quot;Successfully loaded data to MotherDuck {full_table_name}:&quot;)<br>            print(f&quot;- Rows in table: {row_count}&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error loading to MotherDuck: {str(e)}&quot;)<br>            raise<br><br>    def load_to_duckdb(self, df, table_name):<br>        &quot;&quot;&quot;Load data to local DuckDB with consistent type handling&quot;&quot;&quot;<br>        try:<br>            full_table_name = f&quot;ecom_raw.{table_name.lower()}&quot;<br>            <br>            # Force all ID columns to VARCHAR/string type<br>            for col in df.columns:<br>                if col.upper().endswith(&#39;_ID&#39;):<br>                    df[col] = df[col].astype(str)<br>            <br>            # Force string types for metadata columns<br>            metadata_columns = [&#39;DATA_SOURCE&#39;, &#39;BATCH_ID&#39;]<br>            for col in metadata_columns:<br>                if col in df.columns:<br>                    df[col] = df[col].astype(str)<br>            <br>            # Get column definitions with explicit types<br>            column_definitions = []<br>            for col, dtype in df.dtypes.items():<br>                col_type = self.get_duck_type(dtype, col)<br>                if col.upper().endswith(&#39;_ID&#39;) or col in metadata_columns:<br>                    col_type = &#39;VARCHAR&#39;  # Force VARCHAR for ID and metadata columns<br>                column_definitions.append(f&#39;&quot;{col}&quot; {col_type}&#39;)<br>            <br>            # Create target table if it doesn&#39;t exist<br>            create_table_sql = f&quot;&quot;&quot;<br>                CREATE TABLE IF NOT EXISTS {full_table_name} (<br>                    {&#39;, &#39;.join(column_definitions)}<br>                )<br>            &quot;&quot;&quot;<br>            self.duck_conn.execute(create_table_sql)<br>            <br>            # Get primary keys<br>            primary_keys = [pk.upper() for pk in self.get_primary_keys(table_name)]<br>            <br>            # Create temporary table for new data with same schema<br>            temp_table_name = f&quot;temp_{table_name.lower()}&quot;<br>            self.duck_conn.execute(f&quot;DROP TABLE IF EXISTS {temp_table_name}&quot;)<br>            self.duck_conn.execute(f&quot;&quot;&quot;<br>                CREATE TEMPORARY TABLE {temp_table_name} AS <br>                SELECT * FROM {full_table_name} WHERE 1=0<br>            &quot;&quot;&quot;)<br>            <br>            # Insert data into temporary table<br>            self.duck_conn.execute(f&quot;&quot;&quot;<br>                INSERT INTO {temp_table_name}<br>                SELECT * FROM df<br>            &quot;&quot;&quot;)<br>            <br>            # Delete existing records that will be updated<br>            if primary_keys:<br>                pk_conditions = []<br>                for pk in primary_keys:<br>                    pk_conditions.append(<br>                        f&quot;{full_table_name}.\&quot;{pk}\&quot;::VARCHAR IN (SELECT \&quot;{pk}\&quot;::VARCHAR FROM {temp_table_name})&quot;<br>                    )<br>                delete_condition = &quot; AND &quot;.join(pk_conditions)<br>                <br>                self.duck_conn.execute(f&quot;&quot;&quot;<br>                    DELETE FROM {full_table_name}<br>                    WHERE {delete_condition}<br>                &quot;&quot;&quot;)<br>            <br>            # Insert new records from temporary table<br>            self.duck_conn.execute(f&quot;&quot;&quot;<br>                INSERT INTO {full_table_name}<br>                SELECT * FROM {temp_table_name}<br>            &quot;&quot;&quot;)<br>            <br>            # Clean up temporary table<br>            self.duck_conn.execute(f&quot;DROP TABLE IF EXISTS {temp_table_name}&quot;)<br>            <br>            # Get stats<br>            row_count = self.duck_conn.execute(f&quot;&quot;&quot;<br>                SELECT COUNT(*) FROM {full_table_name}<br>            &quot;&quot;&quot;).fetchone()[0]<br>            <br>            print(f&quot;Successfully loaded data to local DuckDB {full_table_name}:&quot;)<br>            print(f&quot;- Rows in table: {row_count}&quot;)<br>            <br>            return full_table_name<br>            <br>        except Exception as e:<br>            print(f&quot;Error loading to DuckDB: {str(e)}&quot;)<br>            raise<br><br>    def cleanup_temp_tables(self):<br>        &quot;&quot;&quot;Clean up any temporary tables that might exist&quot;&quot;&quot;<br>        try:<br>            # Get list of temporary tables<br>            temp_tables = self.duck_conn.execute(&quot;&quot;&quot;<br>                SELECT table_name <br>                FROM information_schema.tables <br>                WHERE table_schema = &#39;ecom_raw&#39; <br>                AND table_name LIKE &#39;temp_%&#39;<br>            &quot;&quot;&quot;).fetchall()<br>            <br>            # Drop each temporary table<br>            for table in temp_tables:<br>                self.duck_conn.execute(f&quot;DROP TABLE IF EXISTS ecom_raw.{table[0]}&quot;)<br>                print(f&quot;Dropped temporary table: {table[0]}&quot;)<br>                <br>        except Exception as e:<br>            print(f&quot;Error cleaning up temporary tables: {str(e)}&quot;)<br><br>    def sync_to_motherduck(self, table_name):<br>        &quot;&quot;&quot;Sync local DuckDB table to MotherDuck with improved cross-database query handling&quot;&quot;&quot;<br>        try:<br>            full_table_name = f&quot;ecom_raw.{table_name.lower()}&quot;<br>            <br>            # Get the schema from local DuckDB<br>            schema_query = f&quot;&quot;&quot;<br>            SELECT column_name, data_type <br>            FROM information_schema.columns <br>            WHERE table_name = &#39;{table_name.lower()}&#39;<br>            AND table_schema = &#39;ecom_raw&#39;<br>            ORDER BY ordinal_position<br>            &quot;&quot;&quot;<br>            columns = self.duck_conn.execute(schema_query).fetchall()<br>            <br>            # Build CREATE TABLE statement<br>            column_definitions = [f&#39;&quot;{col[0]}&quot; {col[1]}&#39; for col in columns]<br>            create_table_sql = f&quot;&quot;&quot;<br>            CREATE TABLE IF NOT EXISTS {full_table_name} (<br>                {&#39;, &#39;.join(column_definitions)}<br>            )<br>            &quot;&quot;&quot;<br>            <br>            # Create table in MotherDuck<br>            self.md_conn.execute(create_table_sql)<br>            <br>            # Get row count from local table<br>            local_count = self.duck_conn.execute(f&quot;SELECT COUNT(*) FROM {full_table_name}&quot;).fetchone()[0]<br>            <br>            if local_count &gt; 0:<br>                # Get primary keys<br>                primary_keys = [pk.upper() for pk in self.get_primary_keys(table_name)]<br>                <br>                # Get the data from local DuckDB as a DataFrame<br>                local_data = self.duck_conn.execute(f&quot;SELECT * FROM {full_table_name}&quot;).df()<br>                <br>                # If table has primary keys, use merge approach<br>                if primary_keys:<br>                    # Create temporary table in MotherDuck<br>                    temp_table = f&quot;temp_{table_name.lower()}&quot;<br>                    self.md_conn.execute(f&quot;DROP TABLE IF EXISTS {temp_table}&quot;)<br>                    <br>                    # Create temp table with same schema<br>                    self.md_conn.execute(f&quot;&quot;&quot;<br>                        CREATE TEMPORARY TABLE {temp_table} (<br>                            {&#39;, &#39;.join(column_definitions)}<br>                        )<br>                    &quot;&quot;&quot;)<br>                    <br>                    # Insert data into temp table using DataFrame<br>                    self.md_conn.execute(f&quot;INSERT INTO {temp_table} SELECT * FROM local_data&quot;)<br>                    <br>                    # Delete existing records that will be updated<br>                    pk_conditions = []<br>                    for pk in primary_keys:<br>                        pk_conditions.append(<br>                            f&quot;target.\&quot;{pk}\&quot;::VARCHAR IN (SELECT \&quot;{pk}\&quot;::VARCHAR FROM {temp_table})&quot;<br>                        )<br>                    delete_condition = &quot; AND &quot;.join(pk_conditions)<br>                    <br>                    self.md_conn.execute(f&quot;&quot;&quot;<br>                        DELETE FROM {full_table_name} target<br>                        WHERE {delete_condition}<br>                    &quot;&quot;&quot;)<br>                    <br>                    # Insert new records<br>                    self.md_conn.execute(f&quot;&quot;&quot;<br>                        INSERT INTO {full_table_name}<br>                        SELECT * FROM {temp_table}<br>                    &quot;&quot;&quot;)<br>                    <br>                    # Clean up temp table<br>                    self.md_conn.execute(f&quot;DROP TABLE IF EXISTS {temp_table}&quot;)<br>                <br>                else:<br>                    # For tables without primary keys, just append using DataFrame<br>                    self.md_conn.execute(f&quot;INSERT INTO {full_table_name} SELECT * FROM local_data&quot;)<br>            <br>            # Verify row count<br>            md_count = self.md_conn.execute(f&quot;SELECT COUNT(*) FROM {full_table_name}&quot;).fetchone()[0]<br>            <br>            print(f&quot;Successfully synced to MotherDuck {full_table_name}:&quot;)<br>            print(f&quot;- Local rows: {local_count}&quot;)<br>            print(f&quot;- MotherDuck rows: {md_count}&quot;)<br>            <br>            if local_count != md_count:<br>                print(f&quot;Warning: Row count mismatch between local ({local_count}) and MotherDuck ({md_count})&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error syncing to MotherDuck: {str(e)}&quot;)<br>            print(&quot;Full error details:&quot;)<br>            import traceback<br>            print(traceback.format_exc())<br>            raise<br><br>    def reset_motherduck_database(self):<br>        &quot;&quot;&quot;Delete and recreate the MotherDuck database&quot;&quot;&quot;<br>        try:<br>            # First connect without database to drop/create it<br>            print(&quot;\nResetting MotherDuck database...&quot;)<br>            connection_string = f&quot;md:?motherduck_token={self.motherduck_token}&quot;<br>            temp_conn = duckdb.connect(connection_string)<br>            <br>            try:<br>                # Drop database if exists<br>                temp_conn.execute(&quot;DROP DATABASE IF EXISTS ecom_db&quot;)<br>                print(&quot;Existing database dropped successfully&quot;)<br>                <br>                # Create fresh database<br>                temp_conn.execute(&quot;CREATE DATABASE ecom_db&quot;)<br>                print(&quot;New database created successfully&quot;)<br>                <br>            finally:<br>                temp_conn.close()<br>            <br>            # Connect to new database<br>            connection_string = f&quot;md:ecom_db?motherduck_token={self.motherduck_token}&quot;<br>            self.md_conn = duckdb.connect(connection_string)<br>            <br>            # Create schema<br>            self.md_conn.execute(&quot;CREATE SCHEMA IF NOT EXISTS ecom_raw&quot;)<br>            print(&quot;Schema created successfully&quot;)<br>            <br>            return True<br>            <br>        except Exception as e:<br>            print(f&quot;Error resetting MotherDuck database: {str(e)}&quot;)<br>            raise<br><br>    def reset_local_duckdb(self):<br>        &quot;&quot;&quot;Reset local DuckDB database&quot;&quot;&quot;<br>        try:<br>            print(&quot;\nResetting local DuckDB...&quot;)<br>            <br>            # Ensure existing connection is closed<br>            if hasattr(self, &#39;duck_conn&#39;):<br>                self.duck_conn.close()<br><br>            <br>            # Try to remove the file, with error handling<br>            try:<br>                if os.path.exists(&#39;ecom_db&#39;):<br>                    os.remove(&#39;ecom_db&#39;)<br>                    print(&quot;Existing local database file removed&quot;)<br>            except PermissionError:<br>                print(&quot;Could not remove ecom_db. Attempting alternative cleanup.&quot;)<br>                <br>                # Alternative approach: use duckdb to detach and remove<br>                try:<br>                    # Forcefully close any existing connections<br>                    duckdb.close_all_connections()<br>                    <br>                    # Wait a moment to ensure connections are closed<br>                    import time<br>                    time.sleep(1)<br>                    <br>                    # Try removing again<br>                    if os.path.exists(&#39;ecom_db&#39;):<br>                        os.remove(&#39;ecom_db&#39;)<br>                        print(&quot;Database file removed successfully after connection closure&quot;)<br>                except Exception as e:<br>                    print(f&quot;Failed to remove database file: {e}&quot;)<br>                    raise<br>            <br>            # Create fresh connection<br>            self.duck_conn = duckdb.connect(&#39;ecom_db&#39;)<br>            <br>            # Create schema<br>            self.duck_conn.execute(&quot;CREATE SCHEMA IF NOT EXISTS ecom_raw&quot;)<br>            print(&quot;Local database reset successfully&quot;)<br>            <br>            return True<br>            <br>        except Exception as e:<br>            print(f&quot;Error resetting local DuckDB: {str(e)}&quot;)<br>            raise<br><br>    def run_etl(self):<br>        &quot;&quot;&quot;Execute ETL process with database reset&quot;&quot;&quot;<br>        try:<br>            print(&quot;\nStarting ETL process with database reset...&quot;)<br>            <br>            # Reset both databases<br>            self.reset_local_duckdb()<br>            self.reset_motherduck_database()<br>            <br>            for table in self.postgres_tables + self.s3_tables:<br>                print(f&quot;\nProcessing {table}&quot;)<br>                <br>                try:<br>                    # Extract data<br>                    historic_df = self.extract_historic_from_s3(table)<br>                    latest_df = (self.extract_latest_from_s3(table)<br>                            if table in self.s3_tables <br>                            else self.extract_latest_from_postgres(table))<br>                    <br>                    # Transform data<br>                    historic_df = self.transform_data(historic_df, f&quot;{table}&quot;)<br>                    latest_df = self.transform_data(latest_df, f&quot;latest_{table}&quot;)<br>                    <br>                    # Combine datasets<br>                    all_columns = list(set(historic_df.columns) | set(latest_df.columns))<br>                    for col in all_columns:<br>                        if col not in historic_df.columns:<br>                            historic_df[col] = None<br>                        if col not in latest_df.columns:<br>                            latest_df[col] = None<br>                    <br>                    historic_df = historic_df[all_columns]<br>                    latest_df = latest_df[all_columns]<br>                    <br>                    combined_df = pd.concat([historic_df, latest_df], ignore_index=True)<br>                    transformed_df = self.transform_data(combined_df, table)<br>                    <br>                    # Load data<br>                    print(f&quot;\nLoading {table} to databases...&quot;)<br>                    self.load_to_duckdb(transformed_df, table)<br>                    self.sync_to_motherduck(table)<br>                    <br>                    print(f&quot;Successfully processed {table}&quot;)<br>                    <br>                except Exception as e:<br>                    print(f&quot;Error processing table {table}: {str(e)}&quot;)<br>                    continue<br>                    <br>        except Exception as e:<br>            print(f&quot;ETL process error: {str(e)}&quot;)<br>            raise<br>        finally:<br>            # Clean up connections<br>            if hasattr(self, &#39;duck_conn&#39;):<br>                self.duck_conn.close()<br>            if hasattr(self, &#39;md_conn&#39;):<br>                self.md_conn.close()<br>            print(&quot;\nETL process completed. All connections closed.&quot;)<br>            <br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        # Get MotherDuck token from environment variable<br>        token = os.getenv(&#39;MOTHERDUCK_TOKEN&#39;)<br>        etl = IncrementalETL(token)<br>        etl.run_etl()<br>    except Exception as e:<br>        print(f&quot;Main execution error: {str(e)}&quot;)<br>        raise</pre><p>2. Run</p><pre>python src/pipeline/ingest_latest_synthetic_data.py</pre><p>3. Check if the ingested_data csv files and historic-ecom/csv files have been recently updated. They are just exact copies of the initial append output data.</p><p>Example log:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*4FM8Q0s1vTWcbFQPV883aA.png" /></figure><h3>IV. Data Transformation &amp; Modeling</h3><h3>1. Setup</h3><p>Steps:</p><ol><li>Follow section IV. 1 of this <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">article</a> for the entire setup, but set the following configurations as:</li><li>dbt_project.yml:</li></ol><pre>name: &#39;ecom_data_model&#39;<br>version: &#39;1.0.0&#39;<br>profile: &#39;motherduck&#39;<br><br>model-paths: [&quot;models&quot;]<br>analysis-paths: [&quot;analyses&quot;]<br>test-paths: [&quot;tests&quot;]<br>seed-paths: [&quot;seeds&quot;]<br>macro-paths: [&quot;macros&quot;]<br>snapshot-paths: [&quot;snapshots&quot;]<br><br>clean-targets:<br>  - &quot;target&quot;<br>  - &quot;dbt_packages&quot;<br><br>models:<br>  +database: ecom_db<br>  ecom_data_model:<br>    ecom_staging:<br>      +materialized: view<br><br>    # Intermediate models<br>    ecom_intermediate:<br>      +materialized: table<br>      +tags: [&quot;intermediate&quot;]<br>    <br>    # Mart models<br>    ecom_marts:<br>      +materialized: table<br>      +tags: [&quot;marts&quot;]<br><br>vars:<br>  # Add any variables you might need<br>  &#39;dbt_date:time_zone&#39;: &#39;America/New_York&#39;<br>  schema_prefix: &#39;&#39;<br><br>seeds:<br>  ecom_data_model:<br>    +schema: ecom_raw<br><br>tests:<br>  +store_failures: true<br>  +severity: error</pre><p>profiles.yml:</p><pre>duckdb:<br>  target: dev<br>  outputs:<br>    dev_staging:<br>      type: duckdb<br>      path: ../../ecom_db<br>      schema: ecom_staging<br>      threads: 4<br>    dev_intermediate:<br>      type: duckdb<br>      path: ../../ecom_db<br>      schema: ecom_intermediate<br>      threads: 4<br>    dev_marts:<br>      type: duckdb<br>      path: ../../ecom_db<br>      schema: ecom_intermediate<br>      threads: 4<br><br>motherduck:<br>  target: prod<br>  outputs:<br>    prod_staging:<br>      type: duckdb<br>      path: &quot;md:ecom_db&quot;<br>      schema: ecom_staging<br>      threads: 4<br>      motherduck_token: &quot;{{ env_var(&#39;MOTHERDUCK_TOKEN&#39;) }}&quot;<br>      connect_args:<br>        endpoint: &quot;https://api.motherduck.com&quot;<br>    prod_intermediate:<br>      type: duckdb<br>      path: &quot;md:ecom_db&quot;<br>      schema: ecom_intermediate<br>      threads: 4<br>      motherduck_token: &quot;{{ env_var(&#39;MOTHERDUCK_TOKEN&#39;) }}&quot;<br>      connect_args:<br>        endpoint: &quot;https://api.motherduck.com&quot;<br>    prod_marts:<br>      type: duckdb<br>      path: &quot;md:ecom_db&quot;<br>      schema: ecom_marts<br>      threads: 4<br>      motherduck_token: &quot;{{ env_var(&#39;MOTHERDUCK_TOKEN&#39;) }}&quot;<br>      connect_args:<br>        endpoint: &quot;https://api.motherduck.com&quot;</pre><p>3. Run the following commands respectively:</p><pre>dbt run --profile duckdb --target dev_staging --select ecom_staging<br>dbt run --profile motherduck --target prod_staging --select ecom_staging<br><br>dbt run --profile duckdb --target dev_intermediate --select ecom_intermediate<br>dbt run --profile motherduck --target prod_intermediate --select ecom_intermediate<br><br>dbt run --profile duckdb --target dev_marts --select ecom_marts<br>dbt run --profile motherduck --target prod_marts --select ecom_mart</pre><h3>2. Testing</h3><ol><li>Test all models on DuckDB by creating the following files under src:</li><li>sample_ecom_raw_query_duckdb.py</li></ol><pre>import duckdb<br><br># Connect to the database<br>conn = duckdb.connect(&#39;ecom_db&#39;)<br><br># List schemas<br>print(&quot;Schemas:&quot;)<br>schemas = conn.execute(&quot;SELECT schema_name FROM information_schema.schemata&quot;).fetchall()<br>print(schemas)<br><br># List tables in ecom_raw schema<br>print(&quot;\nTables in ecom_raw schema:&quot;)<br>tables = conn.execute(&quot;&quot;&quot;<br>    SELECT table_name <br>    FROM information_schema.tables <br>    WHERE table_schema = &#39;ecom_raw&#39;<br>&quot;&quot;&quot;).fetchall()<br>print(tables)<br><br># Check columns in reviews table<br>print(&quot;\nColumns in reviews table:&quot;)<br>columns = conn.execute(&quot;&quot;&quot;<br>    SELECT column_name, data_type <br>    FROM information_schema.columns <br>    WHERE table_schema = &#39;ecom_raw&#39; AND table_name = &#39;reviews&#39;<br>&quot;&quot;&quot;).fetchall()<br>print(columns)<br><br># Verify table existence and row count<br>print(&quot;\nTable existence and row count:&quot;)<br>try:<br>    row_count = conn.execute(&quot;SELECT COUNT(*) FROM ecom_raw.reviews&quot;).fetchone()[0]<br>    print(f&quot;Reviews table exists. Row count: {row_count}&quot;)<br>except Exception as e:<br>    print(f&quot;Error checking reviews table: {e}&quot;)<br><br># Print first few rows if table exists<br>print(&quot;\nFirst 5 rows:&quot;)<br>try:<br>    first_rows = conn.execute(&quot;SELECT * FROM ecom_raw.reviews LIMIT 5&quot;).fetchall()<br>    print(first_rows)<br>except Exception as e:<br>    print(f&quot;Error fetching rows: {e}&quot;)</pre><p>sample_ecom_stg_query_duckdb.py</p><pre>import duckdb<br><br># Connect to the database<br>conn = duckdb.connect(&#39;ecom_db&#39;)<br><br># List schemas<br>print(&quot;Schemas:&quot;)<br>schemas = conn.execute(&quot;SELECT schema_name FROM information_schema.schemata&quot;).fetchall()<br>print(schemas)<br><br># List tables in ecom_staging schema<br>print(&quot;\nTables in ecom_staging schema:&quot;)<br>tables = conn.execute(&quot;&quot;&quot;<br>    SELECT table_name <br>    FROM information_schema.tables <br>    WHERE table_schema = &#39;ecom_staging&#39;<br>&quot;&quot;&quot;).fetchall()<br>print(tables)<br><br># Check columns in reviews table<br>print(&quot;\nColumns in reviews table:&quot;)<br>columns = conn.execute(&quot;&quot;&quot;<br>    SELECT column_name, data_type <br>    FROM information_schema.columns <br>    WHERE table_schema = &#39;ecom_staging&#39; AND table_name = &#39;stg_reviews&#39;<br>&quot;&quot;&quot;).fetchall()<br>print(columns)<br><br># Verify table existence and row count<br>print(&quot;\nTable existence and row count:&quot;)<br>try:<br>    row_count = conn.execute(&quot;SELECT COUNT(*) FROM ecom_staging.stg_reviews&quot;).fetchone()[0]<br>    print(f&quot;Reviews table exists. Row count: {row_count}&quot;)<br>except Exception as e:<br>    print(f&quot;Error checking reviews table: {e}&quot;)<br><br># Print first few rows if table exists<br>print(&quot;\nFirst 5 rows:&quot;)<br>try:<br>    first_rows = conn.execute(&quot;SELECT * FROM ecom_staging.stg_reviews LIMIT 5&quot;).fetchall()<br>    print(first_rows)<br>except Exception as e:<br>    print(f&quot;Error fetching rows: {e}&quot;)</pre><p>sample_ecom_int_query_duckdb.py</p><pre>import duckdb<br><br># Connect to the database<br>conn = duckdb.connect(&#39;ecom_db&#39;)<br><br># List schemas<br>print(&quot;Schemas:&quot;)<br>schemas = conn.execute(&quot;SELECT schema_name FROM information_schema.schemata&quot;).fetchall()<br>print(schemas)<br><br># List tables in ecom_intermediate schema<br>print(&quot;\nTables in ecom_intermediate schema:&quot;)<br>tables = conn.execute(&quot;&quot;&quot;<br>    SELECT table_name <br>    FROM information_schema.tables <br>    WHERE table_schema = &#39;ecom_intermediate&#39;<br>&quot;&quot;&quot;).fetchall()<br>print(tables)<br><br># Check columns in orders table<br>print(&quot;\nColumns in orders table:&quot;)<br>columns = conn.execute(&quot;&quot;&quot;<br>    SELECT column_name, data_type <br>    FROM information_schema.columns <br>    WHERE table_schema = &#39;ecom_intermediate&#39; AND table_name = &#39;orders&#39;<br>&quot;&quot;&quot;).fetchall()<br>print(columns)<br><br># Verify table existence and row count<br>print(&quot;\nTable existence and row count:&quot;)<br>try:<br>    row_count = conn.execute(&quot;SELECT COUNT(*) FROM ecom_intermediate.orders&quot;).fetchone()[0]<br>    print(f&quot;orders table exists. Row count: {row_count}&quot;)<br>except Exception as e:<br>    print(f&quot;Error checking orders table: {e}&quot;)<br><br># Print first few rows if table exists<br>print(&quot;\nFirst 5 rows:&quot;)<br>try:<br>    first_rows = conn.execute(&quot;SELECT * FROM ecom_intermediate.orders LIMIT 5&quot;).fetchall()<br>    print(first_rows)<br>except Exception as e:<br>    print(f&quot;Error fetching rows: {e}&quot;)</pre><p>sample_ecom_marts_query_duckdb.py</p><pre>import duckdb<br><br># Connect to the database<br>conn = duckdb.connect(&#39;ecom_db&#39;)<br><br># List schemas<br>print(&quot;Schemas:&quot;)<br>schemas = conn.execute(&quot;SELECT schema_name FROM information_schema.schemata&quot;).fetchall()<br>print(schemas)<br><br># List tables in ecom_marts schema<br>print(&quot;\nTables in ecom_marts schema:&quot;)<br>tables = conn.execute(&quot;&quot;&quot;<br>    SELECT table_name <br>    FROM information_schema.tables <br>    WHERE table_schema = &#39;ecom_marts&#39;<br>&quot;&quot;&quot;).fetchall()<br>print(tables)<br><br># Check columns in fct_customer_activity table<br>print(&quot;\nColumns in fct_customer_activity table:&quot;)<br>columns = conn.execute(&quot;&quot;&quot;<br>    SELECT column_name, data_type <br>    FROM information_schema.columns <br>    WHERE table_schema = &#39;ecom_marts&#39; AND table_name = &#39;fct_customer_activity&#39;<br>&quot;&quot;&quot;).fetchall()<br>print(columns)<br><br># Verify table existence and row count<br>print(&quot;\nTable existence and row count:&quot;)<br>try:<br>    row_count = conn.execute(&quot;SELECT COUNT(*) FROM ecom_marts.fct_customer_activity&quot;).fetchone()[0]<br>    print(f&quot;fct_customer_activity table exists. Row count: {row_count}&quot;)<br>except Exception as e:<br>    print(f&quot;Error checking fct_customer_activity table: {e}&quot;)<br><br># Print first few rows if table exists<br>print(&quot;\nFirst 5 rows:&quot;)<br>try:<br>    first_rows = conn.execute(&quot;SELECT * FROM ecom_marts.fct_customer_activity LIMIT 5&quot;).fetchall()<br>    print(first_rows)<br>except Exception as e:<br>    print(f&quot;Error fetching rows: {e}&quot;)</pre><p>2. Run all scripts to test. Sample run:</p><pre>python src/sample_ecom_raw_query_duckdb.py</pre><ol><li>Sample query output:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeK5pIV74UdXRdAmIMKC2A.png" /></figure><h3>V. Orchestration</h3><h3>1. Generation and Ingestion</h3><p>Steps:</p><ol><li>Copy the src folder under ecom_airflow &gt; dags</li><li>Remove the python files starting with 0_. These files will not be orchestrated.</li><li>Under the dags folder, create a file gen_latest_synth_dag.py</li></ol><pre>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from datetime import datetime, timedelta<br>import os<br>import sys<br>from pathlib import Path<br><br>from src.pipeline.generate_latest_synthetic_data import RecentEcommerceDataGenerator, save_data<br>from src.pipeline.ingest_latest_synthetic_data import IncrementalETL<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: datetime(2024, 12, 1),<br>    &#39;email_on_failure&#39;: True,<br>    &#39;email_on_retry&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>}<br><br>dag = DAG(<br>    &#39;generate_append_latest_pipeline&#39;,<br>    default_args=default_args,<br>    description=&#39;E-commerce data generation and ETL pipeline&#39;,<br>    schedule_interval=&#39;0 0 * * *&#39;,  # Run daily at midnight<br>    catchup=False<br>)<br><br>def generate_latest_data(**context):<br>    &quot;&quot;&quot;Generate latest synthetic e-commerce data&quot;&quot;&quot;<br>    try:<br>        generator = RecentEcommerceDataGenerator()<br>        data = generator.generate_all_data()<br>        <br>        # Save data directly to S3 and PostgreSQL<br>        save_data(data)<br>        <br>        print(&quot;Latest data generation completed successfully&quot;)<br>        return True<br>    except Exception as e:<br>        print(f&quot;Error in generate_latest_data: {str(e)}&quot;)<br>        raise<br><br>def ingest_etl(**context):<br>    &quot;&quot;&quot;Process ETL pipeline&quot;&quot;&quot;<br>    try:<br>        etl = IncrementalETL()<br>        etl.run_etl()<br>        print(&quot;ETL processing completed successfully&quot;)<br>        return True<br>    except Exception as e:<br>        print(f&quot;Error in ingest_etl: {str(e)}&quot;)<br>        raise<br><br># Define tasks<br>generate_data_task = PythonOperator(<br>    task_id=&#39;generate_latest_data&#39;,<br>    python_callable=generate_latest_data,<br>    provide_context=True,<br>    dag=dag,<br>)<br><br>ingest_etl_task = PythonOperator(<br>    task_id=&#39;ingest_etl&#39;,<br>    python_callable=ingest_etl,<br>    provide_context=True,<br>    dag=dag,<br>)<br><br># Set task dependencies<br>generate_data_task &gt;&gt; ingest_etl_task</pre><p>4. Modify the Postgres credentials on the .env file inside ecom_airflow.</p><pre>POSTGRES_HOST=db<br>POSTGRES_DB=ecom_db_source<br>POSTGRES_USER=root<br>POSTGRES_PASSWORD=root<br>POSTGRES_PORT=5432</pre><p>5. Modify the docker-compose.yml to add networks.</p><pre>services:<br>  db:<br>    container_name: postgres_container<br>    image: postgres<br>    restart: always<br>    environment:<br>      POSTGRES_USER: root<br>      POSTGRES_PASSWORD: root<br>      POSTGRES_DB: ecom_db_source<br>    ports:<br>      - &quot;5433:5432&quot;<br>    volumes:<br>      - postgres_db_source_data:/var/lib/postgresql/data<br>    networks:<br>      - ecom-airflow_20dd52_airflow<br><br>  pgadmin:<br>    container_name: pgadmin4_container<br>    image: dpage/pgadmin4<br>    restart: always<br><br>    environment:<br>      PGADMIN_DEFAULT_EMAIL: admin@admin.com<br>      PGADMIN_DEFAULT_PASSWORD: root<br>    ports:<br>      - &quot;5050:80&quot;<br>    volumes:<br>      - pgadmin_data:/var/lib/pgadmin<br>    depends_on:<br>      - db<br>    networks:<br>      - ecom-airflow_20dd52_airflow<br><br>volumes:<br>  postgres_db_source_data:<br>  pgadmin_data:<br><br>networks:<br>  ecom-airflow_20dd52_airflow:<br>    external: true</pre><p>Note: Run to determine network:</p><pre>docker network ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkMI2JD7xjX-wGfRo5tRcg.png" /></figure><p>6. Follow section V of this <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">article</a> for the entire setup. MotherDuck configuration as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W39MPky2mJF4dzG5OG27RQ.png" /></figure><p>8. Navigate back to the DAGs tab. Click on the toggle button and click on the Trigger DAG button to manually run, then click on the DAG name.</p><h3>2. Transformation</h3><p>Steps:</p><ol><li>Add the following on ecom_airflow &gt; Dockerfile</li></ol><pre>FROM quay.io/astronomer/astro-runtime:9.1.0<br><br># Install dbt and related packages<br>RUN pip install --no-cache-dir dbt-core==1.6.1 dbt-duckdb==1.6.1<br><br># Install Cosmos<br>RUN pip install &#39;astronomer-cosmos[duckdb]&#39;<br><br># Create virtual environment for dbt<br>RUN python -m venv /usr/local/airflow/dbt_venv &amp;&amp; \<br>    /usr/local/airflow/dbt_venv/bin/pip install dbt-core==1.6.1 dbt-duckdb==1.6.1<br><br># Switch to root for permission-sensitive operations<br>USER root<br><br># Make dbt executable available<br>ENV PATH=&quot;/usr/local/airflow/dbt_venv/bin:${PATH}&quot;<br>RUN ln -sf /usr/local/airflow/dbt_venv/bin/dbt /usr/local/bin/dbt<br><br># Create directory for dbt and set permissions<br>RUN mkdir -p /usr/local/airflow/dbt<br>RUN chown -R astro:astro /usr/local/airflow/dbt_venv /usr/local/airflow/dbt /usr/local/bin/dbt<br><br># Switch back to astro user<br>USER astro<br><br># Copy dbt project files<br>COPY dags/dbt/ecom_staging/ /usr/local/airflow/dbt/ecom_staging/<br>COPY dags/dbt/ecom_intermediate/ /usr/local/airflow/dbt/ecom_intermediate/<br>COPY dags/dbt/ecom_marts/ /usr/local/airflow/dbt/ecom_marts/</pre><p>2. Follow section V. 2 of this <a href="https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906">article</a> for the entire setup.</p><p>3. Create the following DAG files under ecom_airflow &gt; dags. Review the code and modify as needed:</p><ul><li>dbt_staging_dag.py</li></ul><pre>import os<br>from airflow import DAG<br>from cosmos import DbtDag, ProjectConfig, ProfileConfig<br>from datetime import datetime<br><br>ENV = os.getenv(&quot;DBT_ENV&quot;, &quot;prod&quot;)<br>target_profile = &quot;motherduck&quot;<br>target_name = &quot;prod&quot; if ENV == &quot;prod&quot; else &quot;dev&quot;<br><br># Define project directory<br>DBT_PROJECT_DIR = os.path.join(<br>    os.path.dirname(os.path.abspath(__file__)),<br>    &quot;dbt&quot;,<br>    &quot;ecom_staging&quot;<br>)<br><br>dbt_staging_dag = DbtDag(<br>    project_config=ProjectConfig(<br>        DBT_PROJECT_DIR<br>    ),<br>    profile_config=ProfileConfig(<br>        profile_name=target_profile,<br>        target_name=target_name,<br>        profiles_yml_filepath=os.path.join(DBT_PROJECT_DIR, &quot;profiles.yml&quot;)<br>    ),<br>    schedule_interval=&quot;@daily&quot;,<br>    start_date=datetime(2024, 1, 1),<br>    catchup=False,<br>    dag_id=&quot;dbt_ecom_staging_dag&quot;,<br>    operator_args={<br>        &quot;install_deps&quot;: True,<br>        &quot;models&quot;: [&quot;stg_*&quot;, &quot;fct_*&quot;, &quot;dim_*&quot;],<br>        &quot;full_refresh&quot;: True,<br>        &quot;vars&quot;: {<br>            &quot;is_test&quot;: ENV != &quot;prod&quot;,<br>            &quot;load_date&quot;: &quot;{{ ds }}&quot;<br>        }<br>    },<br>    tags=[&quot;dbt&quot;, &quot;staging&quot;, &quot;ecommerce&quot;]<br>)</pre><p>profiles.yml</p><pre>duckdb:<br>  target: dev<br>  outputs:<br>    dev:<br>      type: duckdb<br>      path: /usr/local/airflow/dbt/ecom_staging/ecom_db<br>      schema: ecom_staging<br>      threads: 4<br><br>motherduck:<br>  target: prod<br>  outputs:<br>    prod:<br>      type: duckdb<br>      path: &quot;md:ecom_db&quot;<br>      schema: ecom_staging<br>      threads: 4<br>      motherduck_token: &quot;{{ env_var(&#39;MOTHERDUCK_TOKEN&#39;) }}&quot;<br>      connect_args:<br>        endpoint: &quot;https://api.motherduck.com&quot;</pre><ul><li>dbt_intermediate_dag.py</li></ul><pre>from datetime import datetime<br>from cosmos import DbtDag, ProjectConfig, ProfileConfig, ExecutionConfig<br><br>profile_config = ProfileConfig(<br>    profile_name=&quot;motherduck&quot;,<br>    target_name=&quot;prod&quot;,<br>    profiles_yml_filepath=&quot;/usr/local/airflow/dags/dbt/ecom_intermediate/profiles.yml&quot;<br>)<br><br>execution_config = ExecutionConfig(<br>    dbt_executable_path=&quot;/usr/local/airflow/dbt_venv/bin/dbt&quot;,<br>)<br><br>intermediate_dag = DbtDag(<br>    dag_id=&quot;dbt_ecom_intermediate_dag&quot;,<br>    schedule_interval=&quot;@daily&quot;,<br>    start_date=datetime(2025, 1, 1),<br>    catchup=False,<br>    project_config=ProjectConfig(<br>        &quot;/usr/local/airflow/dags/dbt/ecom_intermediate&quot;,<br>    ),<br>    profile_config=profile_config,<br>    execution_config=execution_config,<br>    operator_args={<br>        &quot;vars&quot;: {<br>            &quot;is_test&quot;: False,<br>            &quot;load_date&quot;: &quot;{{ ds }}&quot;<br>        },<br>        &quot;full_refresh&quot;: True,<br>    },<br>    max_active_runs=1,<br>    tags=[&#39;dbt&#39;, &#39;intermediate&#39;],<br>)</pre><ul><li>profiles.yml</li></ul><pre>duckdb:<br>  target: dev<br>  outputs:<br>    dev:<br>      type: duckdb<br>      path: /usr/local/airflow/dbt/ecom_intermediate/ecom_db<br>      schema: ecom_intermediate<br>      threads: 4<br><br>motherduck:<br>  target: prod<br>  outputs:<br>    prod:<br>      type: duckdb<br>      path: md:ecom_db?motherduck_token={{ env_var(&#39;MOTHERDUCK_TOKEN&#39;) }}<br>      schema: ecom_intermediate<br>      threads: 4</pre><ul><li>dbt_marts_dag.py</li></ul><pre>from datetime import datetime<br>from cosmos import DbtDag, ProjectConfig, ProfileConfig, ExecutionConfig<br><br>profile_config = ProfileConfig(<br>    profile_name=&quot;motherduck&quot;,<br>    target_name=&quot;prod&quot;,<br>    profiles_yml_filepath=&quot;/usr/local/airflow/dags/dbt/ecom_marts/profiles.yml&quot;<br>)<br><br>execution_config = ExecutionConfig(<br>    dbt_executable_path=&quot;/usr/local/airflow/dbt_venv/bin/dbt&quot;,<br>)<br><br>marts_dag = DbtDag(<br>    dag_id=&quot;dbt_ecom_marts_dag&quot;,<br>    schedule_interval=&quot;@daily&quot;,<br>    start_date=datetime(2025, 1, 1),<br>    catchup=False,<br>    project_config=ProjectConfig(<br>        &quot;/usr/local/airflow/dags/dbt/ecom_marts&quot;,<br>    ),<br>    profile_config=profile_config,<br>    execution_config=execution_config,<br>    operator_args={<br>        &quot;vars&quot;: {<br>            &quot;is_test&quot;: False,<br>            &quot;load_date&quot;: &quot;{{ ds }}&quot;<br>        },<br>        &quot;full_refresh&quot;: True,<br>    },<br>    max_active_runs=1,<br>    tags=[&#39;dbt&#39;, &#39;marts&#39;],<br>)</pre><ul><li>profiles.yml</li></ul><pre>duckdb:<br>  target: dev<br>  outputs:<br>    dev:<br>      type: duckdb<br>      path: /usr/local/airflow/dbt/ecom_marts/ecom_db<br>      schema: ecom_marts<br>      threads: 4<br><br>motherduck:<br>  target: prod<br>  outputs:<br>    prod:<br>      type: duckdb<br>      path: md:ecom_db?motherduck_token={{ env_var(&#39;MOTHERDUCK_TOKEN&#39;) }}<br>      schema: ecom_marts<br>      threads: 4</pre><p>4. Open and refresh the Airflow UI.</p><p>5. Run the staging DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3m7e9Kv-i--8ydatw5rNqA.png" /></figure><p>6. Run the intermediate DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PXeFGleI9loRQTy5RiYnwQ.png" /></figure><p>7. Run the marts DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPZdR82EqrWlJj45cIkCxw.png" /></figure><h3>Wrapping Up</h3><p>This concludes the implementation section of the migration solution. I hope you found this article insightful and inspiring for your own projects!</p><p>If you have suggestions for improvement, ideas to enhance the solution, or creative ways to expand its functionality, feel free to contribute by creating pull requests (PRs). Collaboration and feedback are always welcome to refine and evolve this solution further.</p><figure><a href="https://buymeacoffee.com/sai_documents"><img alt="" src="https://cdn-images-1.medium.com/max/300/0*4PkMHnwi65xxhmEA.png" /></a></figure><p>Or connect with me on the following:</p><p><a href="https://www.linkedin.com/in/sandy-lauguico/">https://www.linkedin.com/in/sandy-lauguico/</a></p><p><a href="https://github.com/sclauguico">https://github.com/sclauguico</a></p><p><a href="https://www.facebook.com/sandy.c.lauguico/">https://www.facebook.com/sandy.c.lauguico/</a></p><p><a href="https://www.instagram.com/sai_documents/">https://www.instagram.com/sai_documents/</a></p><p>And please give a clap (or claps) below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41fadae1da1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECOM Phase 1: Build an End-to-End Data Engineering Pipeline for eCommerce with a Modern Data Stack]]></title>
            <link>https://medium.com/@sclauguico/build-an-end-to-end-data-engineering-pipeline-for-ecommerce-with-a-modern-data-stack-e874d89b9906?source=rss-47876a26005------2</link>
            <guid isPermaLink="false">https://medium.com/p/e874d89b9906</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[ecommerce]]></category>
            <dc:creator><![CDATA[Sandy Lauguico]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 06:09:37 GMT</pubDate>
            <atom:updated>2025-04-20T04:31:21.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zj8t8xydmzPuXadY_Wx6aw.png" /><figcaption>Project Diagram</figcaption></figure><h3>Introduction</h3><p>In today’s data-driven world, eCommerce businesses rely on accurate and timely insights to optimize operations, enhance customer experiences, and drive growth. The exponential increase in online transactions, customer interactions, and product data poses a unique challenge: how to efficiently manage, process, and analyze this vast amount of information. A robust data engineering pipeline is the foundation of any successful eCommerce analytics strategy, enabling businesses to transform raw data into actionable insights.</p><p>This article introduces a comprehensive eCommerce data engineering solution designed to address every stage of the data engineering lifecycle, leveraging the increasingly popular concept of the Modern Data Stack. From data generation and ingestion to transformation and serving, this solution integrates cutting-edge cloud technologies like <strong>AWS S3</strong>, <strong>Snowflake</strong>, <strong>Apache Airflow</strong>, and <strong>dbt</strong>. Tailored for scalability, reliability, and adaptability, it is purpose-built to meet the dynamic and evolving demands of eCommerce businesses.</p><p>The pipeline we will be building processes synthetic datasets that simulate real-world eCommerce operations, including customer profiles, product catalogs, order histories, and customer reviews. It ensures seamless integration of historical and incremental data while transforming them into a serving model which could be utilize in downstream use cases such as dashboards, predictive models, and operational systems. This will be covered in another project and article.</p><p>Whether your goal is to build personalized recommendations, optimize inventory, or generate business intelligence reports, this data engineering solution provides the tools and framework to meet the demands of a fast-paced eCommerce environment.</p><p>In the following sections, we’ll explore how the pipeline is structured, the tools it employs, and the step-by-step flow of data through its components, showcasing how this solution transforms raw eCommerce data into a competitive advantage.</p><h3>Project Vision and Scope</h3><p>The project aims to simulate a complete e-commerce data ecosystem, tackling real-world challenges like:</p><ul><li>Setting up an infrastructure from scratch</li><li>Developing ETL pipelines</li><li>Handling both structured and semi-structured data</li><li>Managing incremental data loads</li><li>Implementing proper data modeling practices</li></ul><h3>Data Flow</h3><h3>1. Data Generation</h3><p>The data flow begins with two parallel streams of synthetic data generation:</p><p><strong>Historical Synthetic Data Generation (Initial Load):</strong></p><ul><li><strong>JSON Data</strong>: Customers, products, orders, and reviews data are generated in JSON format and stored in AWS S3.</li><li><strong>Structured Data</strong>: Product categories, subcategories, order items, and interaction data are generated in a structured format and stored in <strong>Postgres</strong> (managed via pgAdmin on Docker).</li></ul><p><strong>Latest (30-day) Synthetic Data Generation (Ongoing Operations):</strong></p><ul><li><strong>JSON Data</strong>: Customers, products, orders, and reviews data are generated in JSON format and stored in AWS S3.</li><li><strong>Structured Data</strong>: Product categories, subcategories, order items, and interaction data are generated in a structured format and stored in <strong>Postgres</strong> (managed via pgAdmin on Docker).</li></ul><h3>2. Data Ingestion</h3><ul><li><strong>JSON Data from S3</strong>: Apache Airflow orchestrates the <strong>ETL (Extract, Transform, Load)</strong> process, appending new JSON records from S3 to historical data, and loading them to the historical data in S3 and Snowflake raw schema.</li><li><strong>Structured Data from Postgres</strong>: Airflow also orchestrates the <strong>ETL</strong> process, appending new structured records from Postgres to historical data, and loading to the historical data in S3 and Snowflake raw schema.</li></ul><h3>3. Data Transformation</h3><p>The ingested data is processed with dbt (data build tool) and stored in Snowflake through different layers:</p><ul><li><strong>Raw Layer</strong>: Data is first dumped in its raw form.</li><li><strong>Staging Layer</strong>: Data is casted into appropriate data types and formats.</li><li><strong>Intermediate Layer</strong>: Data is normalized to remove redundancy and ensure consistency.</li><li><strong>Marts Layer</strong>: Data is aggregated and structured into data marts for specific business use cases.</li></ul><h3>4. Orchestration</h3><ul><li>Orchestrates the latest (last 30 days) synthetic data generation and ingestion</li><li>Orchestrates the transformations across the Snowflake layers, ensuring proper lineage and documentation.</li></ul><h3>5. Data Serving (Next Project)</h3><p>The processed and aggregated data is served to different downstream systems:</p><ul><li><strong>Business Intelligence</strong>: Aggregated data marts are consumed by Power BI for reporting and dashboards.</li><li><strong>Data Science</strong>: Processed data is used in Jupyter Notebooks for machine learning, statistics, and AI operations.</li></ul><h3>I. Data Infrastructure Setup</h3><p>GitHub branch to follow: <a href="https://github.com/sclauguico/ecommerce-modern-data-stack/tree/1-infrastructure-setup">https://github.com/sclauguico/ecommerce-modern-data-stack/tree/1-infrastructure-setup</a></p><h3>1. VS Code</h3><p>Steps:</p><ol><li>Download <a href="https://code.visualstudio.com/download">VS Code</a> with the appropriate version for your operating system (Windows, macOS, or Linux).</li><li>Run the installer and follow the installation wizard.</li></ol><h3>2. Project Directory</h3><p>You may do this by creating a folder using the file explorer. If you want create a folder using the terminal, follow the steps below.</p><p>Steps:</p><ol><li>Open a terminal.</li><li>cd into the directory of choice</li><li>Create a folder:</li></ol><pre>mkdir &lt;project-name&gt;</pre><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*RjjHayUoK0dZkA9kga_w6A.png" /></figure><p>4. cd into the folder. In my case:</p><pre>cd ecommerce-modern-data-stack</pre><ol><li>Open VS Code by running</li></ol><pre>code .</pre><h3>3. Docker Desktop</h3><p>Steps:</p><ol><li>Follow the step-by-step <a href="https://docs.docker.com/desktop/setup/install/windows-install/">Docker Desktop</a> installation process.</li><li>Search on Start Menu and open the newly installed Docker Desktop.</li></ol><h3>4. WSL (For Windows users only)</h3><p>Steps:</p><ol><li>Search for Powershell in Windows on Start Menu and right click on it to select “Run as administrator”.</li><li>Run:</li></ol><pre>wsl --install</pre><p>3. Restart computer.</p><p>4. Search for the newly installed Ubuntu on Start menu.</p><p>5. Enter a desired username and password.</p><p>6. Run:</p><pre>sudo apt update &amp;&amp; sudo apt upgrade</pre><p>7. On Docker Desktop, go to Settings &gt; Resources &gt; WSL Integration.</p><p>8. Click on the toggle to enable integration with Ubuntu.</p><p>9. Click Apply &amp; Restart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8nohVhYjvGZr7moUeCR_w.png" /></figure><h3>5. Python</h3><p>Steps:</p><ol><li>Search on the start menu and open Ubuntu terminal.</li><li>Confirm that Python is installed by running the command:</li></ol><pre>python3 --version</pre><p>This will show a Python version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*Gln4_kDuhOKENJZ069IGVQ.png" /></figure><p>3. Install pip:</p><pre>sudo apt install python3-pip</pre><p>4. Confirm pip installation is successful:</p><ul><li>sudo apt install python3-pip</li></ul><pre>pip3 --version</pre><h3>6. Airflow and Astronomer</h3><p>Steps:</p><ol><li>On Ubuntu terminal, run:</li></ol><pre>pip3 install apache-airflow</pre><p>2. cd into the project directory created earlier</p><pre>cd ecommerce-modern-data-stack</pre><p>3. Create an Airflow project directory inside the project folder</p><pre>mkdir ecom_airflow</pre><p>4. cd into it</p><pre>cd ecom_airflow</pre><p>5. Run:</p><pre>nano ~/.bashrc</pre><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*Zv88RQ8Bl5YHhrKgIpWOaA.png" /></figure><p>6. Add line at the bottom export AIRFLOW_HOME=/path/to/your/directory/project-name/ecom_airflow</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiBBZYw92F7bhlFelbJIbQ.png" /></figure><p>7. Ctrl + x to exit and enter the save option</p><p>8. Initialize Astro project on your project directory by running:</p><pre>astro dev init</pre><p>Press y when prompted to initialize.</p><p>9. Go back to VS Code and open the explorer to see Astro project created.</p><p>10. Add the following on ecom_airflow/requirements.txt</p><pre># Core Airflow and Providers<br>astronomer-cosmos<br>apache-airflow-providers-snowflake<br>apache-airflow-providers-postgres<br>apache-airflow-providers-amazon<br>faker==19.3.0<br>boto3==1.35.77<br>psycopg2-binary==2.9.10<br>python-dotenv==1.0.1<br>SQLAlchemy<br>pyarrow==18.1.0<br>snowflake-connector-python==3.12.4</pre><p>11. Go back to the Ubuntu terminal. Ensure you’re in the ecom_airflow directory and run:</p><pre>astro dev start</pre><p>This will be displayed on the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*W5f-MD6wkpuh7mEjVLDHNw.png" /></figure><p>12. Open <a href="http://localhost:8080/">http://localhost:8080/</a> on your browser</p><p>13. Enter:</p><ul><li>username: admin</li><li>password: admin</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpH3pXCEeZr2sb9y40sb7g.png" /></figure><p>An example DAG from Astronomer will be loaded by default:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8LvB_UfF1Wjdv6ZGQ3qEw.png" /></figure><h3>7. Virtual Environment and Frameworks</h3><p>Steps:</p><ol><li>Open a terminal and cd into the project directory. I prefer doing this on VS Code by using the following keyboard shortcut:</li></ol><pre>Ctrl + Shift + Esc</pre><p>2. Create a virtual environment to isolate project package installation by running:</p><pre>python -m venv venv</pre><p>3. Activate venv</p><pre>venv/Scripts/activate</pre><p>4. Create a requirements.txt file inside the main project directory (not the requirements.txt in ecom_airflow), and paste:</p><pre># Database and Query Handling<br>psycopg2-binary<br>SQLAlchemy==2.0.36<br>snowflake-connector-python==3.12.4<br><br># Data Processing<br>pandas==2.1.0<br>numpy==1.24.0<br>pyarrow==18.1.0<br><br># AWS Integration<br>boto3==1.35.77<br><br># Environment Management<br>python-dotenv==1.0.1<br><br># Data Generation (for synthetic data)<br>faker==19.3.0<br><br># dbt<br>dbt-core==1.8.9<br>dbt-snowflake==1.9.0</pre><p>5. Run on the terminal:</p><pre>pip3 install -r requirements.txt</pre><p>6. Confirm packages were installed.</p><pre>pip3 list</pre><p>Note: If you’re using Git, add venv/ on your .gitignore</p><h3>8. Postgres and pgAdmin</h3><p>Steps:</p><ol><li>Create a docker-compose.yml file under the root directroy and paste:</li></ol><pre>services:<br>  db:<br>    container_name: postgres_cont<br>    image: postgres<br>    restart: always<br>    environment:<br>      POSTGRES_USER: root<br>      POSTGRES_PASSWORD: root<br>      POSTGRES_DB: ecom_db_source<br>    ports:<br>      - &quot;5433:5432&quot;<br>    volumes:<br>      - postgres_db_source_data:/var/lib/postgresql/data<br><br>  pgadmin:<br>    container_name: pgadmin4_cont<br>    image: dpage/pgadmin4<br>    restart: always<br><br>    environment:<br>      PGADMIN_DEFAULT_EMAIL: admin@admin.com<br>      PGADMIN_DEFAULT_PASSWORD: root<br>    ports:<br>      - &quot;5050:80&quot;<br>    volumes:<br>      - pgadmin_data:/var/lib/pgadmin<br>    depends_on:<br>      - db<br><br>volumes:<br>  postgres_db_source_data:<br>  pgadmin_data:</pre><p>2. On a terminal, cd into the project directory, and run:</p><pre>docker compose up</pre><p>3. On your Docker Desktop, go to Containers &gt; ecommerce-modern-data-stack &gt; pgadmin4_cont</p><p>4. Click 5050:80</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d57X0qQkuCoLe9npoJHMsQ.png" /></figure><p>Note: Another way of doing this is opening <a href="http://localhost:5050/">http://localhost:5050/</a> on your browser.</p><p>5. Enter:</p><ul><li>email: <a href="/service/mailto:admin@admin.com">admin@admin.com</a></li><li>password: root</li></ul><p>Note: Use the email and password set on the docker-compose.yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aptiuD3BOiqgmR9S9SRY-g.png" /></figure><p>6. Open a new terminal, cd into the project directory, and run:</p><pre>docker container ls</pre><p>7. Copy Postgres container ID and run:</p><pre>docker inspect &lt;container-id&gt;</pre><p>8. Copy the IPAddress. For example: 172.24.0.2</p><p>9. On pgAdmin, click Add New Server.</p><p>10. Add name. For example: ps_source_db</p><p>11. Go to connection tab and:</p><ul><li>Add the IPAdress. For example: 172.24.0.2</li><li>Set username to root.</li><li>Enter the password: root.</li><li>Click save.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*8zVN56KInqmEr6MTw45euQ.png" /></figure><p>12. Under Servers &gt; ps_source_db &gt; Databases, you’ll see ecom_db_source. Note: ecom_db_source is the database set up in the .yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUdj5YH9BcTPJCNcTd6Jfw.png" /></figure><p>13. Under the root project directory, create a .env file</p><p><strong>IMPORTANT</strong>: Don’t share this file to anyone. If you’re using Git, add .env to .gitignore.</p><p>As an example, I will be sharing this configuration and since I am running this locally:</p><pre>POSTGRES_HOST=localhost<br>POSTGRES_DB=ecom_db_source<br>POSTGRES_USER=root<br>POSTGRES_PASSWORD=root<br>POSTGRES_PORT=5433</pre><h3>9. IAM User and AWS S3 Bucket</h3><p>Steps:</p><p>I. Create an IAM User.</p><ol><li>Sign in to AWS Console (Create an AWS account).</li></ol><ul><li>Go to <a href="https://aws.amazon.com/">AWS Management Console</a>.</li><li>Sign in with your root account credentials.</li><li>In the search bar, type “IAM” and select it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*zS6gCIhjL8i271bYOR-91Q.png" /></figure><p>2. Create a New IAM User.</p><ul><li>In the IAM dashboard, click “Users” from the left sidebar.</li><li>Click “Add users” button.</li><li>Enter a username (e.g., ecommerce_admin).</li><li>Check Provide user access to the AWS Management Console — <em>optional.</em></li><li>Click “Next”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-rhKTKKQ7ujvjVt_ufUzg.png" /></figure><p>3. Set Up User Permissions.</p><ul><li>Click “Attach existing policies directly”.</li><li>Search for and select the policy:</li></ul><p>AmazonS3FullAccess (for development; use more restricted permissions in production).</p><ul><li>Click “Next”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Y0aNthXjI1ViFCD3LIawA.png" /></figure><p>4. Review and Create.</p><ul><li>Review all the settings.</li><li>Click “Create user”.</li><li>Store these securely; you won’t be able to see the secret key again.</li></ul><p><strong>IMPORTANT</strong>: Don’t share this to anyone. Download the CSV file with credentials. You will use this to sign in to AWS as the IAM user later.</p><p>5. Create New Access Keys.</p><ul><li>Go back to users.</li><li>Click the “Security credentials” tab.</li><li>Scroll to “Access keys”.</li><li>Click “Create access key”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PD80zIrZOK_oeuwrIbhZw.png" /></figure><p>6. Update .env file:</p><p><strong>IMPORTANT</strong>: Don’t share this file to anyone. If you’re using Git, add .env to .gitignore.</p><pre># AWS Configuration<br>AWS_S3_ACCESS_KEY_ID=&lt;your_new_access_key_id&gt;<br>AWS_S3_SECRET_ACCESS_KEY=&lt;your_new_secret_key&gt;</pre><p>II. Create S3 Buckets</p><ol><li>Navigate to S3.</li></ol><ul><li>In the AWS Console search bar, type “S3” and select it.</li><li>Click “Create bucket”.</li><li>Configure as needed or use the default settings.</li></ul><p>2. Create Historic and Latest Data Buckets:</p><pre>historic-ecom<br>latest-ecom</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCEcvd3qAeRdqLaZOSwvNA.png" /></figure><p>3. For the historic bucket create the folders:</p><pre>/csv <br>/json</pre><p>4. For the latest bucket, create the folder:</p><pre>/json</pre><p>5. Update the .env file with the configuration from the downloaded CSV file with credentials:</p><p><strong>IMPORTANT</strong>: Don’t share this file to anyone. If you’re using Git, add .env to .gitignore</p><pre># Retain this if your buckets have the same name<br>AWS_S3_LATEST_SYNTH=latest-ecom<br>AWS_S3_HISTORIC_SYNTH=historic-ecom</pre><h3>10. Snowflake</h3><p>Steps:</p><ol><li>Sign Up for Snowflake.</li></ol><ul><li>Visit <a href="https://signup.snowflake.com/">Snowflake’s signup page</a>.</li><li>Choose “Enterprise” edition for the 30-day free trial.</li></ul><p>2. Activate account.</p><ul><li>Check your email for activation link.</li><li>Set up your admin username and password.</li></ul><p>3. Log into Snowflake Console.</p><ul><li>Go to your Snowflake URL.</li><li>Log in with your admin credentials.</li></ul><p>4. Click Create SQL Worksheet on the upper left corner</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*YYqPNRjc6Uu_7ELiCRA5dw.png" /></figure><p>5. Setup warehouse, database, role, grants, schema.</p><p>Example:</p><pre><br>USE ROLE ACCOUNTADMIN;<br><br>-- Create Warehouse<br>CREATE WAREHOUSE ECOM_WH WITH WAREHOUSE_SIZE = &#39;X-SMALL&#39;;<br><br>-- Database structure<br>CREATE DATABASE IF NOT EXISTS ECOM_DB;<br><br>-- Create Role<br>CREATE ROLE IF NOT EXISTS ECOM_ROLE;<br>SHOW GRANTS ON WAREHOUSE ECOM_WH;<br><br>-- Schema creation<br>CREATE SCHEMA IF NOT EXISTS ECOM_DB.ECOM_RAW;<br>CREATE SCHEMA IF NOT EXISTS ECOM_DB.ECOM_STAGING;<br>CREATE SCHEMA IF NOT EXISTS ECOM_DB.ECOM_INTERMEDIATE;<br>CREATE SCHEMA IF NOT EXISTS ECOM_DB.ECOM_MARTS;<br>SHOW SCHEMAS IN DATABASE ECOM_DB;<br><br>-- Grant schema privileges to ECOM_ROLE<br>GRANT ALL PRIVILEGES ON SCHEMA ECOM_DB.ECOM_RAW TO ROLE ECOM_ROLE;<br>GRANT ALL PRIVILEGES ON SCHEMA ECOM_DB.ECOM_STAGING TO ROLE ECOM_ROLE;<br>GRANT ALL PRIVILEGES ON SCHEMA ECOM_DB.ECOM_INTERMEDIATE TO ROLE ECOM_ROLE;<br>GRANT ALL PRIVILEGES ON SCHEMA ECOM_DB.ECOM_MARTS TO ROLE ECOM_ROLE;<br><br>SHOW ROLES;<br>GRANT ROLE ECOM_ROLE TO USER your_username;<br><br>-- Switch role<br>USE ROLE ECOM_ROLE;</pre><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7VuzkjIBB8sn2ZmSwJTJA.png" /></figure><p>6. From Snowflake URL, look at your Snowflake URL to get the account ID: https://&lt;account_id&gt;.snowflakecomputing.com</p><p>7. Update .env.</p><p><strong>IMPORTANT</strong>: Don’t share this file to anyone. If you’re using Git, add .env to .gitignore</p><pre>SNOWFLAKE_USER=your_username<br>SNOWFLAKE_PASSWORD=you_password<br>SNOWFLAKE_ACCOUNT=your_snowflake_account_id<br>SNOWFLAKE_ROLE=ECOM_ROLE<br>SNOWFLAKE_WAREHOUSE=ECOM_WH<br>SNOWFLAKE_DATABASE=ECOM_DB<br>SNOWFLAKE_RAW_SCHEMA=ECOM_RAW</pre><p>Note: Sample SNOWFLAKE_ACCOUNT</p><p>abcdefg-hi12345</p><h3>11. dbt</h3><p>Steps:</p><ol><li>Under the root directory, create a dbt project folder and cd into it</li></ol><pre>mkdir ecom_dbt cd ecom_dbt</pre><p>2. Initialize dbt project</p><pre>dbt init</pre><p>3. Enter the following:</p><ul><li>Project: ecom_data_model</li><li>Select snowflake as database. In this example, the Snowflake option can be selected by pressing 1.</li><li>Enter your credentials as prompted.</li><li>role (dev role): ECOM_ROLE</li><li>warehouse (warehouse name): ECOM_WH</li><li>database (default database that dbt will build objects in): ECOM_DB</li><li>schema (default schema that dbt will build objects in): ECOM_RAW</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElyQHjOy-HWBNDbBQtCiAg.png" /></figure><p>4. Create a profiles.yml file under ecom_dbt/ecom_data_model</p><p><strong>IMPORTANT</strong>: Don’t share this file to anyone. If you’re using Git, add profiles.yml to .gitignore</p><pre>ecom_data_model:<br>  target: dev<br>  outputs:<br>    dev:<br>      type: snowflake<br>      account: your_account<br>      user: your_username<br>      password: your_password<br>      role: ECOM_ROLE<br>      database: ECOM_DB<br>      warehouse: ECOM_WH<br>      schema: ECOM_RAW<br>      threads: 10</pre><p>5. Create a packages.yml file under ecom_dbt/ecom_data_model</p><pre>packages:<br>  - package: dbt-labs/dbt_utils<br>    version: [&quot;&gt;=1.1.1&quot;, &quot;&lt;2.0.0&quot;]</pre><p>6. cd into ecom_dbt/ecom_data_model and run:</p><pre>dbt deps</pre><p>Tip: Consistently refer to the branch linked at the start of this section to follow project setup and directory.</p><h3>II. Data Generation</h3><p>GitHub branch to follow: <a href="https://github.com/sclauguico/ecommerce-modern-data-stack/tree/2-data-generation">https://github.com/sclauguico/ecommerce-modern-data-stack/tree/2-data-generation</a></p><h3>1. Historic Data Generation</h3><p>Steps:</p><ol><li>Create the following folders and files following the directory tree:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*PMeEA3zLcOPvc-8bFHCTcw.png" /></figure><p>2. Copy and paste the following script for 0_generate_historic_synthetic_data.py. Review the script and modify as needed.</p><pre>import os<br>import pandas as pd<br>import numpy as np<br>from datetime import datetime, timedelta<br>import random<br>from faker import Faker<br>import boto3<br>import psycopg2<br>from io import StringIO<br>import pandas as pd<br>import json<br>from sqlalchemy import create_engine<br>from dotenv import load_dotenv<br>from pathlib import Path<br><br>load_dotenv()<br><br>class EcommerceDataGenerator:<br>    def __init__(self, start_date=datetime(2023, 1, 1), end_date=datetime(2024, 12, 15)):<br>        self.start_date = start_date<br>        self.end_date = end_date<br>        self.fake = Faker()<br>        np.random.seed(42)<br>        random.seed(42)<br>        <br>        self.review_templates = {<br>            &#39;positive&#39;: [<br>                &quot;Great {product_type}! {positive_aspect}. Highly recommend!&quot;,<br>                &quot;Really happy with this purchase. {positive_aspect} and {another_positive}.&quot;,<br>                &quot;Excellent quality {product_type}. {positive_aspect}.&quot;,<br>                &quot;Best {product_type} I&#39;ve bought. {positive_aspect}.&quot;,<br>                &quot;{positive_aspect}. Worth every penny!&quot;<br>            ],<br>            &#39;neutral&#39;: [<br>                &quot;Decent {product_type}. {positive_aspect}, but {negative_aspect}.&quot;,<br>                &quot;Average {product_type}. {neutral_comment}.&quot;,<br>                &quot;Good enough for the price. {neutral_comment}.&quot;,<br>                &quot;{positive_aspect}, however {negative_aspect}.&quot;,<br>                &quot;Not bad, but not great. {neutral_comment}.&quot;<br>            ],<br>            &#39;negative&#39;: [<br>                &quot;Disappointed with this {product_type}. {negative_aspect}.&quot;,<br>                &quot;Not worth the price. {negative_aspect}.&quot;,<br>                &quot;Had issues with {negative_aspect}.&quot;,<br>                &quot;Wouldn&#39;t recommend. {negative_aspect}.&quot;,<br>                &quot;Poor quality {product_type}. {negative_aspect}.&quot;<br>            ]<br>        }<br>        <br>        self.positive_aspects = [<br>            &quot;Excellent build quality&quot;,<br>            &quot;Fast shipping&quot;,<br>            &quot;Great customer service&quot;,<br>            &quot;Perfect fit&quot;,<br>            &quot;Amazing features&quot;,<br>            &quot;Beautiful design&quot;,<br>            &quot;Easy to use&quot;,<br>            &quot;Incredible value&quot;,<br>            &quot;Superior performance&quot;,<br>            &quot;Long battery life&quot;<br>        ]<br>        <br>        self.negative_aspects = [<br>            &quot;Poor build quality&quot;,<br>            &quot;Slow delivery&quot;,<br>            &quot;Unresponsive customer service&quot;,<br>            &quot;Doesn&#39;t fit well&quot;,<br>            &quot;Missing features&quot;,<br>            &quot;Unappealing design&quot;,<br>            &quot;Complicated to use&quot;,<br>            &quot;Overpriced&quot;,<br>            &quot;Underperforms&quot;,<br>            &quot;Short battery life&quot;<br>        ]<br>        <br>        self.neutral_comments = [<br>            &quot;Meets basic expectations&quot;,<br>            &quot;Standard quality&quot;,<br>            &quot;Average performance&quot;,<br>            &quot;Fair for the price&quot;,<br>            &quot;Could be better&quot;<br>        ]<br><br>    def generate_product_categories(self):<br>        &quot;&quot;&quot;Generate product categories and subcategories&quot;&quot;&quot;<br>        categories = {<br>            &#39;Electronics&#39;: [&#39;Smartphones&#39;, &#39;Laptops&#39;, &#39;Accessories&#39;, &#39;Tablets&#39;, &#39;Wearables&#39;],<br>            &#39;Fashion&#39;: [&#39;Men\&#39;s Clothing&#39;, &#39;Women\&#39;s Clothing&#39;, &#39;Children\&#39;s Clothing&#39;, &#39;Shoes&#39;, &#39;Accessories&#39;],<br>            &#39;Home &amp; Living&#39;: [&#39;Furniture&#39;, &#39;Kitchen&#39;, &#39;Decor&#39;, &#39;Bedding&#39;, &#39;Storage&#39;],<br>            &#39;Beauty&#39;: [&#39;Skincare&#39;, &#39;Makeup&#39;, &#39;Haircare&#39;, &#39;Fragrances&#39;, &#39;Tools&#39;],<br>            &#39;Sports&#39;: [&#39;Exercise Equipment&#39;, &#39;Sportswear&#39;, &#39;Outdoor Gear&#39;, &#39;Accessories&#39;, &#39;Footwear&#39;]<br>        }<br>        <br>        category_data = []<br>        subcategory_data = []<br>        <br>        for cat_id, (category, subcategories) in enumerate(categories.items(), 1):<br>            category_data.append({<br>                &#39;category_id&#39;: cat_id,<br>                &#39;category_name&#39;: category,<br>                &#39;created_at&#39;: self.start_date<br>            })<br>            <br>            for sub_id, subcategory in enumerate(subcategories, 1):<br>                subcategory_data.append({<br>                    &#39;subcategory_id&#39;: (cat_id * 100) + sub_id,<br>                    &#39;category_id&#39;: cat_id,<br>                    &#39;subcategory_name&#39;: subcategory,<br>                    &#39;created_at&#39;: self.start_date<br>                })<br>        <br>        return pd.DataFrame(category_data), pd.DataFrame(subcategory_data)<br><br>    def generate_products(self, n_products=1000):<br>        &quot;&quot;&quot;Generate product catalog&quot;&quot;&quot;<br>        categories_df, subcategories_df = self.generate_product_categories()<br>        <br>        products = []<br>        for product_id in range(1, n_products + 1):<br>            category_id = random.randint(1, len(categories_df))<br>            valid_subcats = subcategories_df[subcategories_df[&#39;category_id&#39;] == category_id]<br>            subcategory_id = random.choice(valid_subcats[&#39;subcategory_id&#39;].values)<br>            <br>            base_price = random.uniform(10, 1000)<br>            <br>            products.append({<br>                &#39;product_id&#39;: product_id,<br>                &#39;category_id&#39;: category_id,<br>                &#39;subcategory_id&#39;: subcategory_id,<br>                &#39;product_name&#39;: f&quot;{self.fake.company()} {self.fake.word().title()}&quot;,<br>                &#39;description&#39;: self.fake.text(max_nb_chars=200),<br>                &#39;base_price&#39;: round(base_price, 2),<br>                &#39;sale_price&#39;: round(base_price * random.uniform(0.8, 1.0), 2),<br>                &#39;stock_quantity&#39;: random.randint(0, 1000),<br>                &#39;weight_kg&#39;: round(random.uniform(0.1, 20.0), 2),<br>                &#39;is_active&#39;: random.random() &gt; 0.1,<br>                &#39;created_at&#39;: self.start_date + timedelta(days=random.randint(0, 30)),<br>                &#39;brand&#39;: self.fake.company(),<br>                &#39;sku&#39;: f&quot;SKU-{random.randint(10000, 99999)}&quot;,<br>                &#39;rating&#39;: round(random.uniform(3.0, 5.0), 1),<br>                &#39;review_count&#39;: random.randint(0, 1000)<br>            })<br>        <br>        return pd.DataFrame(products), categories_df, subcategories_df<br><br>    def generate_customers(self, n_customers=1000):<br>        &quot;&quot;&quot;Generate customer data&quot;&quot;&quot;<br>        customers = []<br>        for customer_id in range(1, n_customers + 1):<br>            age = np.random.normal(45, 15)<br>            age = max(18, min(90, int(age)))<br>            signup_date = self.start_date + timedelta(days=random.randint(0, (self.end_date - self.start_date).days))<br>            <br>            customers.append({<br>                &#39;customer_id&#39;: customer_id,<br>                &#39;email&#39;: self.fake.email(),<br>                &#39;first_name&#39;: self.fake.first_name(),<br>                &#39;last_name&#39;: self.fake.last_name(),<br>                &#39;age&#39;: age,<br>                &#39;gender&#39;: random.choice([&#39;M&#39;, &#39;F&#39;, &#39;Other&#39;]),<br>                &#39;annual_income&#39;: max(15000, int(np.random.normal(65000, 30000))),<br>                &#39;marital_status&#39;: random.choice([&#39;Single&#39;, &#39;Married&#39;, &#39;Divorced&#39;, &#39;Widowed&#39;]),<br>                &#39;education&#39;: random.choice([&#39;High School&#39;, &#39;Some College&#39;, &#39;Bachelor&#39;, &#39;Master&#39;, &#39;PhD&#39;]),<br>                &#39;location_type&#39;: random.choice([&#39;Urban&#39;, &#39;Suburban&#39;, &#39;Rural&#39;]),<br>                &#39;city&#39;: self.fake.city(),<br>                &#39;state&#39;: self.fake.state(),<br>                &#39;country&#39;: &#39;USA&#39;,<br>                &#39;signup_date&#39;: signup_date,<br>                &#39;last_login&#39;: signup_date + timedelta(days=random.randint(0, 30)),<br>                &#39;preferred_channel&#39;: random.choice([&#39;Web&#39;, &#39;Mobile App&#39;, &#39;Email&#39;]),<br>                &#39;is_active&#39;: random.random() &gt; 0.1<br>            })<br>        <br>        return pd.DataFrame(customers)<br><br>    def generate_orders(self, customers_df, products_df):<br>        &quot;&quot;&quot;Generate order data&quot;&quot;&quot;<br>        orders = []<br>        order_items = []<br>        order_id = 1<br>        <br>        for _, customer in customers_df.iterrows():<br>            # Number of orders influenced by customer demographics<br>            income_factor = min(2.0, max(0.5, customer[&#39;annual_income&#39;] / 65000))<br>            num_orders = np.random.poisson(5 * income_factor)<br>            <br>            for _ in range(num_orders):<br>                # Ensure order_date is within the date range<br>                max_days = (self.end_date - customer[&#39;signup_date&#39;]).days<br>                if max_days &lt;= 0:<br>                    order_date = customer[&#39;signup_date&#39;]<br>                else:<br>                    order_date = customer[&#39;signup_date&#39;] + timedelta(days=random.randint(0, max_days))<br>                <br>                # Order status flow<br>                if order_date + timedelta(days=7) &gt; self.end_date:<br>                    status = random.choice([&#39;Pending&#39;, &#39;Processing&#39;, &#39;Shipped&#39;])<br>                else:<br>                    status = &#39;Delivered&#39;<br>                <br>                shipping_cost = round(random.uniform(5, 20), 2)<br>                <br>                # Generate order items<br>                num_items = np.random.poisson(2) + 1<br>                order_products = products_df.sample(n=min(num_items, len(products_df)), replace=True)<br>                <br>                total_amount = shipping_cost<br>                for _, product in order_products.iterrows():<br>                    quantity = random.randint(1, 3)<br>                    price = product[&#39;sale_price&#39;]<br>                    item_total = quantity * price<br>                    total_amount += item_total<br>                    <br>                    order_items.append({<br>                        &#39;order_item_id&#39;: len(order_items) + 1,<br>                        &#39;order_id&#39;: order_id,<br>                        &#39;product_id&#39;: product[&#39;product_id&#39;],<br>                        &#39;quantity&#39;: quantity,<br>                        &#39;unit_price&#39;: price,<br>                        &#39;total_price&#39;: item_total,<br>                        &#39;created_at&#39;: order_date<br>                    })<br>                <br>                orders.append({<br>                    &#39;order_id&#39;: order_id,<br>                    &#39;customer_id&#39;: customer[&#39;customer_id&#39;],<br>                    &#39;order_date&#39;: order_date,<br>                    &#39;status&#39;: status,<br>                    &#39;total_amount&#39;: round(total_amount, 2),<br>                    &#39;shipping_cost&#39;: shipping_cost,<br>                    &#39;payment_method&#39;: random.choice([&#39;Credit Card&#39;, &#39;PayPal&#39;, &#39;Debit Card&#39;]),<br>                    &#39;shipping_address&#39;: self.fake.street_address(),<br>                    &#39;billing_address&#39;: self.fake.street_address(),<br>                    &#39;created_at&#39;: order_date,<br>                    &#39;updated_at&#39;: order_date + timedelta(days=random.randint(0, 5))<br>                })<br>                <br>                order_id += 1<br>        <br>        return pd.DataFrame(orders), pd.DataFrame(order_items)<br><br>    def generate_customer_interactions(self, customers_df, products_df):<br>        &quot;&quot;&quot;Generate customer interaction events&quot;&quot;&quot;<br>        events = []<br>        <br>        for _, customer in customers_df.iterrows():<br>            num_interactions = np.random.poisson(20)<br>            <br>            for _ in range(num_interactions):<br>                # Ensure event_date is within the date range<br>                max_days = (self.end_date - customer[&#39;signup_date&#39;]).days<br>                if max_days &lt;= 0:<br>                    event_date = customer[&#39;signup_date&#39;]<br>                else:<br>                    event_date = customer[&#39;signup_date&#39;] + timedelta(days=random.randint(0, max_days))<br>                <br>                product = products_df.sample(n=1).iloc[0]<br>                <br>                event_type = random.choice([&#39;view&#39;, &#39;cart_add&#39;, &#39;cart_remove&#39;, &#39;wishlist_add&#39;, &#39;search&#39;, &#39;purchase&#39;])<br>                <br>                events.append({<br>                    &#39;event_id&#39;: len(events) + 1,<br>                    &#39;customer_id&#39;: customer[&#39;customer_id&#39;],<br>                    &#39;product_id&#39;: product[&#39;product_id&#39;],<br>                    &#39;event_type&#39;: event_type,<br>                    &#39;event_date&#39;: event_date,<br>                    &#39;device_type&#39;: random.choice([&#39;desktop&#39;, &#39;mobile&#39;, &#39;tablet&#39;]),<br>                    &#39;session_id&#39;: f&quot;session_{random.randint(10000, 99999)}&quot;,<br>                    &#39;created_at&#39;: event_date<br>                })<br>        <br>        return pd.DataFrame(events)<br><br>    def generate_review_text(self, rating, product_type):<br>        &quot;&quot;&quot;Generate realistic review text based on rating&quot;&quot;&quot;<br>        if rating &gt;= 4:<br>            template = random.choice(self.review_templates[&#39;positive&#39;])<br>            aspect = random.choice(self.positive_aspects)<br>            another = random.choice(self.positive_aspects)<br>            return template.format(<br>                product_type=product_type,<br>                positive_aspect=aspect,<br>                another_positive=another<br>            )<br>        elif rating &gt;= 3:<br>            template = random.choice(self.review_templates[&#39;neutral&#39;])<br>            return template.format(<br>                product_type=product_type,<br>                positive_aspect=random.choice(self.positive_aspects),<br>                negative_aspect=random.choice(self.negative_aspects),<br>                neutral_comment=random.choice(self.neutral_comments)<br>            )<br>        else:<br>            template = random.choice(self.review_templates[&#39;negative&#39;])<br>            return template.format(<br>                product_type=product_type,<br>                negative_aspect=random.choice(self.negative_aspects)<br>            )<br><br>    def generate_reviews(self, orders_df, order_items_df, products_df, customers_df):<br>        &quot;&quot;&quot;<br>        Generate synthetic reviews for products based on order and customer data.<br>        <br>        Parameters:<br>            orders_df (DataFrame): DataFrame containing order details.<br>            order_items_df (DataFrame): DataFrame containing order items.<br>            products_df (DataFrame): DataFrame containing product details.<br>            customers_df (DataFrame): DataFrame containing customer details.<br><br>        Returns:<br>            reviews_df (DataFrame): DataFrame containing generated reviews.<br>            updated_products_df (DataFrame): DataFrame with updated product review counts.<br>        &quot;&quot;&quot;<br>        # Ensure &#39;review_count&#39; exists in products_df<br>        if &#39;review_count&#39; not in products_df.columns:<br>            products_df[&#39;review_count&#39;] = 0<br>            print(&quot;Added &#39;review_count&#39; column to products_df with default value 0.&quot;)<br><br>        # Ensure &#39;review_count&#39; column is properly filled and cast to int<br>        products_df[&#39;review_count&#39;] = products_df[&#39;review_count&#39;].fillna(0).astype(int)<br><br>        # Logic to generate synthetic reviews<br>        reviews_data = []<br>        for _, row in orders_df.iterrows():<br>            order_id = row[&#39;order_id&#39;]<br>            customer_id = row[&#39;customer_id&#39;]<br>            # Get items for this order<br>            order_items = order_items_df[order_items_df[&#39;order_id&#39;] == order_id]<br><br>            for _, item in order_items.iterrows():<br>                product_id = item[&#39;product_id&#39;]<br>                # Create synthetic review (e.g., random score and text)<br>                review_score = np.random.randint(1, 6)  # Random score between 1 and 5<br>                review_text = f&quot;Review for product {product_id}&quot;  # Placeholder text<br><br>                reviews_data.append({<br>                    &#39;product_id&#39;: product_id,<br>                    &#39;order_id&#39;: order_id,<br>                    &#39;customer_id&#39;: customer_id,<br>                    &#39;review_score&#39;: review_score,<br>                    &#39;review_text&#39;: review_text<br>                })<br><br>                # Increment review count for the product<br>                products_df.loc[products_df[&#39;product_id&#39;] == product_id, &#39;review_count&#39;] += 1<br><br>        # Create DataFrame for reviews<br>        reviews_df = pd.DataFrame(reviews_data)<br><br>        # Return reviews and updated products DataFrame<br>        return reviews_df, products_df<br><br>    def format_datetime(self, dt):<br>        &quot;&quot;&quot;Format datetime objects for JSON serialization&quot;&quot;&quot;<br>        return dt.isoformat() if isinstance(dt, datetime) else dt<br><br>    def df_to_json_records(self, df):<br>        &quot;&quot;&quot;Convert DataFrame to JSON-serializable records with datetime handling&quot;&quot;&quot;<br>        return json.loads(df.to_json(orient=&#39;records&#39;, date_format=&#39;iso&#39;))<br><br>    def generate_all_data(self, n_customers=1000, n_products=1000):<br>        &quot;&quot;&quot;Generate all e-commerce data with specified output formats&quot;&quot;&quot;<br>        # Define output format for each table<br>        output_formats = {<br>            &#39;customers&#39;: &#39;json&#39;,  # Complex nested data, good for JSON<br>            &#39;products&#39;: &#39;json&#39;,   # Product details often needed in API format<br>            &#39;orders&#39;: &#39;json&#39;,     # Order details benefit from JSON structure<br>            &#39;reviews&#39;: &#39;json&#39;,    # Review text better handled in JSON<br>            &#39;categories&#39;: &#39;csv&#39;,  # Simple structural data good for CSV<br>            &#39;subcategories&#39;: &#39;csv&#39;,<br>            &#39;order_items&#39;: &#39;csv&#39;, # Transactional data good for CSV<br>            &#39;interactions&#39;: &#39;csv&#39; # High-volume data better in CSV<br>        }<br>        <br>        print(&quot;Generating products...&quot;)<br>        products_df, categories_df, subcategories_df = self.generate_products(n_products)<br>        <br>        print(&quot;Generating customers...&quot;)<br>        customers_df = self.generate_customers(n_customers)<br>        <br>        print(&quot;Generating orders...&quot;)<br>        orders_df, order_items_df = self.generate_orders(customers_df, products_df)<br>        <br>        print(&quot;Generating reviews...&quot;)<br>        reviews_df, updated_products_df = self.generate_reviews(orders_df, order_items_df, products_df, customers_df)<br>        <br>        print(&quot;Generating customer interactions...&quot;)<br>        interactions_df = self.generate_customer_interactions(customers_df, updated_products_df)<br>        <br>        # Prepare data dictionary<br>        data_dict = {<br>            &#39;customers&#39;: customers_df,<br>            &#39;products&#39;: updated_products_df,<br>            &#39;categories&#39;: categories_df,<br>            &#39;subcategories&#39;: subcategories_df,<br>            &#39;orders&#39;: orders_df,<br>            &#39;order_items&#39;: order_items_df,<br>            &#39;reviews&#39;: reviews_df,<br>            &#39;interactions&#39;: interactions_df<br>        }<br>        <br>        # # Save data in appropriate formats<br>        # print(&quot;Saving data in specified formats...&quot;)<br>        # self.save_data(data_dict, output_formats)<br>        <br>        return data_dict<br>    <br>class EcommerceDataLoader:<br>    def __init__(self, aws_access_key_id, aws_secret_access_key, bucket_name, <br>                 pg_host, pg_port, pg_user, <br>                 pg_password, pg_database):<br>        &quot;&quot;&quot;Initialize connections to S3 and PostgreSQL&quot;&quot;&quot;<br>        # Validate required parameters<br>        if not all([aws_access_key_id, aws_secret_access_key, bucket_name]):<br>            raise ValueError(&quot;AWS credentials and bucket name are required&quot;)<br><br>        # S3 client setup<br>        self.s3_client = boto3.client(<br>            &#39;s3&#39;,<br>            aws_access_key_id=aws_access_key_id,<br>            aws_secret_access_key=aws_secret_access_key<br>        )<br>        self.bucket_name = bucket_name<br><br>        # PostgreSQL connection setup<br>        self.pg_conn_string = f&quot;postgresql://{pg_user}:{pg_password}@{pg_host}:{pg_port}/{pg_database}&quot;<br>        self.engine = create_engine(self.pg_conn_string)<br><br>    def upload_json_to_s3(self, data_df, table_name):<br>        &quot;&quot;&quot;Upload JSON data directly to S3&quot;&quot;&quot;<br>        if not isinstance(data_df, pd.DataFrame):<br>            raise ValueError(&quot;data_df must be a pandas DataFrame&quot;)<br><br>        try:<br>            # Convert DataFrame to JSON format with metadata<br>            json_data = {<br>                &quot;metadata&quot;: {<br>                    &quot;table&quot;: table_name,<br>                    &quot;recordCount&quot;: len(data_df),<br>                    &quot;generatedAt&quot;: pd.Timestamp.now().isoformat(),<br>                    &quot;version&quot;: &quot;1.0&quot;<br>                },<br>                &quot;data&quot;: json.loads(data_df.to_json(orient=&#39;records&#39;, date_format=&#39;iso&#39;))<br>            }<br>            <br>            # Convert to JSON string<br>            json_str = json.dumps(json_data)<br>            <br>            # Upload to S3<br>            s3_key = f&#39;json/{table_name}.json&#39;<br>            self.s3_client.put_object(<br>                Bucket=self.bucket_name,<br>                Key=s3_key,<br>                Body=json_str,<br>                ContentType=&#39;application/json&#39;<br>            )<br>            print(f&quot;Successfully uploaded {table_name} to S3: s3://{self.bucket_name}/{s3_key}&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error uploading {table_name} to S3: {str(e)}&quot;)<br>            raise<br><br>    def load_csv_to_postgres(self, df, table_name):<br>        &quot;&quot;&quot;Load DataFrame directly to PostgreSQL&quot;&quot;&quot;<br>        if not isinstance(df, pd.DataFrame):<br>            raise ValueError(&quot;df must be a pandas DataFrame&quot;)<br><br>        try:<br>            # Create copy buffer<br>            output = StringIO()<br>            df.to_csv(output, index=False, header=True)<br>            output.seek(0)<br>            <br>            # Create database connection<br>            with self.engine.connect() as connection:<br>                # Create table if it doesn&#39;t exist<br>                df.head(0).to_sql(table_name, connection, if_exists=&#39;replace&#39;, index=False)<br>                <br>                # Copy data<br>                raw_conn = connection.connection<br>                with raw_conn.cursor() as cursor:<br>                    cursor.copy_expert(<br>                        f&quot;COPY {table_name} FROM STDIN WITH CSV HEADER&quot;,<br>                        output<br>                    )<br>                raw_conn.commit()<br>                <br>            print(f&quot;Successfully loaded {len(df)} rows to PostgreSQL table: {table_name}&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error loading {table_name} to PostgreSQL: {str(e)}&quot;)<br>            raise<br><br>def save_data(data_dict):<br>    &quot;&quot;&quot;Save data to S3 and PostgreSQL&quot;&quot;&quot;<br>    # Get AWS credentials from environment variables<br>    aws_access_key_id = os.environ.get(&quot;AWS_S3_ACCESS_KEY_ID&quot;)<br>    aws_secret_access_key = os.environ.get(&quot;AWS_S3_SECRET_ACCESS_KEY&quot;)<br>    bucket_name = os.environ.get(&quot;AWS_S3_HISTORIC_SYNTH&quot;)<br><br>    # Validate AWS credentials<br>    if not all([aws_access_key_id, aws_secret_access_key, bucket_name]):<br>        raise ValueError(&quot;Required AWS environment variables are not set&quot;)<br><br>    # PostgreSQL connection details<br>    pg_config = {<br>        &#39;pg_host&#39;: os.environ.get(&quot;POSTGRES_HOST&quot;),<br>        &#39;pg_port&#39;: int(os.environ.get(&quot;POSTGRES_PORT&quot;)),<br>        &#39;pg_user&#39;: os.environ.get(&quot;POSTGRES_USER&quot;),<br>        &#39;pg_password&#39;: os.environ.get(&quot;POSTGRES_PASSWORD&quot;),<br>        &#39;pg_database&#39;: os.environ.get(&quot;POSTGRES_DB&quot;)<br>    }<br>    # Initialize loader<br>    loader = EcommerceDataLoader(<br>        aws_access_key_id=aws_access_key_id,<br>        aws_secret_access_key=aws_secret_access_key,<br>        bucket_name=bucket_name,<br>        **pg_config<br>    )<br><br>    # Define which tables go to which destination<br>    json_tables = [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;]<br>    csv_tables = [&#39;categories&#39;, &#39;subcategories&#39;, &#39;order_items&#39;, &#39;interactions&#39;]<br><br>    # Validate data_dict<br>    if not isinstance(data_dict, dict):<br>        raise ValueError(&quot;data_dict must be a dictionary containing DataFrames&quot;)<br><br>    # Upload JSON files to S3<br>    for table_name in json_tables:<br>        if table_name in data_dict:<br>            loader.upload_json_to_s3(data_dict[table_name], table_name)<br><br>    # Load CSV files to PostgreSQL<br>    for table_name in csv_tables:<br>        if table_name in data_dict:<br>            loader.load_csv_to_postgres(data_dict[table_name], table_name)<br><br>    output_dir = Path(&#39;generated_historic_data&#39;)<br>    output_dir.mkdir(parents=True, exist_ok=True)<br>    <br>    for table_name, df in data_dict.items():<br>        csv_path = output_dir / f&quot;{table_name}.csv&quot;<br>        df.to_csv(csv_path, index=False)<br>        print(f&quot;Saved {table_name} to {csv_path}&quot;)<br>        <br>    output_dir.mkdir(parents=True, exist_ok=True)<br>    for table_name, df in data_dict.items():<br>        csv_path = os.path.join(output_dir, f&quot;{table_name}.csv&quot;)<br>        df.to_csv(csv_path, index=False)<br>        print(f&quot;Saved {table_name} to {csv_path}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        generator = EcommerceDataGenerator()<br>        data = generator.generate_all_data()<br>        <br>        # Save data directly to S3 and PostgreSQL<br>        save_data(data)        <br>        # Print sample data and format information<br>        print(&quot;\nData Generation Summary:&quot;)<br>        for table_name, df in data.items():<br>            print(f&quot;\n{table_name.upper()} Table:&quot;)<br>            print(f&quot;Total records: {len(df)}&quot;)<br>            print(f&quot;Output format: {&#39;JSON&#39; if table_name in [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;] else &#39;CSV&#39;}&quot;)<br>            print(&quot;\nSample data:&quot;)<br>            print(df.head())<br>            <br>    except Exception as e:<br>        print(f&quot;Error in main execution: {str(e)}&quot;)<br>        raise</pre><p>3. Under the root directory, run:</p><pre>python src/pipeline/0_generate_historic_synthetic_data.py</pre><p>Note: Ensure Docker containers are running</p><p>4. Initially check the generated_historc_data folder for the csv versions of the data. Review the data generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SnZFTTt_lwRb6qFr9GQNeQ.png" /></figure><p>5. Check the historic-ecom S3 bucket json folder for the generated data (customers, orders, products, reviews).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fi60OesFONcja1oE-nF28g.png" /></figure><p>6. Check the historic data (categories, interactions, order_items, subcategories) on pgAdmin by going to the Query Tool and running SQL queries as sampled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwGGrDxBsTkTe53A4h1vUA.png" /></figure><p>7. You can also verify the Postgres data using psql. Run the command on a terminal:</p><pre>docker exec -it postgres_cont psql -U root -d ecom_db_source<br><br>SELECT * FROM &lt;table_name&gt;;</pre><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nwkee1sIiFpiXzOwN9N1CA.png" /></figure><p>Note: Enter \q to exit psql</p><h3>2. Latest Data Generation</h3><p>Steps:</p><ol><li>Copy and paste the following script for generate_latest_synthetic_data.py. Review the script and modify as needed.</li></ol><pre>import os<br>import pandas as pd<br>import numpy as np<br>from datetime import datetime, timedelta<br>import random<br>from faker import Faker<br>import boto3<br>import psycopg2<br>from io import StringIO<br>import pandas as pd<br>import json<br>from sqlalchemy import create_engine<br>from dotenv import load_dotenv<br>from pathlib import Path<br><br>load_dotenv()<br><br>class RecentEcommerceDataGenerator:<br>    def __init__(self, id_offset=1000000):  # Add a large offset to some IDs<br>        # Set end date to today and start date to 30 days ago<br>        self.end_date = datetime.now()<br>        self.start_date = self.end_date - timedelta(days=30)<br>        self.fake = Faker()<br>        self.id_offset = id_offset  # Store the offset<br>        np.random.seed(42)<br>        random.seed(42)<br>        <br>        # Keep existing templates and aspects from the original code<br>        self.review_templates = {<br>            &#39;positive&#39;: [<br>                &quot;Great {product_type}! {positive_aspect}. Highly recommend!&quot;,<br>                &quot;Really happy with this purchase. {positive_aspect} and {another_positive}.&quot;,<br>                &quot;Excellent quality {product_type}. {positive_aspect}.&quot;,<br>                &quot;Best {product_type} I&#39;ve bought. {positive_aspect}.&quot;,<br>                &quot;{positive_aspect}. Worth every penny!&quot;<br>            ],<br>            &#39;neutral&#39;: [<br>                &quot;Decent {product_type}. {positive_aspect}, but {negative_aspect}.&quot;,<br>                &quot;Average {product_type}. {neutral_comment}.&quot;,<br>                &quot;Good enough for the price. {neutral_comment}.&quot;,<br>                &quot;{positive_aspect}, however {negative_aspect}.&quot;,<br>                &quot;Not bad, but not great. {neutral_comment}.&quot;<br>            ],<br>            &#39;negative&#39;: [<br>                &quot;Disappointed with this {product_type}. {negative_aspect}.&quot;,<br>                &quot;Not worth the price. {negative_aspect}.&quot;,<br>                &quot;Had issues with {negative_aspect}.&quot;,<br>                &quot;Wouldn&#39;t recommend. {negative_aspect}.&quot;,<br>                &quot;Poor quality {product_type}. {negative_aspect}.&quot;<br>            ]<br>        }<br>    <br>        self.positive_aspects = [<br>            &quot;Excellent build quality&quot;,<br>            &quot;Fast shipping&quot;,<br>            &quot;Great customer service&quot;,<br>            &quot;Perfect fit&quot;,<br>            &quot;Amazing features&quot;,<br>            &quot;Beautiful design&quot;,<br>            &quot;Easy to use&quot;,<br>            &quot;Incredible value&quot;,<br>            &quot;Superior performance&quot;,<br>            &quot;Long battery life&quot;<br>        ]<br>        <br>        self.negative_aspects = [<br>            &quot;Poor build quality&quot;,<br>            &quot;Slow delivery&quot;,<br>            &quot;Unresponsive customer service&quot;,<br>            &quot;Doesn&#39;t fit well&quot;,<br>            &quot;Missing features&quot;,<br>            &quot;Unappealing design&quot;,<br>            &quot;Complicated to use&quot;,<br>            &quot;Overpriced&quot;,<br>            &quot;Underperforms&quot;,<br>            &quot;Short battery life&quot;<br>        ]<br>        <br>        self.neutral_comments = [<br>            &quot;Meets basic expectations&quot;,<br>            &quot;Standard quality&quot;,<br>            &quot;Average performance&quot;,<br>            &quot;Fair for the price&quot;,<br>            &quot;Could be better&quot;<br>        ]<br><br>    def generate_product_categories(self):<br>        &quot;&quot;&quot;Generate product categories and subcategories&quot;&quot;&quot;<br>        categories = {<br>            &#39;Electronics&#39;: [&#39;Smartphones&#39;, &#39;Laptops&#39;, &#39;Accessories&#39;, &#39;Tablets&#39;, &#39;Wearables&#39;],<br>            &#39;Fashion&#39;: [&#39;Men\&#39;s Clothing&#39;, &#39;Women\&#39;s Clothing&#39;, &#39;Children\&#39;s Clothing&#39;, &#39;Shoes&#39;, &#39;Accessories&#39;],<br>            &#39;Home &amp; Living&#39;: [&#39;Furniture&#39;, &#39;Kitchen&#39;, &#39;Decor&#39;, &#39;Bedding&#39;, &#39;Storage&#39;],<br>            &#39;Beauty&#39;: [&#39;Skincare&#39;, &#39;Makeup&#39;, &#39;Haircare&#39;, &#39;Fragrances&#39;, &#39;Tools&#39;],<br>            &#39;Sports&#39;: [&#39;Exercise Equipment&#39;, &#39;Sportswear&#39;, &#39;Outdoor Gear&#39;, &#39;Accessories&#39;, &#39;Footwear&#39;]<br>        }<br>        <br>        category_data = []<br>        subcategory_data = []<br>        <br>        for cat_id, (category, subcategories) in enumerate(categories.items(), 1):<br>            category_data.append({<br>                &#39;category_id&#39;: cat_id,<br>                &#39;category_name&#39;: category,<br>                &#39;created_at&#39;: self.start_date<br>            })<br>            <br>            for sub_id, subcategory in enumerate(subcategories, 1):<br>                subcategory_data.append({<br>                    &#39;subcategory_id&#39;: (cat_id * 100) + sub_id,<br>                    &#39;category_id&#39;: cat_id,<br>                    &#39;subcategory_name&#39;: subcategory,<br>                    &#39;created_at&#39;: self.start_date<br>                })<br>        <br>        return pd.DataFrame(category_data), pd.DataFrame(subcategory_data)<br><br>    def generate_random_date(self):<br>        &quot;&quot;&quot;Generate a random date within the last 30 days&quot;&quot;&quot;<br>        days_offset = random.randint(0, 30)<br>        return self.end_date - timedelta(days=days_offset)<br><br>    def generate_products(self, n_products=1000):<br>        &quot;&quot;&quot;Generate product catalog with recent dates&quot;&quot;&quot;<br>        categories_df, subcategories_df = self.generate_product_categories()<br>        <br>        products = []<br>        for product_id in range(1, n_products + 1):<br>            category_id = random.randint(1, len(categories_df))<br>            valid_subcats = subcategories_df[subcategories_df[&#39;category_id&#39;] == category_id]<br>            subcategory_id = random.choice(valid_subcats[&#39;subcategory_id&#39;].values)<br>            <br>            base_price = random.uniform(10, 1000)<br>            <br>            # Use recent date for created_at<br>            created_at = self.generate_random_date()<br>            <br>            products.append({<br>                &#39;product_id&#39;: product_id,<br>                &#39;category_id&#39;: category_id,<br>                &#39;subcategory_id&#39;: subcategory_id,<br>                &#39;product_name&#39;: f&quot;{self.fake.company()} {self.fake.word().title()}&quot;,<br>                &#39;description&#39;: self.fake.text(max_nb_chars=200),<br>                &#39;base_price&#39;: round(base_price, 2),<br>                &#39;sale_price&#39;: round(base_price * random.uniform(0.8, 1.0), 2),<br>                &#39;stock_quantity&#39;: random.randint(0, 1000),<br>                &#39;weight_kg&#39;: round(random.uniform(0.1, 20.0), 2),<br>                &#39;is_active&#39;: random.random() &gt; 0.1,<br>                &#39;created_at&#39;: created_at,<br>                &#39;brand&#39;: self.fake.company(),<br>                &#39;sku&#39;: f&quot;SKU-{random.randint(10000, 99999)}&quot;,<br>                &#39;rating&#39;: round(random.uniform(3.0, 5.0), 1),<br>                &#39;review_count&#39;: random.randint(0, 100)<br>            })<br>        <br>        return pd.DataFrame(products), categories_df, subcategories_df<br><br>    def generate_customers(self, n_customers=1000, historic_customers_file=&#39;de-ecommerce/data/customers.csv&#39;):<br>        &quot;&quot;&quot;<br>        Generate customer data with a mix of returning and new customers<br>        <br>        Parameters:<br>            n_customers: Number of total customers to generate<br>            historic_customers_file: Path to historic customers CSV file<br>            <br>        Returns:<br>            DataFrame with customer data<br>        &quot;&quot;&quot;<br>        # Try to load historic customers<br>        try:<br>            historic_df = pd.read_csv(historic_customers_file)<br>            print(f&quot;Loaded {len(historic_df)} historic customers&quot;)<br>            <br>            # Calculate number of returning customers (30% of historic customers)<br>            n_returning = min(int(len(historic_df) * 0.3), n_customers)<br>            n_new = n_customers - n_returning<br>            <br>            print(f&quot;Generating {n_returning} returning customers and {n_new} new customers&quot;)<br>            <br>            # Select random returning customers<br>            returning_customers = historic_df.sample(n=n_returning).copy()<br>            <br>            # Update their activity for the recent period<br>            for idx in returning_customers.index:<br>                # Generate new login date within the last 30 days<br>                last_login = self.generate_random_date()<br>                returning_customers.loc[idx, &#39;last_login&#39;] = last_login<br>                <br>                # Maybe update some other fields that might change<br>                returning_customers.loc[idx, &#39;annual_income&#39;] = max(15000, int(np.random.normal(65000, 30000)))<br>                returning_customers.loc[idx, &#39;marital_status&#39;] = random.choice([&#39;Single&#39;, &#39;Married&#39;, &#39;Divorced&#39;, &#39;Widowed&#39;])<br>                returning_customers.loc[idx, &#39;location_type&#39;] = random.choice([&#39;Urban&#39;, &#39;Suburban&#39;, &#39;Rural&#39;])<br>                returning_customers.loc[idx, &#39;preferred_channel&#39;] = random.choice([&#39;Web&#39;, &#39;Mobile App&#39;, &#39;Email&#39;])<br>                returning_customers.loc[idx, &#39;is_active&#39;] = True  # They&#39;re active since they&#39;re returning<br>            <br>        except FileNotFoundError:<br>            print(&quot;Historic customers file not found. Generating all new customers.&quot;)<br>            n_returning = 0<br>            n_new = n_customers<br>            returning_customers = pd.DataFrame()<br>        <br>        # Generate new customers<br>        new_customers = []<br>        start_id = self.id_offset if not len(returning_customers) else max(returning_customers[&#39;customer_id&#39;]) + 1<br>        <br>        for customer_id in range(start_id, start_id + n_new):<br>            signup_date = self.generate_random_date()<br>            last_login = min(signup_date + timedelta(days=random.randint(0, 5)), self.end_date)<br>            <br>            new_customers.append({<br>                &#39;customer_id&#39;: customer_id,<br>                &#39;email&#39;: self.fake.email(),<br>                &#39;first_name&#39;: self.fake.first_name(),<br>                &#39;last_name&#39;: self.fake.last_name(),<br>                &#39;age&#39;: max(18, min(90, int(np.random.normal(45, 15)))),<br>                &#39;gender&#39;: random.choice([&#39;M&#39;, &#39;F&#39;, &#39;Other&#39;]),<br>                &#39;annual_income&#39;: max(15000, int(np.random.normal(65000, 30000))),<br>                &#39;marital_status&#39;: random.choice([&#39;Single&#39;, &#39;Married&#39;, &#39;Divorced&#39;, &#39;Widowed&#39;]),<br>                &#39;education&#39;: random.choice([&#39;High School&#39;, &#39;Some College&#39;, &#39;Bachelor&#39;, &#39;Master&#39;, &#39;PhD&#39;]),<br>                &#39;location_type&#39;: random.choice([&#39;Urban&#39;, &#39;Suburban&#39;, &#39;Rural&#39;]),<br>                &#39;city&#39;: self.fake.city(),<br>                &#39;state&#39;: self.fake.state(),<br>                &#39;country&#39;: &#39;USA&#39;,<br>                &#39;signup_date&#39;: signup_date,<br>                &#39;last_login&#39;: last_login,<br>                &#39;preferred_channel&#39;: random.choice([&#39;Web&#39;, &#39;Mobile App&#39;, &#39;Email&#39;]),<br>                &#39;is_active&#39;: random.random() &gt; 0.1<br>            })<br>        <br>        # Combine returning and new customers<br>        new_customers_df = pd.DataFrame(new_customers)<br>        final_customers_df = pd.concat([returning_customers, new_customers_df], ignore_index=True)<br>        <br>        print(f&quot;Generated total of {len(final_customers_df)} customers&quot;)<br>        print(f&quot;- Returning customers: {len(returning_customers)}&quot;)<br>        print(f&quot;- New customers: {len(new_customers_df)}&quot;)<br>        <br>        return final_customers_df<br><br>    def generate_orders(self, customers_df, products_df):<br>        &quot;&quot;&quot;Generate order data for the last 30 days&quot;&quot;&quot;<br>        orders = []<br>        order_items = []<br>        order_id = 1<br>        <br>        for _, customer in customers_df.iterrows():<br>            # Reduce number of orders for 30-day period<br>            num_orders = np.random.poisson(2)  # Reduced from 5 to 2<br>            <br>            for _ in range(num_orders):<br>                order_id = order_id + self.id_offset<br>                order_date = max(<br>                    customer[&#39;signup_date&#39;],<br>                    self.generate_random_date()<br>                )<br>                <br>                # Order status based on recent dates<br>                days_since_order = (self.end_date - order_date).days<br>                if days_since_order &lt; 2:<br>                    status = &#39;Pending&#39;<br>                elif days_since_order &lt; 4:<br>                    status = &#39;Processing&#39;<br>                elif days_since_order &lt; 7:<br>                    status = &#39;Shipped&#39;<br>                else:<br>                    status = &#39;Delivered&#39;<br>                <br>                # Generate order items<br>                num_items = np.random.poisson(2) + 1<br>                order_products = products_df.sample(n=min(num_items, len(products_df)))<br>                <br>                shipping_cost = round(random.uniform(5, 20), 2)<br>                total_amount = shipping_cost<br>                <br>                for _, product in order_products.iterrows():<br>                    quantity = random.randint(1, 3)<br>                    price = product[&#39;sale_price&#39;]<br>                    item_total = quantity * price<br>                    total_amount += item_total<br>                    <br>                    order_items.append({<br>                        &#39;order_item_id&#39;: len(order_items) + 1,<br>                        &#39;order_id&#39;: order_id,<br>                        &#39;product_id&#39;: product[&#39;product_id&#39;],<br>                        &#39;quantity&#39;: quantity,<br>                        &#39;unit_price&#39;: price,<br>                        &#39;total_price&#39;: item_total,<br>                        &#39;created_at&#39;: order_date<br>                    })<br>                <br>                orders.append({<br>                    &#39;order_id&#39;: order_id,<br>                    &#39;customer_id&#39;: customer[&#39;customer_id&#39;],<br>                    &#39;order_date&#39;: order_date,<br>                    &#39;status&#39;: status,<br>                    &#39;total_amount&#39;: round(total_amount, 2),<br>                    &#39;shipping_cost&#39;: shipping_cost,<br>                    &#39;payment_method&#39;: random.choice([&#39;Credit Card&#39;, &#39;PayPal&#39;, &#39;Debit Card&#39;]),<br>                    &#39;shipping_address&#39;: self.fake.street_address(),<br>                    &#39;billing_address&#39;: self.fake.street_address(),<br>                    &#39;created_at&#39;: order_date,<br>                    &#39;updated_at&#39;: order_date + timedelta(days=random.randint(0, 2))<br>                })<br>                <br>                order_id += 1<br>        <br>        return pd.DataFrame(orders), pd.DataFrame(order_items)<br><br>    def generate_customer_interactions(self, customers_df, products_df):<br>        &quot;&quot;&quot;Generate customer interactions for the last 30 days&quot;&quot;&quot;<br>        events = []<br>        <br>        for _, customer in customers_df.iterrows():<br>            # Reduce number of interactions for 30-day period<br>            num_interactions = np.random.poisson(10)  # Reduced from 20 to 10<br>            <br>            for _ in range(num_interactions):<br>                event_date = max(<br>                    customer[&#39;signup_date&#39;],<br>                    self.generate_random_date()<br>                )<br>                <br>                product = products_df.sample(n=1).iloc[0]<br>                <br>                events.append({<br>                    &#39;event_id&#39;: len(events) + 1 + self.id_offset,<br>                    &#39;customer_id&#39;: customer[&#39;customer_id&#39;],<br>                    &#39;product_id&#39;: product[&#39;product_id&#39;],<br>                    &#39;event_type&#39;: random.choice([&#39;view&#39;, &#39;cart_add&#39;, &#39;cart_remove&#39;, &#39;wishlist_add&#39;, &#39;search&#39;, &#39;purchase&#39;]),<br>                    &#39;event_date&#39;: event_date,<br>                    &#39;device_type&#39;: random.choice([&#39;desktop&#39;, &#39;mobile&#39;, &#39;tablet&#39;]),<br>                    &#39;session_id&#39;: f&quot;session_{random.randint(10000, 99999)}&quot;,<br>                    &#39;created_at&#39;: event_date<br>                })<br>        <br>        return pd.DataFrame(events)<br>    <br>    def generate_review_text(self, rating, product_type):<br>        &quot;&quot;&quot;Generate realistic review text based on rating&quot;&quot;&quot;<br>        if rating &gt;= 4:<br>            template = random.choice(self.review_templates[&#39;positive&#39;])<br>            aspect = random.choice(self.positive_aspects)<br>            another = random.choice(self.positive_aspects)<br>            return template.format(<br>                product_type=product_type,<br>                positive_aspect=aspect,<br>                another_positive=another<br>            )<br>        elif rating &gt;= 3:<br>            template = random.choice(self.review_templates[&#39;neutral&#39;])<br>            return template.format(<br>                product_type=product_type,<br>                positive_aspect=random.choice(self.positive_aspects),<br>                negative_aspect=random.choice(self.negative_aspects),<br>                neutral_comment=random.choice(self.neutral_comments)<br>            )<br>        else:<br>            template = random.choice(self.review_templates[&#39;negative&#39;])<br>            return template.format(<br>                product_type=product_type,<br>                negative_aspect=random.choice(self.negative_aspects)<br>            )<br><br>    def generate_reviews(self, orders_df, order_items_df, products_df, customers_df):<br>        &quot;&quot;&quot;Generate reviews with new IDs&quot;&quot;&quot;<br>        reviews_data = []<br>        review_id = 1<br>        <br>        for _, row in orders_df.iterrows():<br>            order_items = order_items_df[order_items_df[&#39;order_id&#39;] == row[&#39;order_id&#39;]]<br><br>            for _, item in order_items.iterrows():<br>                reviews_data.append({<br>                    &#39;review_id&#39;: review_id + self.id_offset,<br>                    &#39;product_id&#39;: item[&#39;product_id&#39;],<br>                    &#39;order_id&#39;: row[&#39;order_id&#39;],<br>                    &#39;customer_id&#39;: row[&#39;customer_id&#39;],<br>                    &#39;review_score&#39;: np.random.randint(1, 6),<br>                    &#39;review_text&#39;: self.generate_review_text(<br>                        np.random.randint(1, 6),<br>                        products_df[products_df[&#39;product_id&#39;] == item[&#39;product_id&#39;]].iloc[0][&#39;product_name&#39;]<br>                    )<br>                })<br>                review_id += 1<br><br>                # Update product review count<br>                products_df.loc[products_df[&#39;product_id&#39;] == item[&#39;product_id&#39;], &#39;review_count&#39;] += 1<br><br>        return pd.DataFrame(reviews_data), products_df<br><br>    def generate_all_data(self, n_customers=1000, n_products=1000):<br>        &quot;&quot;&quot;Generate all e-commerce data for the last 30 days&quot;&quot;&quot;<br>        output_formats = {<br>            &#39;customers&#39;: &#39;json&#39;,<br>            &#39;products&#39;: &#39;json&#39;,<br>            &#39;orders&#39;: &#39;json&#39;,<br>            &#39;reviews&#39;: &#39;json&#39;,<br>            &#39;categories&#39;: &#39;csv&#39;,<br>            &#39;subcategories&#39;: &#39;csv&#39;,<br>            &#39;order_items&#39;: &#39;csv&#39;,<br>            &#39;interactions&#39;: &#39;csv&#39;<br>        }<br>        <br>        print(f&quot;Generating data for period: {self.start_date.date()} to {self.end_date.date()}&quot;)<br>        <br>        print(&quot;Generating products...&quot;)<br>        products_df, categories_df, subcategories_df = self.generate_products(n_products)<br>        <br>        print(&quot;Generating customers...&quot;)<br>        customers_df = self.generate_customers(n_customers)<br>        <br>        print(&quot;Generating orders...&quot;)<br>        orders_df, order_items_df = self.generate_orders(customers_df, products_df)<br>        <br>        print(&quot;Generating reviews...&quot;)<br>        reviews_df, updated_products_df = self.generate_reviews(orders_df, order_items_df, products_df, customers_df)<br>        <br>        print(&quot;Generating customer interactions...&quot;)<br>        interactions_df = self.generate_customer_interactions(customers_df, updated_products_df)<br>        <br>        data_dict = {<br>            &#39;customers&#39;: customers_df,<br>            &#39;products&#39;: updated_products_df,<br>            &#39;categories&#39;: categories_df,<br>            &#39;subcategories&#39;: subcategories_df,<br>            &#39;orders&#39;: orders_df,<br>            &#39;order_items&#39;: order_items_df,<br>            &#39;reviews&#39;: reviews_df,<br>            &#39;interactions&#39;: interactions_df<br>        }<br>        <br>        # self.save_data(data_dict, output_formats)<br>        <br>        return data_dict<br>    <br>class EcommerceDataLoader:<br>    def __init__(self, aws_access_key_id, aws_secret_access_key, bucket_name, <br>                 pg_host, pg_port, pg_user, <br>                 pg_password, pg_database):<br>        &quot;&quot;&quot;Initialize connections to S3 and PostgreSQL&quot;&quot;&quot;<br>        # S3 client setup<br>        self.s3_client = boto3.client(<br>            &#39;s3&#39;,<br>            aws_access_key_id=aws_access_key_id,<br>            aws_secret_access_key=aws_secret_access_key<br>        )<br>        self.bucket_name = bucket_name<br><br>        # PostgreSQL connection setup<br>        self.pg_conn_string = f&quot;postgresql://{pg_user}:{pg_password}@{pg_host}:{pg_port}/{pg_database}&quot;<br>        self.engine = create_engine(self.pg_conn_string)<br><br>    def upload_json_to_s3(self, data_dict, table_name):<br>        &quot;&quot;&quot;Upload JSON data directly to S3&quot;&quot;&quot;<br>        try:<br>            # Convert DataFrame to JSON format with metadata<br>            json_data = {<br>                &quot;metadata&quot;: {<br>                    &quot;table&quot;: table_name,<br>                    &quot;recordCount&quot;: len(data_dict),<br>                    &quot;generatedAt&quot;: pd.Timestamp.now().isoformat(),<br>                    &quot;version&quot;: &quot;1.0&quot;<br>                },<br>                &quot;data&quot;: json.loads(data_dict.to_json(orient=&#39;records&#39;, date_format=&#39;iso&#39;))<br>            }<br>            <br>            # Convert to JSON string<br>            json_str = json.dumps(json_data)<br>            <br>            # Upload to S3<br>            s3_key = f&#39;json/{table_name}.json&#39;<br>            self.s3_client.put_object(<br>                Bucket=self.bucket_name,<br>                Key=s3_key,<br>                Body=json_str,<br>                ContentType=&#39;application/json&#39;<br>            )<br>            print(f&quot;Uploaded {table_name} to S3: s3://{self.bucket_name}/{s3_key}&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error uploading {table_name} to S3: {str(e)}&quot;)<br>            raise<br><br>    def load_csv_to_postgres(self, df, table_name):<br>        &quot;&quot;&quot;Load DataFrame directly to PostgreSQL&quot;&quot;&quot;<br>        <br>        if not isinstance(df, pd.DataFrame):<br>            raise ValueError(&quot;df must be a pandas DataFrame&quot;)<br>        try:<br>            # Create copy buffer<br>            output = StringIO()<br>            df.to_csv(output, index=False, header=True)<br>            output.seek(0)<br>            <br>            # Create database connection<br>            with self.engine.connect() as connection:<br>                # Create table if it doesn&#39;t exist<br>                df.head(0).to_sql(table_name, connection, if_exists=&#39;replace&#39;, index=False)<br>                <br>                # Copy data<br>                raw_conn = connection.connection<br>                with raw_conn.cursor() as cursor:<br>                    cursor.copy_expert(<br>                        f&quot;COPY {table_name} FROM STDIN WITH CSV HEADER&quot;,<br>                        output<br>                    )<br>                raw_conn.commit()<br>                <br>            print(f&quot;Loaded {len(df)} rows to PostgreSQL table: {table_name}&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error loading {table_name} to PostgreSQL: {str(e)}&quot;)<br>            raise<br><br>def save_data(data_dict):<br>    &quot;&quot;&quot;Save data to S3 and PostgreSQL&quot;&quot;&quot;<br>    # AWS credentials (replace with your own)<br>    aws_access_key_id = os.environ.get(&quot;AWS_S3_ACCESS_KEY_ID&quot;)<br>    aws_secret_access_key = os.environ.get(&quot;AWS_S3_SECRET_ACCESS_KEY&quot;)<br>    bucket_name = os.environ.get(&quot;AWS_S3_LATEST_SYNTH&quot;)<br><br>    # Validate AWS credentials<br>    if not all([aws_access_key_id, aws_secret_access_key, bucket_name]):<br>        raise ValueError(&quot;Required AWS environment variables are not set&quot;)<br><br>    # PostgreSQL connection details<br>    pg_config = {<br>        &#39;pg_host&#39;: os.environ.get(&quot;POSTGRES_HOST&quot;),<br>        &#39;pg_port&#39;: int(os.environ.get(&quot;POSTGRES_PORT&quot;)),<br>        &#39;pg_user&#39;: os.environ.get(&quot;POSTGRES_USER&quot;),<br>        &#39;pg_password&#39;: os.environ.get(&quot;POSTGRES_PASSWORD&quot;),<br>        &#39;pg_database&#39;: os.environ.get(&quot;POSTGRES_DB&quot;)<br>    }<br><br>    # Initialize loader<br>    loader = EcommerceDataLoader(<br>        aws_access_key_id=aws_access_key_id,<br>        aws_secret_access_key=aws_secret_access_key,<br>        bucket_name=bucket_name,<br>        **pg_config<br>    )<br><br>    # Define which tables go to which destination<br>    json_tables = [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;]<br>    csv_tables_mapping = {<br>        &#39;categories&#39;: &#39;latest_categories&#39;,<br>        &#39;subcategories&#39;: &#39;latest_subcategories&#39;,<br>        &#39;order_items&#39;: &#39;latest_order_items&#39;,<br>        &#39;interactions&#39;: &#39;latest_interactions&#39;<br>    }<br>    <br>    # Upload JSON files to S3<br>    for table_name in json_tables:<br>        if table_name in data_dict:<br>            loader.upload_json_to_s3(data_dict[table_name], table_name)<br><br>    # Load CSV files to PostgreSQL with the &#39;latest_&#39; prefix<br>    for original_name, latest_name in csv_tables_mapping.items():<br>        if original_name in data_dict:<br>            print(f&quot;Loading {original_name} to PostgreSQL as {latest_name}&quot;)<br>            loader.load_csv_to_postgres(data_dict[original_name], latest_name)<br>            <br>    output_dir = Path(&#39;generated_latest_data&#39;)<br>    output_dir.mkdir(parents=True, exist_ok=True)<br>    <br>    for table_name, df in data_dict.items():<br>        csv_path = output_dir / f&quot;{table_name}.csv&quot;<br>        df.to_csv(csv_path, index=False)<br>        print(f&quot;Saved {table_name} to {csv_path}&quot;)<br>        <br>    output_dir.mkdir(parents=True, exist_ok=True)<br>    for table_name, df in data_dict.items():<br>        csv_path = os.path.join(output_dir, f&quot;{table_name}.csv&quot;)<br>        df.to_csv(csv_path, index=False)<br>        print(f&quot;Saved {table_name} to {csv_path}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    # Generate data<br>    generator = RecentEcommerceDataGenerator()<br>    data = generator.generate_all_data()<br>    <br>    # Save data directly to S3 and PostgreSQL<br>    save_data(data)<br>    <br>    # Print summary<br>    print(&quot;\nData Generation and Loading Summary:&quot;)<br>    for table_name, df in data.items():<br>        print(f&quot;\n{table_name.upper()} Table:&quot;)<br>        print(f&quot;Total records: {len(df)}&quot;)<br>        <br>        # Different tables have different date columns<br>        date_columns = {<br>            &#39;customers&#39;: &#39;signup_date&#39;,<br>            &#39;products&#39;: &#39;created_at&#39;,<br>            &#39;orders&#39;: &#39;order_date&#39;,<br>            &#39;latest_order_items&#39;: &#39;created_at&#39;,<br>            &#39;reviews&#39;: &#39;created_at&#39;,<br>            &#39;latest_interactions&#39;: &#39;event_date&#39;,<br>            &#39;latest_categories&#39;: &#39;created_at&#39;,<br>            &#39;latest_subcategories&#39;: &#39;created_at&#39;<br>        }<br>        <br>        # Get the appropriate date column for this table<br>        date_col = date_columns.get(table_name)<br>        if date_col and date_col in df.columns:<br>            print(f&quot;Date range: {df[date_col].min()} to {df[date_col].max()}&quot;)<br>        <br>        destination = &#39;S3&#39; if table_name in [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;] else &#39;PostgreSQL&#39;<br>        print(f&quot;Loaded to: {destination}&quot;)</pre><p>2. Run:</p><pre>python src/pipeline/generate/latest_synthetic_data.py</pre><p>3. Initially check the generated_latest_data folder for the csv versions of the data. Review the data generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*zHuWoi8lJS7fXEuO8Kmc2g.png" /></figure><p>4. Check the latest-ecom S3 bucket json folder for the generated data (customers, orders, products, reviews).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxVHWtaI0tEXK_tD3Dsn2g.png" /></figure><p>5. Check the latest data (categories, interactions, order_items, subcategories) on pgAdmin by going to the Query Tool and running SQL queries as sampled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fIQRTRjv9Fx6bx4TUWyRA.png" /></figure><p>6. You can also verify the Postgres data using psql. Run the command on a terminal:</p><pre>docker exec -it postgres_cont psql -U root -d ecom_db_source<br><br>SELECT * FROM latest_&lt;table_name&gt;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*rQ-xhmVeGM4Q7OrfXauDWg.png" /></figure><h3>III. Data Ingestion</h3><p>GitHub branch to follow: <a href="https://github.com/sclauguico/ecommerce-modern-data-stack/tree/3-data-ingestion-etl">https://github.com/sclauguico/ecommerce-modern-data-stack/tree/3-data-ingestion-etl</a></p><h3>1. Initial Append ETL Ingestion</h3><p>Steps:</p><ol><li>Add the following files under src/pipeline:</li></ol><ul><li>ingested_data</li><li>0_ingest_historic_synthetic_data.py</li><li>generate_latest_synthetic_data.py</li></ul><p>2. Copy and paste the following code to 0_ingest_historic_synthetic_data.py:</p><pre>import os<br>import pandas as pd<br>import boto3<br>import json<br>from sqlalchemy import create_engine<br>from dotenv import load_dotenv<br>import snowflake.connector<br>from snowflake.connector.pandas_tools import write_pandas<br>import psycopg2<br>import tempfile<br>from pandas import json_normalize<br>from datetime import datetime<br>import uuid<br>import io<br>from pathlib import Path<br><br>load_dotenv()<br><br>class InitialHistoricETL:<br>    def __init__(self):<br>        # Initialize connections<br>        self._init_postgres()<br>        self._init_s3()<br>        self._init_snowflake()<br>        <br>        # Define source mappings<br>        self.postgres_tables = [&#39;categories&#39;, &#39;subcategories&#39;, &#39;order_items&#39;, &#39;interactions&#39;]<br>        self.s3_tables = [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;]<br>        <br>        # Track batch information<br>        self.batch_id = str(uuid.uuid4())<br>        self.batch_timestamp = datetime.now()<br>    <br>    def _init_postgres(self):<br>        &quot;&quot;&quot;Initialize PostgreSQL connection&quot;&quot;&quot;<br>        self.pg_conn_string = f&quot;postgresql://{os.getenv(&#39;POSTGRES_USER&#39;)}:{os.getenv(&#39;POSTGRES_PASSWORD&#39;)}@{os.getenv(&#39;POSTGRES_HOST&#39;)}:{os.getenv(&#39;POSTGRES_PORT&#39;)}/{os.getenv(&#39;POSTGRES_DB&#39;)}&quot;<br>        self.pg_engine = create_engine(self.pg_conn_string)<br><br>    def _init_s3(self):<br>        &quot;&quot;&quot;Initialize S3 clients&quot;&quot;&quot;<br>        s3_credentials = {<br>            &#39;aws_access_key_id&#39;: os.getenv(&#39;AWS_S3_ACCESS_KEY_ID&#39;),<br>            &#39;aws_secret_access_key&#39;: os.getenv(&#39;AWS_S3_SECRET_ACCESS_KEY&#39;)<br>        }<br>        <br>        self.s3_client = boto3.client(&#39;s3&#39;, **s3_credentials)<br>        self.historic_bucket = os.getenv(&#39;AWS_S3_HISTORIC_SYNTH&#39;)<br>        self.latest_bucket = os.getenv(&#39;AWS_S3_LATEST_SYNTH&#39;)<br><br>    def _init_snowflake(self):<br>        &quot;&quot;&quot;Initialize Snowflake connection&quot;&quot;&quot;<br>        try:<br>            self.snow_conn = snowflake.connector.connect(<br>                user=os.getenv(&#39;SNOWFLAKE_USER&#39;),<br>                password=os.getenv(&#39;SNOWFLAKE_PASSWORD&#39;),<br>                account=os.getenv(&#39;SNOWFLAKE_ACCOUNT&#39;),<br>                warehouse=os.getenv(&#39;SNOWFLAKE_WAREHOUSE&#39;),<br>                role=os.getenv(&#39;SNOWFLAKE_ROLE&#39;)<br>            )<br>            <br>            self.snow_cursor = self.snow_conn.cursor()<br>            <br>            # Setup database and schema<br>            for cmd in [<br>                f&quot;USE WAREHOUSE {os.getenv(&#39;SNOWFLAKE_WAREHOUSE&#39;)}&quot;,<br>                f&quot;USE DATABASE {os.getenv(&#39;SNOWFLAKE_DATABASE&#39;)}&quot;,<br>                f&quot;USE SCHEMA {os.getenv(&#39;SNOWFLAKE_RAW_SCHEMA&#39;)}&quot;<br>            ]:<br>                self.snow_cursor.execute(cmd)<br>                <br>        except Exception as e:<br>            print(f&quot;Snowflake initialization error: {str(e)}&quot;)<br>            raise<br><br>    def extract_from_postgres(self, table_name, data_source):<br>        &quot;&quot;&quot;Extract data from PostgreSQL&quot;&quot;&quot;<br>        try:<br>            table_prefix = &#39;latest_&#39; if data_source == &#39;latest&#39; else &#39;&#39;<br>            query = f&quot;SELECT * FROM {table_prefix}{table_name}&quot;<br>            df = pd.read_sql(query, self.pg_engine)<br>            return df<br>        except Exception as e:<br>            print(f&quot;PostgreSQL extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def extract_from_s3(self, table_name, data_source):<br>        &quot;&quot;&quot;Extract data from S3&quot;&quot;&quot;<br>        try:<br>            bucket = self.latest_bucket if data_source == &#39;latest&#39; else self.historic_bucket<br>            response = self.s3_client.get_object(<br>                Bucket=bucket,<br>                Key=f&#39;json/{table_name}.json&#39;<br>            )<br>            <br>            json_content = json.loads(response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;))<br>            return pd.DataFrame(json_content[&#39;data&#39;])<br>        except Exception as e:<br>            print(f&quot;S3 extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br>        <br>    def get_primary_keys(self, table_name):<br>        &quot;&quot;&quot;Return primary key columns for each table&quot;&quot;&quot;<br>        pk_mapping = {<br>            &#39;customers&#39;: [&#39;CUSTOMER_ID&#39;],<br>            &#39;orders&#39;: [&#39;ORDER_ID&#39;],<br>            &#39;products&#39;: [&#39;PRODUCT_ID&#39;],<br>            &#39;order_items&#39;: [&#39;ORDER_ITEM_ID&#39;],<br>            &#39;categories&#39;: [&#39;CATEGORY_ID&#39;],<br>            &#39;subcategories&#39;: [&#39;SUBCATEGORY_ID&#39;],<br>            &#39;reviews&#39;: [&#39;REVIEW_ID&#39;],<br>            &#39;interactions&#39;: [&#39;EVENT_ID&#39;]<br>        }<br>        return pk_mapping.get(table_name.replace(&#39;latest_&#39;, &#39;&#39;), [&#39;id&#39;])<br><br>    def remove_duplicate_primary_keys(self, df, table_name):<br>        &quot;&quot;&quot;Remove rows with duplicate primary keys, defaulting to the first column if necessary.&quot;&quot;&quot;<br>        try:<br>            # Get primary keys for the table<br>            primary_keys = self.get_primary_keys(table_name)<br><br>            if not primary_keys:<br>                print(f&quot;Warning: No primary keys found or defined for {table_name}. Skipping deduplication.&quot;)<br>                return df<br><br>            # Ensure all primary keys exist in the DataFrame<br>            missing_keys = [key for key in primary_keys if key not in df.columns]<br>            if missing_keys:<br>                print(f&quot;Error: Missing primary keys {missing_keys} in table {table_name}.&quot;)<br>                return df<br><br>            # Deduplicate based on primary keys<br>            if &quot;LOADED_AT&quot; in df.columns:<br>                df = df.sort_values(by=&quot;LOADED_AT&quot;, ascending=False)<br>            else:<br>                print(f&quot;Warning: No valid date column found for {table_name}. Proceeding without sorting.&quot;)<br>            df = df.drop_duplicates(subset=primary_keys, keep=&quot;first&quot;)<br>            return df<br>        except Exception as e:<br>            print(f&quot;Error removing duplicate primary keys for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def transform_data(self, df, table_name):<br>        &quot;&quot;&quot;Transform data with added metadata columns&quot;&quot;&quot;<br>        try:<br>            # Flatten JSON if needed<br>            df = self.flatten_json_df(df, table_name)<br>            <br>            # Add metadata columns<br>            df[&#39;DATA_SOURCE&#39;] = &#39;historic&#39;<br>            df[&#39;BATCH_ID&#39;] = self.batch_id<br>            df[&#39;LOADED_AT&#39;] = self.batch_timestamp<br>            <br>            # Standard transformations<br>            for col in df.select_dtypes(include=[&#39;datetime64&#39;]).columns:<br>                df[col] = df[col].dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>            <br>            df = df.replace({pd.NA: None, pd.NaT: None})<br>            <br>            # Convert column names to uppercase for Snowflake<br>            df.columns = [col.upper() for col in df.columns]<br>            df = self.remove_duplicate_primary_keys(df, table_name)<br>            <br>            return df<br>            <br>        except Exception as e:<br>            print(f&quot;Transform error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def flatten_json_df(self, df, table_name):<br>        &quot;&quot;&quot;Flatten nested JSON structures&quot;&quot;&quot;<br>        try:<br>            json_columns = [<br>                col for col in df.columns <br>                if df[col].dtype == &#39;object&#39; and <br>                isinstance(df[col].dropna().iloc[0] if not df[col].isna().all() else None, (dict, list))<br>            ]<br>            <br>            if not json_columns:<br>                return df<br><br>            flat_df = df.copy()<br>            <br>            for col in json_columns:<br>                try:<br>                    if isinstance(df[col].dropna().iloc[0], dict):<br>                        flattened = pd.json_normalize(df[col].dropna(), sep=&#39;_&#39;)<br>                        flat_df = flat_df.drop(columns=[col])<br>                        for new_col in flattened.columns:<br>                            flat_df[f&quot;{col}_{new_col}&quot;] = flattened[new_col]<br>                    elif isinstance(df[col].dropna().iloc[0], list):<br>                        flat_df[col] = df[col].apply(lambda x: json.dumps(x) if isinstance(x, list) else x)<br>                except Exception as e:<br>                    print(f&quot;Warning: Could not flatten column {col}: {str(e)}&quot;)<br>                    continue<br>            <br>            return flat_df<br>        except Exception as e:<br>            print(f&quot;JSON flattening error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def save_to_s3_historic(self, df, table_name, metadata):<br>        &quot;&quot;&quot;Save transformed data and metadata to S3 historic bucket&quot;&quot;&quot;<br>        try:<br>            <br>            output_dir = Path(&#39;ingested_data&#39;)<br>            output_dir.mkdir(parents=True, exist_ok=True)<br>            <br>            # Save as CSV<br>            csv_buffer = io.StringIO()<br>            df.to_csv(csv_buffer, index=False)<br><br>            # Save to historic data folder<br>            self.s3_client.put_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}.csv&#39;,<br>                Body=csv_buffer.getvalue().encode(&#39;utf-8&#39;)<br>            )<br>            <br>            # Save metadata<br>            self.s3_client.put_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}_metadata.json&#39;,<br>                Body=json.dumps(metadata, default=str)<br>            )<br>            <br>            print(f&quot;Successfully saved {table_name} to historic bucket as CSV with metadata&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error saving to S3 historic bucket: {str(e)}&quot;)<br>            raise<br><br>    def load_to_snowflake(self, df, table_name):<br>        &quot;&quot;&quot;Load data to Snowflake&quot;&quot;&quot;<br>        try:<br>            database = os.getenv(&#39;SNOWFLAKE_DATABASE&#39;)<br>            schema = os.getenv(&#39;SNOWFLAKE_RAW_SCHEMA&#39;)<br>            full_table_name = f&quot;{database}.{schema}.{table_name.upper()}&quot;<br>            <br>            # Create table if not exists<br>            column_definitions = []<br>            for col_name, dtype in df.dtypes.items():<br>                sf_type = &quot;VARCHAR&quot;<br>                if pd.api.types.is_integer_dtype(dtype):<br>                    sf_type = &quot;NUMBER&quot;<br>                elif pd.api.types.is_float_dtype(dtype):<br>                    sf_type = &quot;FLOAT&quot;<br>                elif pd.api.types.is_datetime64_any_dtype(dtype):<br>                    sf_type = &quot;TIMESTAMP&quot;<br>                column_definitions.append(f&#39;&quot;{col_name.upper()}&quot; {sf_type}&#39;)<br><br>            create_table_sql = f&quot;&quot;&quot;<br>            CREATE TABLE IF NOT EXISTS {full_table_name} (<br>                {&#39;, &#39;.join(column_definitions)}<br>            )<br>            &quot;&quot;&quot;<br>            <br>            self.snow_cursor.execute(create_table_sql)<br>            <br>            # Write data<br>            success, num_chunks, num_rows, _ = write_pandas(<br>                conn=self.snow_conn,<br>                df=df,<br>                table_name=table_name.upper(),<br>                database=database,<br>                schema=schema,<br>                quote_identifiers=False<br>            )<br><br>            if not success:<br>                raise Exception(f&quot;Failed to load {table_name} to Snowflake&quot;)<br><br>            print(f&quot;Successfully loaded {num_rows} rows to {full_table_name}&quot;)<br><br>        except Exception as e:<br>            print(f&quot;Error loading to Snowflake: {str(e)}&quot;)<br>            raise<br><br>    def find_valid_date_column(self, df, table_name):<br>        &quot;&quot;&quot;Find the first valid date column from the possible options&quot;&quot;&quot;<br>        possible_columns = self.get_date_column(table_name)<br>        <br>        for col in possible_columns:<br>            if col in df.columns:<br>                return col<br>                <br>        return None<br><br>    def get_date_column(self, table_name):<br>        &quot;&quot;&quot;Return the appropriate date column for each table with fallbacks&quot;&quot;&quot;<br>        date_columns = {<br>            &#39;customers&#39;: [&#39;signup_date&#39;, &#39;last_login&#39;, &#39;created_at&#39;],<br>            &#39;orders&#39;: [&#39;order_date&#39;, &#39;created_at&#39;, &#39;updated_at&#39;],<br>            &#39;products&#39;: [&#39;created_at&#39;],<br>            &#39;order_items&#39;: [&#39;created_at&#39;, &#39;order_date&#39;],<br>            &#39;reviews&#39;: [&#39;created_at&#39;, &#39;order_date&#39;],<br>            &#39;interactions&#39;: [&#39;event_date&#39;, &#39;created_at&#39;],<br>            &#39;categories&#39;: [&#39;created_at&#39;],<br>            &#39;subcategories&#39;: [&#39;created_at&#39;]<br>        }<br>        <br>        clean_table_name = table_name.replace(&#39;latest_&#39;, &#39;&#39;)<br>        return date_columns.get(clean_table_name, [&#39;created_at&#39;])<br><br>    def run_initial_load(self):<br>        &quot;&quot;&quot;Execute ETL process for initial historic data setup&quot;&quot;&quot;<br>        try:<br>            print(&quot;\nStarting initial historic data load...&quot;)<br>            <br>            # Create local directory for CSV files if it doesn&#39;t exist<br>            os.makedirs(&quot;ingested_data&quot;, exist_ok=True)<br>            <br>            for table in self.postgres_tables + self.s3_tables:<br>                print(f&quot;\nProcessing {table}&quot;)<br>                <br>                try:<br>                    # Extract and combine data<br>                    historic_df = (self.extract_from_s3(table, &#39;historic&#39;) <br>                                if table in self.s3_tables <br>                                else self.extract_from_postgres(table, &#39;historic&#39;))<br>                    <br>                    latest_df = (self.extract_from_s3(table, &#39;latest&#39;) <br>                            if table in self.s3_tables <br>                            else self.extract_from_postgres(table, &#39;latest&#39;))<br>                    <br>                    # Find valid date column<br>                    date_column = self.find_valid_date_column(latest_df, table)<br>                    <br>                    if date_column:<br>                        min_latest_date = latest_df[date_column].min()<br>                        print(f&quot;Latest data starts from: {min_latest_date}&quot;)<br>                    else:<br>                        print(f&quot;Warning: No valid date column found for {table}&quot;)<br>                        min_latest_date = None<br>                    <br>                    # Combine and transform data<br>                    combined_df = pd.concat([historic_df, latest_df], ignore_index=True)<br>                    transformed_df = self.transform_data(combined_df, table)<br>                    <br>                    # Save to local CSV<br>                    combined_path = f&quot;ingested_data/{table}_combined.csv&quot;<br>                    transformed_df.to_csv(combined_path, index=False)<br>                    print(f&quot;Saved combined data to {combined_path}&quot;)<br>                    <br>                    # Prepare metadata<br>                    metadata = {<br>                        &#39;table_name&#39;: table,<br>                        &#39;batch_id&#39;: self.batch_id,<br>                        &#39;timestamp&#39;: self.batch_timestamp,<br>                        &#39;historic_records&#39;: len(historic_df),<br>                        &#39;latest_records&#39;: len(latest_df),<br>                        &#39;total_records&#39;: len(combined_df),<br>                        &#39;date_column_used&#39;: date_column,<br>                        &#39;columns&#39;: transformed_df.columns.tolist(),<br>                        &#39;data_types&#39;: transformed_df.dtypes.astype(str).to_dict(),<br>                        &#39;min_date&#39;: min_latest_date if date_column else None<br>                    }<br>                    <br>                    # Save to S3 as historic data<br>                    self.save_to_s3_historic(transformed_df, table, metadata)<br>                    <br>                    # Load to Snowflake<br>                    self.load_to_snowflake(transformed_df, table)<br>                    <br>                    print(f&quot;&quot;&quot;<br>                    Completed processing for {table}:<br>                    - Historic records: {len(historic_df)}<br>                    - Latest records: {len(latest_df)}<br>                    - Total records processed: {len(combined_df)}<br>                    - Date column used: {date_column if date_column else &#39;None&#39;}<br>                    - Data saved locally to: {combined_path}<br>                    - Data saved to S3 historic bucket<br>                    - Data loaded to Snowflake table: {table.upper()}<br>                    &quot;&quot;&quot;)<br><br>                except Exception as e:<br>                    print(f&quot;Error processing table {table}: {str(e)}&quot;)<br>                    continue<br><br>        except Exception as e:<br>            print(f&quot;Initial load process error: {str(e)}&quot;)<br>            raise<br>        finally:<br>            self.snow_cursor.close()<br>            self.snow_conn.close()<br>            print(&quot;\nInitial historic data load completed. Connections closed.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        etl = InitialHistoricETL()<br>        etl.run_initial_load()<br>    except Exception as e:<br>        print(f&quot;Main execution error: {str(e)}&quot;)<br>        raise</pre><ol><li>Run:</li></ol><pre>python src/pipeline/0_ingest_historic_synthetic_data.py</pre><p>2. Initially check if the latest data is appended to the historic data in the ingested_data folder:</p><p>Note: Take note of the min and max dates. You can also do this using .ipynb</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHoqO-rZRkxqQqaKbbLR6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*__W4g1f0SvG3LZ2S9ZZdfA.png" /></figure><p>4. Check historic-ecom S3 bucket &gt; csv if the appended data have been loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxoqJv2HEYUAnZpnvizp5A.png" /></figure><p>5. Run this on Snowflake to ensure all privileges are granted to ECOM_ROLE</p><pre>BEGIN<br>-- Grant warehouse usage<br>GRANT USAGE ON WAREHOUSE ECOM_WH TO ROLE ECOM_ROLE;<br><br>-- Grant database level privileges<br>GRANT ALL PRIVILEGES ON DATABASE ECOM_DB TO ROLE ECOM_ROLE;<br><br>-- Grant schema level privileges for all existing schemas<br>GRANT ALL PRIVILEGES ON ALL SCHEMAS IN DATABASE ECOM_DB TO ROLE ECOM_ROLE;<br>GRANT ALL PRIVILEGES ON FUTURE SCHEMAS IN DATABASE ECOM_DB TO ROLE ECOM_ROLE;<br><br>-- Grant table level privileges<br>GRANT ALL PRIVILEGES ON ALL TABLES IN DATABASE ECOM_DB TO ROLE ECOM_ROLE;<br>GRANT ALL PRIVILEGES ON FUTURE TABLES IN DATABASE ECOM_DB TO ROLE ECOM_ROLE;<br><br>-- Grant view level privileges<br>GRANT ALL PRIVILEGES ON ALL VIEWS IN DATABASE ECOM_DB TO ROLE ECOM_ROLE;<br>GRANT ALL PRIVILEGES ON FUTURE VIEWS IN DATABASE ECOM_DB TO ROLE ECOM_ROLE;<br><br>-- Switch back to ECOM_ROLE<br>USE ROLE ECOM_ROLE;<br><br>-- Verify grants<br>SHOW GRANTS TO ROLE ECOM_ROLE;<br>END</pre><p>6. Check data in ECOM_RAW. Take note of those in red boxes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ZVinKgnIAsqvYZPpUKEKQ.png" /></figure><p>7. Run queries to test. Example:</p><pre>SELECT <br>    MIN(order_date) as earliest_order,<br>    MAX(order_date) as latest_order<br>FROM orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQhPdgPlTaFZNZatKhKB9A.png" /></figure><p>Note: This shows that the latest data appended to the initial historic data is loaded to ECOM_RAW schema. The maximum order date of the initial data was Nov. 30, 2024. Now it’s updated to Dec. 30, 2024.</p><p>The ECOM_RAW data follows the following data model. <a href="https://dbdiagram.io/d/ecom_raw_schema-6767d960fc29fb2b3b1475af">See model in detail here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKJh17xnjiMfEvrIfkDL0g.png" /></figure><h3>2. Latest Append ETL Ingestion</h3><p>Steps:</p><ol><li>Copy and paste the following code to ingest_latest_synthetic_data.py.</li></ol><p>Note: The script’s objective is the same as the initial append, but extracts historic data from historic-ecom/csv instead of the original generated historic data.</p><pre>import os<br>import pandas as pd<br>import boto3<br>import json<br>from sqlalchemy import create_engine<br>from dotenv import load_dotenv<br>import snowflake.connector<br>from snowflake.connector.pandas_tools import write_pandas<br>import psycopg2<br>import tempfile<br>from pandas import json_normalize<br>from datetime import datetime<br>import uuid<br>import io<br><br>load_dotenv()<br><br>class IncrementalETL:<br>    def __init__(self):<br>        # Initialize connections<br>        self._init_postgres()<br>        self._init_s3()<br>        self._init_snowflake()<br>        <br>        # Define source mappings<br>        self.postgres_tables = [&#39;categories&#39;, &#39;subcategories&#39;, &#39;order_items&#39;, &#39;interactions&#39;]<br>        self.s3_tables = [&#39;customers&#39;, &#39;products&#39;, &#39;orders&#39;, &#39;reviews&#39;]<br>        <br>        # Track batch information<br>        self.batch_id = str(uuid.uuid4())<br>        self.batch_timestamp = datetime.now()<br>    <br>    def _init_postgres(self):<br>        &quot;&quot;&quot;Initialize PostgreSQL connection&quot;&quot;&quot;<br>        self.pg_conn_string = f&quot;postgresql://{os.getenv(&#39;POSTGRES_USER&#39;)}:{os.getenv(&#39;POSTGRES_PASSWORD&#39;)}@{os.getenv(&#39;POSTGRES_HOST&#39;)}:{os.getenv(&#39;POSTGRES_PORT&#39;)}/{os.getenv(&#39;POSTGRES_DB&#39;)}&quot;<br>        self.pg_engine = create_engine(self.pg_conn_string)<br><br>    def _init_s3(self):<br>        &quot;&quot;&quot;Initialize S3 clients&quot;&quot;&quot;<br>        s3_credentials = {<br>            &#39;aws_access_key_id&#39;: os.getenv(&#39;AWS_S3_ACCESS_KEY_ID&#39;),<br>            &#39;aws_secret_access_key&#39;: os.getenv(&#39;AWS_S3_SECRET_ACCESS_KEY&#39;)<br>        }<br>        <br>        self.s3_client = boto3.client(&#39;s3&#39;, **s3_credentials)<br>        self.historic_bucket = os.getenv(&#39;AWS_S3_HISTORIC_SYNTH&#39;)<br>        self.latest_bucket = os.getenv(&#39;AWS_S3_LATEST_SYNTH&#39;)<br><br>    def _init_snowflake(self):<br>        &quot;&quot;&quot;Initialize Snowflake connection&quot;&quot;&quot;<br>        try:<br>            self.snow_conn = snowflake.connector.connect(<br>                user=os.getenv(&#39;SNOWFLAKE_USER&#39;),<br>                password=os.getenv(&#39;SNOWFLAKE_PASSWORD&#39;),<br>                account=os.getenv(&#39;SNOWFLAKE_ACCOUNT&#39;),<br>                warehouse=os.getenv(&#39;SNOWFLAKE_WAREHOUSE&#39;),<br>                role=os.getenv(&#39;SNOWFLAKE_ROLE&#39;)<br>            )<br>            <br>            self.snow_cursor = self.snow_conn.cursor()<br>            <br>            # Setup database and schema<br>            for cmd in [<br>                f&quot;USE WAREHOUSE {os.getenv(&#39;SNOWFLAKE_WAREHOUSE&#39;)}&quot;,<br>                f&quot;USE DATABASE {os.getenv(&#39;SNOWFLAKE_DATABASE&#39;)}&quot;,<br>                f&quot;USE SCHEMA {os.getenv(&#39;SNOWFLAKE_RAW_SCHEMA&#39;)}&quot;<br>            ]:<br>                self.snow_cursor.execute(cmd)<br>                <br>        except Exception as e:<br>            print(f&quot;Snowflake initialization error: {str(e)}&quot;)<br>            raise<br><br>    def extract_historic_from_s3(self, table_name):<br>        &quot;&quot;&quot;Extract historic data from S3 CSV files&quot;&quot;&quot;<br>        try:<br>            # Get CSV file from historic bucket<br>            response = self.s3_client.get_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}.csv&#39;<br>            )<br>            <br>            # Read CSV content<br>            csv_content = response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>            return pd.read_csv(io.StringIO(csv_content))<br>            <br>        except Exception as e:<br>            print(f&quot;Historic S3 extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def extract_latest_from_postgres(self, table_name):<br>        &quot;&quot;&quot;Extract latest data from PostgreSQL&quot;&quot;&quot;<br>        try:<br>            query = f&quot;SELECT * FROM latest_{table_name}&quot;<br>            df = pd.read_sql(query, self.pg_engine)<br>            return df<br>        except Exception as e:<br>            print(f&quot;PostgreSQL extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def extract_latest_from_s3(self, table_name):<br>        &quot;&quot;&quot;Extract latest data from S3&quot;&quot;&quot;<br>        try:<br>            response = self.s3_client.get_object(<br>                Bucket=self.latest_bucket,<br>                Key=f&#39;json/{table_name}.json&#39;<br>            )<br>            <br>            json_content = json.loads(response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;))<br>            return pd.DataFrame(json_content[&#39;data&#39;])<br>        except Exception as e:<br>            print(f&quot;Latest S3 extraction error for {table_name}: {str(e)}&quot;)<br>            raise<br>    def get_primary_keys(self, table_name):<br>        &quot;&quot;&quot;Return primary key columns for each table&quot;&quot;&quot;<br>        pk_mapping = {<br>            &#39;customers&#39;: [&#39;CUSTOMER_ID&#39;],<br>            &#39;orders&#39;: [&#39;ORDER_ID&#39;],<br>            &#39;products&#39;: [&#39;PRODUCT_ID&#39;],<br>            &#39;order_items&#39;: [&#39;ORDER_ITEM_ID&#39;],<br>            &#39;categories&#39;: [&#39;CATEGORY_ID&#39;],<br>            &#39;subcategories&#39;: [&#39;SUBCATEGORY_ID&#39;],<br>            &#39;reviews&#39;: [&#39;REVIEW_ID&#39;],<br>            &#39;interactions&#39;: [&#39;EVENT_ID&#39;]<br>        }<br>        return pk_mapping.get(table_name.replace(&#39;latest_&#39;, &#39;&#39;), [&#39;id&#39;])<br><br>    def remove_duplicate_primary_keys(self, df, table_name):<br>        &quot;&quot;&quot;Remove rows with duplicate primary keys, defaulting to the first column if necessary.&quot;&quot;&quot;<br>        try:<br>            # Get primary keys for the table<br>            primary_keys = self.get_primary_keys(table_name)<br><br>            if not primary_keys:<br>                print(f&quot;Warning: No primary keys found or defined for {table_name}. Skipping deduplication.&quot;)<br>                return df<br><br>            # Ensure all primary keys exist in the DataFrame<br>            missing_keys = [key for key in primary_keys if key not in df.columns]<br>            if missing_keys:<br>                print(f&quot;Error: Missing primary keys {missing_keys} in table {table_name}.&quot;)<br>                return df<br><br>            # Deduplicate based on primary keys<br>            if &quot;LOADED_AT&quot; in df.columns:<br>                df = df.sort_values(by=&quot;LOADED_AT&quot;, ascending=False)<br>            else:<br>                print(f&quot;Warning: No valid date column found for {table_name}. Proceeding without sorting.&quot;)<br>            df = df.drop_duplicates(subset=primary_keys, keep=&quot;first&quot;)<br>            return df<br>        except Exception as e:<br>            print(f&quot;Error removing duplicate primary keys for {table_name}: {str(e)}&quot;)<br>            raise<br>        <br>    def transform_data(self, df, table_name):<br>        &quot;&quot;&quot;Transform data with enhanced column handling and debugging&quot;&quot;&quot;<br>        try:<br>            print(f&quot;\nDETAILED COLUMN ANALYSIS FOR {table_name}&quot;)<br>            print(&quot;=&quot; * 50)<br>            <br>            # Print initial column state<br>            print(&quot;Initial columns with types:&quot;)<br>            for col in df.columns:<br>                print(f&quot;- {col}: {df[col].dtype}&quot;)<br>            <br>            # Handle datetime columns before any other transformations<br>            date_columns = df.select_dtypes(include=[&#39;datetime64&#39;]).columns<br>            for col in date_columns:<br>                # Convert to pandas datetime with error handling<br>                try:<br>                    df[col] = pd.to_datetime(df[col], errors=&#39;coerce&#39;)<br>                    # Convert to string format<br>                    df[col] = df[col].dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>                except Exception as e:<br>                    print(f&quot;Warning: Error converting datetime column {col}: {str(e)}&quot;)<br>                    # If conversion fails, keep original values<br>                    continue<br>                <br>            # Check for and handle duplicate columns<br>            duplicate_cols = df.columns[df.columns.duplicated(keep=False)]<br>            if len(duplicate_cols) &gt; 0:<br>                print(&quot;\nFound duplicate columns:&quot;)<br>                for col in duplicate_cols:<br>                    print(f&quot;- {col}&quot;)<br>                    <br>                # Create a mapping of duplicate columns to their first occurrence<br>                col_mapping = {}<br>                for col in df.columns:<br>                    if col in duplicate_cols:<br>                        if col not in col_mapping:<br>                            col_mapping[col] = f&quot;{col}_1&quot;<br>                        else:<br>                            count = len([k for k in col_mapping.values() if k.startswith(col)]) + 1<br>                            col_mapping[col] = f&quot;{col}_{count}&quot;<br>                    else:<br>                        col_mapping[col] = col<br>                        <br>                # Rename columns using the mapping<br>                df.columns = [col_mapping[col] for col in df.columns]<br>                <br>                print(&quot;\nRenamed duplicate columns:&quot;)<br>                for old_col, new_col in col_mapping.items():<br>                    if old_col in duplicate_cols:<br>                        print(f&quot;- {old_col} -&gt; {new_col}&quot;)<br>            <br>            # Flatten JSON if needed<br>            df = self.flatten_json_df(df, table_name)<br>            <br>            # Add metadata columns<br>            df[&#39;DATA_SOURCE&#39;] = &#39;historic&#39;<br>            df[&#39;BATCH_ID&#39;] = self.batch_id<br>            df[&#39;LOADED_AT&#39;] = self.batch_timestamp.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>            <br>            # Handle NA/NaT values<br>            df = df.replace({pd.NA: None, pd.NaT: None})<br>            <br>            # Convert column names to uppercase<br>            df.columns = [col.upper() for col in df.columns]<br>            df = self.remove_duplicate_primary_keys(df, table_name)<br>            print(&quot;\nFinal columns:&quot;)<br>            print(df.columns.tolist())<br>            <br>            # Verify no duplicates remain<br>            if df.columns.duplicated().any():<br>                duplicates = df.columns[df.columns.duplicated()].tolist()<br>                raise Exception(f&quot;Duplicate columns still exist after transformation: {duplicates}&quot;)<br>            <br>            return df<br>            <br>        except Exception as e:<br>            print(f&quot;Transform error for {table_name}: {str(e)}&quot;)<br>            print(&quot;Full column list at error:&quot;)<br>            print(df.columns.tolist())<br>            raise<br><br><br>    def flatten_json_df(self, df, table_name):<br>        &quot;&quot;&quot;Flatten nested JSON structures&quot;&quot;&quot;<br>        try:<br>            json_columns = [<br>                col for col in df.columns <br>                if df[col].dtype == &#39;object&#39; and <br>                isinstance(df[col].dropna().iloc[0] if not df[col].isna().all() else None, (dict, list))<br>            ]<br>            <br>            if not json_columns:<br>                return df<br><br>            flat_df = df.copy()<br>            <br>            for col in json_columns:<br>                try:<br>                    if isinstance(df[col].dropna().iloc[0], dict):<br>                        flattened = pd.json_normalize(df[col].dropna(), sep=&#39;_&#39;)<br>                        flat_df = flat_df.drop(columns=[col])<br>                        for new_col in flattened.columns:<br>                            flat_df[f&quot;{col}_{new_col}&quot;] = flattened[new_col]<br>                    elif isinstance(df[col].dropna().iloc[0], list):<br>                        flat_df[col] = df[col].apply(lambda x: json.dumps(x) if isinstance(x, list) else x)<br>                except Exception as e:<br>                    print(f&quot;Warning: Could not flatten column {col}: {str(e)}&quot;)<br>                    continue<br>            <br>            return flat_df<br>        except Exception as e:<br>            print(f&quot;JSON flattening error for {table_name}: {str(e)}&quot;)<br>            raise<br><br>    def save_to_s3_historic(self, df, table_name, metadata):<br>        &quot;&quot;&quot;Save transformed data and metadata to S3 historic bucket&quot;&quot;&quot;<br>        try:<br>            # Save as CSV<br>            csv_buffer = io.StringIO()<br>            df.to_csv(csv_buffer, index=False)<br>            <br>            # Save to historic data folder<br>            self.s3_client.put_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}.csv&#39;,<br>                Body=csv_buffer.getvalue().encode(&#39;utf-8&#39;)<br>            )<br>            <br>            # Save metadata<br>            self.s3_client.put_object(<br>                Bucket=self.historic_bucket,<br>                Key=f&#39;csv/{table_name}_metadata.json&#39;,<br>                Body=json.dumps(metadata, default=str)<br>            )<br>            <br>            print(f&quot;Successfully saved {table_name} to historic bucket as CSV with metadata&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;Error saving to S3 historic bucket: {str(e)}&quot;)<br>            raise<br><br>    def load_to_snowflake(self, df, table_name):<br>        &quot;&quot;&quot;Incrementally load data to Snowflake handling duplicates properly&quot;&quot;&quot;<br>        try:<br>            database = os.getenv(&#39;SNOWFLAKE_DATABASE&#39;)<br>            schema = os.getenv(&#39;SNOWFLAKE_RAW_SCHEMA&#39;)<br>            full_table_name = f&quot;{database}.{schema}.{table_name.upper()}&quot;<br>            temp_table_name = f&quot;{database}.{schema}.TEMP_{table_name.upper()}&quot;<br>            <br>            # Get primary keys<br>            primary_keys = [pk.upper() for pk in self.get_primary_keys(table_name)]<br><br>            # Create temporary table for staging the new data<br>            column_definitions = []<br>            for col_name, dtype in df.dtypes.items():<br>                sf_type = &quot;VARCHAR&quot;<br>                if pd.api.types.is_integer_dtype(dtype):<br>                    sf_type = &quot;NUMBER&quot;<br>                elif pd.api.types.is_float_dtype(dtype):<br>                    sf_type = &quot;FLOAT&quot;<br>                elif pd.api.types.is_datetime64_any_dtype(dtype):<br>                    sf_type = &quot;TIMESTAMP&quot;<br>                column_definitions.append(f&#39;&quot;{col_name}&quot; {sf_type}&#39;)<br><br>            # Drop temp table if exists<br>            self.snow_cursor.execute(f&quot;DROP TABLE IF EXISTS {temp_table_name}&quot;)<br><br>            # Create temp table<br>            create_temp_table_sql = f&quot;&quot;&quot;<br>            CREATE TEMPORARY TABLE {temp_table_name} (<br>                {&#39;, &#39;.join(column_definitions)}<br>            )<br>            &quot;&quot;&quot;<br>            self.snow_cursor.execute(create_temp_table_sql)<br><br>            # Load data into temp table<br>            success, num_chunks, num_rows, _ = write_pandas(<br>                conn=self.snow_conn,<br>                df=df,<br>                table_name=f&quot;TEMP_{table_name.upper()}&quot;,<br>                database=database,<br>                schema=schema,<br>                quote_identifiers=False<br>            )<br><br>            if not success:<br>                raise Exception(f&quot;Failed to load data to temporary table for {table_name}&quot;)<br><br>            # Create target table if it doesn&#39;t exist<br>            create_table_sql = f&quot;&quot;&quot;<br>            CREATE TABLE IF NOT EXISTS {full_table_name} (<br>                {&#39;, &#39;.join(column_definitions)}<br>            )<br>            &quot;&quot;&quot;<br>            self.snow_cursor.execute(create_table_sql)<br><br>            # Get all columns except metadata for comparison<br>            compare_columns = [col for col in df.columns if col.upper() not in [&#39;DATA_SOURCE&#39;, &#39;BATCH_ID&#39;, &#39;LOADED_AT&#39;]]<br>            <br>            # Build comparison conditions for each non-metadata column<br>            comparison_conditions = []<br>            for col in compare_columns:<br>                condition = f&quot;&quot;&quot;<br>                (<br>                    target.&quot;{col}&quot; != source.&quot;{col}&quot;<br>                    OR (target.&quot;{col}&quot; IS NULL AND source.&quot;{col}&quot; IS NOT NULL)<br>                    OR (target.&quot;{col}&quot; IS NOT NULL AND source.&quot;{col}&quot; IS NULL)<br>                )<br>                &quot;&quot;&quot;<br>                comparison_conditions.append(condition)<br><br>            # Join all comparison conditions with OR<br>            comparison_clause = &quot; OR &quot;.join(comparison_conditions)<br><br>            # Construct MERGE statement<br>            merge_sql = f&quot;&quot;&quot;<br>            MERGE INTO {full_table_name} target<br>            USING (<br>                SELECT *,<br>                    ROW_NUMBER() OVER (<br>                        PARTITION BY {&#39;, &#39;.join([f&#39;&quot;{pk}&quot;&#39; for pk in primary_keys])}<br>                        ORDER BY &quot;LOADED_AT&quot; DESC<br>                    ) as rn<br>                FROM {temp_table_name}<br>            ) source<br>            ON {&#39; AND &#39;.join([f&#39;target.&quot;{pk}&quot; = source.&quot;{pk}&quot;&#39; for pk in primary_keys])}<br>            AND source.rn = 1<br>            WHEN MATCHED AND ({comparison_clause})<br>            THEN UPDATE SET<br>                {&#39;, &#39;.join([f&#39;&quot;{col}&quot; = source.&quot;{col}&quot;&#39; for col in df.columns])}<br>            WHEN NOT MATCHED AND source.rn = 1<br>            THEN INSERT (<br>                {&#39;, &#39;.join([f&#39;&quot;{col}&quot;&#39; for col in df.columns])}<br>            )<br>            VALUES (<br>                {&#39;, &#39;.join([f&#39;source.&quot;{col}&quot;&#39; for col in df.columns])}<br>            )<br>            &quot;&quot;&quot;<br><br>            # Execute merge<br>            self.snow_cursor.execute(merge_sql)<br><br>            # Clean up temp table<br>            self.snow_cursor.execute(f&quot;DROP TABLE IF EXISTS {temp_table_name}&quot;)<br><br>            print(f&quot;&quot;&quot;Successfully loaded data to {full_table_name}:<br>            - Rows processed: {num_rows}<br>            - Using primary keys: {&#39;, &#39;.join(primary_keys)}&quot;&quot;&quot;)<br><br>        except Exception as e:<br>            print(f&quot;Error loading to Snowflake: {str(e)}&quot;)<br>            raise<br>        <br>    def get_date_column(self, table_name):<br>        &quot;&quot;&quot;Return the appropriate date column for each table with fallbacks&quot;&quot;&quot;<br>        date_columns = {<br>            &#39;customers&#39;: [&#39;signup_date&#39;, &#39;last_login&#39;, &#39;created_at&#39;],<br>            &#39;orders&#39;: [&#39;order_date&#39;, &#39;created_at&#39;, &#39;updated_at&#39;],<br>            &#39;products&#39;: [&#39;created_at&#39;],<br>            &#39;order_items&#39;: [&#39;created_at&#39;, &#39;order_date&#39;],<br>            &#39;reviews&#39;: [&#39;created_at&#39;, &#39;order_date&#39;],<br>            &#39;interactions&#39;: [&#39;event_date&#39;, &#39;created_at&#39;],<br>            &#39;categories&#39;: [&#39;created_at&#39;],<br>            &#39;subcategories&#39;: [&#39;created_at&#39;]<br>        }<br>        <br>        clean_table_name = table_name.replace(&#39;latest_&#39;, &#39;&#39;)<br>        return date_columns.get(clean_table_name, [&#39;created_at&#39;])<br><br>    def find_valid_date_column(self, df, table_name):<br>        &quot;&quot;&quot;Find the first valid date column from the possible options&quot;&quot;&quot;<br>        possible_columns = self.get_date_column(table_name)<br>        <br>        for col in possible_columns:<br>            if col in df.columns:<br>                return col<br>                <br>        return None<br>        <br>    def run_etl(self):<br>        &quot;&quot;&quot;Execute ETL process with historic CSV data&quot;&quot;&quot;<br>        try:<br>            print(&quot;\nStarting ETL process...&quot;)<br>            <br>            # Create local directory for CSV files if it doesn&#39;t exist<br>            os.makedirs(&quot;ingested_data&quot;, exist_ok=True)<br>            <br>            for table in self.postgres_tables + self.s3_tables:<br>                print(f&quot;\nProcessing {table}&quot;)<br>                <br>                try:<br>                    # Extract historic data from S3 CSV<br>                    historic_df = self.extract_historic_from_s3(table)<br>                    <br>                    # Extract latest data from original sources<br>                    latest_df = (self.extract_latest_from_s3(table) <br>                            if table in self.s3_tables <br>                            else self.extract_latest_from_postgres(table))<br>                    <br>                    # Transform data before date handling<br>                    latest_transformed_df = self.transform_data(latest_df, table)<br>                    historic_transformed_df = self.transform_data(historic_df, table)<br>                    <br>                    # Find valid date column<br>                    date_column = self.find_valid_date_column(latest_transformed_df, table)<br>                    <br>                    if date_column:<br>                        try:<br>                            # Convert date columns to datetime for comparison<br>                            latest_transformed_df[date_column] = pd.to_datetime(latest_transformed_df[date_column])<br>                            historic_transformed_df[date_column] = pd.to_datetime(historic_transformed_df[date_column])<br>                            <br>                            min_latest_date = latest_transformed_df[date_column].min()<br>                            print(f&quot;Latest data starts from: {min_latest_date}&quot;)<br>                            <br>                            if date_column in historic_transformed_df.columns:<br>                                historic_transformed_df = historic_transformed_df[<br>                                    historic_transformed_df[date_column] &lt; min_latest_date<br>                                ]<br>                            <br>                            # Convert back to string format for consistency<br>                            latest_transformed_df[date_column] = latest_transformed_df[date_column].dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>                            historic_transformed_df[date_column] = historic_transformed_df[date_column].dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>                        except Exception as e:<br>                            print(f&quot;Warning: Error processing date column {date_column}: {str(e)}&quot;)<br>                            # Continue without date filtering if there&#39;s an error<br>                            min_latest_date = None<br>                    else:<br>                        print(f&quot;Warning: No valid date column found for {table}&quot;)<br>                        min_latest_date = None<br>                    <br>                    # Get primary keys for deduplication<br>                    primary_keys = self.get_primary_keys(table)<br>                    <br>                    # Combine data<br>                    combined_df = pd.concat([historic_transformed_df, latest_transformed_df], ignore_index=True)<br><br>                    print(f&quot;Removed {len(historic_transformed_df) + len(latest_transformed_df) - len(combined_df)} duplicate records&quot;)<br>                    <br>                    # Save to local CSV<br>                    combined_path = f&quot;ingested_data/{table}_combined.csv&quot;<br>                    combined_df.to_csv(combined_path, index=False)<br>                    print(f&quot;Saved combined data to {combined_path}&quot;)<br>                    <br>                    # Prepare metadata<br>                    metadata = {<br>                        &#39;table_name&#39;: table,<br>                        &#39;batch_id&#39;: self.batch_id,<br>                        &#39;timestamp&#39;: str(self.batch_timestamp),<br>                        &#39;historic_records&#39;: len(historic_transformed_df),<br>                        &#39;latest_records&#39;: len(latest_transformed_df),<br>                        &#39;total_records&#39;: len(combined_df),<br>                        &#39;removed_duplicates&#39;: len(historic_transformed_df) + len(latest_transformed_df) - len(combined_df),<br>                        &#39;date_column_used&#39;: date_column,<br>                        &#39;primary_keys_used&#39;: primary_keys,<br>                        &#39;columns&#39;: combined_df.columns.tolist(),<br>                        &#39;data_types&#39;: {col: str(dtype) for col, dtype in combined_df.dtypes.items()},<br>                        &#39;min_date&#39;: str(min_latest_date) if min_latest_date is not None else None<br>                    }<br>                    <br>                    # Save to S3 as historic data<br>                    self.save_to_s3_historic(combined_df, table, metadata)<br>                    <br>                    # Load to Snowflake<br>                    self.load_to_snowflake(combined_df, table)<br>                    <br>                    print(f&quot;&quot;&quot;<br>                    Completed processing for {table}:<br>                    - Historic records: {len(historic_transformed_df)}<br>                    - Latest records: {len(latest_transformed_df)}<br>                    - Duplicates removed: {len(historic_transformed_df) + len(latest_transformed_df) - len(combined_df)}<br>                    - Total records processed: {len(combined_df)}<br>                    - Date column used: {date_column if date_column else &#39;None&#39;}<br>                    - Primary keys used: {&#39;, &#39;.join(primary_keys)}<br>                    - Data saved locally to: {combined_path}<br>                    - Data saved to S3 historic bucket<br>                    - Data loaded to Snowflake table: {table.upper()}<br>                    &quot;&quot;&quot;)<br><br>                except Exception as e:<br>                    print(f&quot;Error processing table {table}: {str(e)}&quot;)<br>                    continue<br><br>        except Exception as e:<br>            print(f&quot;ETL process error: {str(e)}&quot;)<br>            raise<br>        finally:<br>            self.snow_cursor.close()<br>            self.snow_conn.close()<br>            print(&quot;\nETL process completed. Connections closed.&quot;)<br>        <br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        etl = IncrementalETL()<br>        etl.run_etl()<br>    except Exception as e:<br>        print(f&quot;Main execution error: {str(e)}&quot;)<br>        raise</pre><p>2. Check if the ingested_data csv files and historic-ecom/csv files have been recently updated. They are just exact copies of the initial append output data.</p><p>Example log:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*x1OR3x3ZzfxtDykvk-zaRg.png" /></figure><p>Example output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNpwgnkPwFmDmDXb4T__Lw.png" /></figure><p>3. Run more queries on Snowflake to inspect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OJ70KK38yfrbrU38IlX_Q.png" /></figure><h3>IV. Data Transformation &amp; Modeling</h3><p>GitHub branch to follow: <a href="https://github.com/sclauguico/ecommerce-modern-data-stack/tree/4-data-transformation-modeling">https://github.com/sclauguico/ecommerce-modern-data-stack/tree/4-data-transformation-modeling</a></p><p>Steps:</p><ol><li>Delete the example folder under ecom_dbt &gt; ecom_data_model &gt; models.</li></ol><p>2. Add three folders under models.</p><ul><li>staging</li><li>intermediate</li><li>marts</li><li>Folder structure:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*Gif0e84SUgF5DKSvTNe8sA.png" /></figure><h3>1. Staging</h3><p>Steps:</p><ol><li>Copy all sql and yml files from this git branch <a href="https://github.com/sclauguico/ecommerce-modern-data-stack/tree/4-data-transformation-modeling/ecom_dbt/ecom_data_model/models/ecom_staging">ecom_staging folder</a></li></ol><p>Note: Linking the main branch folder here due to model changes. For project directory guide, follow through branch 4-data-transformation-modeling.</p><p>2. Copy also the dbt_project.yml file and place as shown in the directory above.</p><p>3. Modify the schema on profiles.yml to:</p><pre>schema: ECOM_STAGING</pre><p>4. cd into ecom_dbt/ecom_data_model and run staging models:</p><pre>dbt run --select models/ecom_staging/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0wRAWDodG8APhvsIju62Q.png" /></figure><p>5. Test staging models</p><pre>dbt test --select ecom_staging.* --debug</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1S4rPYIwcy87nWw34XsjuA.png" /></figure><p>6. Check the staging models on Snowflake and run some queries to test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3K2PEaTl4rSKFbvpLypDLQ.png" /></figure><p>The ECOM_STAGING data follows the following data model. <a href="https://dbdiagram.io/d/ecom_staging_schema-677226415406798ef7e4c827">See model in detail here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfWGko6z5XZJwY2BMpgsLw.png" /></figure><h3>2. Intermediate</h3><p>Steps:</p><ol><li>Copy all the folder structure, sql, and yml files from this git branch <a href="https://github.com/sclauguico/ecommerce-modern-data-stack/tree/main/ecom_dbt/ecom_data_model/models/ecom_intermediate">ecom_intermediate folder</a>.</li></ol><p>Note: Linking the main branch folder here due to model changes. For project directory guide, follow through branch 4-data-transformation-modeling</p><p>2. Modify the schema on profiles.yml to:</p><pre>schema: ECOM_INTERMEDIATE</pre><p>3. cd into ecom_dbt/ecom_data_model and run intermediate models:</p><pre>dbt run --select models/ecom_intermediate/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mGVq5JarYp7ad8PPcEjyQ.png" /></figure><p>4. Test intermediate models:</p><pre>dbt test --select ecom_intermediate.* --debug</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TziHByOn4LGDkkHk-XnYew.png" /></figure><p>5. Check the intermediate models on Snowflake and run some queries to test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRq6AhnzIf_qcCbHfFlcSw.png" /></figure><p>The ECOM_INTERMEDIATE data follows the following data model. <a href="https://dbdiagram.io/d/ecom_int_schema-676a832f5406798ef78acaf7">See model in detail here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1MLaVfgm2Ca7TNqtas0PQ.png" /></figure><h3>3. Marts</h3><ol><li>Copy all the folder structure, sql, and yml files from this git branch <a href="https://github.com/sclauguico/ecommerce-modern-data-stack/tree/main/ecom_dbt/ecom_data_model/models/ecom_marts">ecom_marts folder</a>.</li></ol><p>Note: Linking the main branch folder here due to model changes. For project directory guide, follow through branch 4-data-transformation-modeling</p><p>2. Modify the schema on profiles.yml to:</p><pre>schema: ECOM_MARTS</pre><p>3. cd into ecom_dbt/ecom_data_model and run marts models:</p><pre>dbt run --select models/ecom_marts/</pre><p>4. Test marts models</p><pre>dbt test --select ecom_marts.* --debug</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iV6dlXPkZ5B8hSsQ3rnd8g.png" /></figure><p>5. Check the marts models on Snowflake and run some queries to test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3H1aNWxWvnvds-GXbNjSYw.png" /></figure><p>The ECOM_MARTS data follows the following data model. <a href="https://dbdiagram.io/d/ecom_marts_schema-676d61de5406798ef7b14873">See model in detail here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Koy9SKXT7xRX9vyxAnFA7w.png" /></figure><h3>V. Orchestration</h3><p>GitHub branch to follow: <a href="https://github.com/sclauguico/ecommerce-modern-data-stack/tree/5-orchestration">https://github.com/sclauguico/ecommerce-modern-data-stack/tree/5-orchestration</a></p><h3>1. Generation and Ingestion</h3><p>Steps:</p><ol><li>Copy the src folder under ecom_airflow &gt; dags</li><li>Remove the python files starting with 0_. These files will not be orchestrated.</li><li>Under the dags folder, create a file gen_latest_synth_dag.py</li></ol><pre>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from datetime import datetime, timedelta<br>import os<br>import sys<br>from pathlib import Path<br><br>from src.pipeline.generate_latest_synthetic_data import RecentEcommerceDataGenerator, save_data<br>from src.pipeline.ingest_latest_synthetic_data import IncrementalETL<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: datetime(2024, 12, 1),<br>    &#39;email_on_failure&#39;: True,<br>    &#39;email_on_retry&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>}<br><br>dag = DAG(<br>    &#39;generate_append_latest_pipeline&#39;,<br>    default_args=default_args,<br>    description=&#39;E-commerce data generation and ETL pipeline&#39;,<br>    schedule_interval=&#39;0 0 * * *&#39;,  # Run daily at midnight<br>    catchup=False<br>)<br><br>def generate_latest_data(**context):<br>    &quot;&quot;&quot;Generate latest synthetic e-commerce data&quot;&quot;&quot;<br>    try:<br>        generator = RecentEcommerceDataGenerator()<br>        data = generator.generate_all_data()<br>        <br>        # Save data directly to S3 and PostgreSQL<br>        save_data(data)<br>        <br>        print(&quot;Latest data generation completed successfully&quot;)<br>        return True<br>    except Exception as e:<br>        print(f&quot;Error in generate_latest_data: {str(e)}&quot;)<br>        raise<br><br>def ingest_etl(**context):<br>    &quot;&quot;&quot;Process ETL pipeline&quot;&quot;&quot;<br>    try:<br>        etl = IncrementalETL()<br>        etl.run_etl()<br>        print(&quot;ETL processing completed successfully&quot;)<br>        return True<br>    except Exception as e:<br>        print(f&quot;Error in ingest_etl: {str(e)}&quot;)<br>        raise<br><br># Define tasks<br>generate_data_task = PythonOperator(<br>    task_id=&#39;generate_latest_data&#39;,<br>    python_callable=generate_latest_data,<br>    provide_context=True,<br>    dag=dag,<br>)<br><br>ingest_etl_task = PythonOperator(<br>    task_id=&#39;process_etl&#39;,<br>    python_callable=ingest_etl,<br>    provide_context=True,<br>    dag=dag,<br>)<br><br># Set task dependencies<br>generate_data_task &gt;&gt; ingest_etl_task</pre><p>3. Modify the Postgres credentials on the .env file inside ecom_airflow.</p><pre>POSTGRES_HOST=db<br>POSTGRES_DB=ecom_db_source<br>POSTGRES_USER=root<br>POSTGRES_PASSWORD=root<br>POSTGRES_PORT=5432</pre><p>4. Modify the docker-compose.yml to add networks.</p><pre>services:<br>  db:<br>    container_name: postgres_cont<br>    image: postgres<br>    restart: always<br>    environment:<br>      POSTGRES_USER: root<br>      POSTGRES_PASSWORD: root<br>      POSTGRES_DB: ecom_db_source<br>    ports:<br>      - &quot;5433:5432&quot;<br>    volumes:<br>      - postgres_db_source_data:/var/lib/postgresql/data<br>    networks:<br>      - ecommerce-modern-data-stack_4b35e1_airflow<br><br>  pgadmin:<br>    container_name: pgadmin4_cont<br>    image: dpage/pgadmin4<br>    restart: always<br><br>    environment:<br>      PGADMIN_DEFAULT_EMAIL: admin@admin.com<br>      PGADMIN_DEFAULT_PASSWORD: root<br>    ports:<br>      - &quot;5050:80&quot;<br>    volumes:<br>      - pgadmin_data:/var/lib/pgadmin<br>    depends_on:<br>      - db<br>    networks:<br>      - ecommerce-modern-data-stack_4b35e1_airflow<br><br>volumes:<br>  postgres_db_source_data:<br>  pgadmin_data:<br><br>networks:<br>  ecommerce-modern-data-stack_4b35e1_airflow:<br>    external: true</pre><p>Note: Run to determine network:</p><pre>docker network ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-4Hp0NQARxSaT-DNwzRRQ.png" /></figure><p>5. Run Postgres and pgAdmin containers. Run Airflow and open the Airflow UI:</p><pre>astro dev start</pre><p>6. Create connections by navigating to Admin &gt; Connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOvudPjMTX2uB_j3DohFug.png" /></figure><p>7. Click on the plus sign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-s_ZmJFeVJ6RJHwluPu2Tg.png" /></figure><p>8. Create the following connections. Configure as shown and save.</p><ul><li>postgres_conn setup</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*5KupHw3dj40cOwxi_DEw2Q.png" /></figure><ul><li>s3_conn setup and add your AWS credentials</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*4-34YCirirsqHknd6tGwpw.png" /></figure><ul><li>snowflake_conn</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*Cf7vdCz2a9wgXula_IqA9Q.png" /></figure><p>9. Check the latest data on ECOM_RAW. On the example below, the latest date is 2024–12–30 or Dec 30, 2024.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmbFYWSKvlZjAN8z8J4Lig.png" /></figure><p>10. Navigate back to the DAGs tab. Click on the toggle button and click on the Trigger DAG button to manually run, then click on the DAG name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e21jB5oZzkBJ130nGoz24Q.png" /></figure><p>11. Check logs by clicking on the box boxed in red</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PvfOCtl6maCNU1Wd7AO6LQ.png" /></figure><p>12. Check historic-ecom &gt; csv data files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbARjvPldnyXoVXrmUJCdA.png" /></figure><p>13. Check the ingestion to Snowflake task logs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHhgqaPO0wK8kEmJoZUGZQ.png" /></figure><p>14. Rerun the orders query in step 9. Latest date is updated to 2025–01–01 or Jan 1, 2025.</p><p>Note: This was tested the following day from the initial load to Snowflake ECOM_RAW.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZslhU-JhygPq_rSF7hHrA.png" /></figure><h3>2. Transformation</h3><ol><li>Add the following on ecom_airflow &gt; Dockerfile</li></ol><pre>RUN python -m venv dbt_venv &amp;&amp; source dbt_venv/bin/activate &amp;&amp; \\     pip install --no-cache-dir dbt-snowflake &amp;&amp; deactivate</pre><p>2. In this section, we will separate the staging, intermediate, and marts models’ dbt project setup inside the ecom_airflow directory. This can be done by executing section I.11 three times for each of the schema. But for this demonstration, a faster way of doing this is to:</p><ul><li>Create a folder named dbt under ecom_airflow &gt; dags.</li><li>Copy the original ecom_dbt under it and rename to ecom_staging</li><li>Delete the ecom_intermediate and ecom_marts models inside it</li><li>Ensure all configurations are setup for ecom_staging such as in profiles.yml</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*yYFi6vskqXLOaMmGUOxd2A.png" /></figure><p>Note: Review branch to replicate implementation.</p><p>3. Repeat the steps for ecom_intermediate and ecom_marts, creating the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*squot1l191a5i0MXplctzg.png" /></figure><p>4. Create the following DAG files under ecom_airflow &gt; dags. Review the code and modify as needed:</p><ul><li>dbt_staging_dag.py</li></ul><pre>import os<br>from datetime import datetime<br>from cosmos import DbtDag, ProjectConfig, ProfileConfig, ExecutionConfig<br>from cosmos.profiles import SnowflakeUserPasswordProfileMapping<br>from dotenv import load_dotenv<br><br># Load environment variables<br>load_dotenv()<br><br>snowflake_base_config = {<br>    &quot;type&quot;: &quot;snowflake&quot;,<br>    &quot;account&quot;: os.getenv(&quot;SNOWFLAKE_ACCOUNT&quot;),<br>    &quot;warehouse&quot;: os.getenv(&quot;SNOWFLAKE_WAREHOUSE&quot;),<br>    &quot;database&quot;: os.getenv(&quot;SNOWFLAKE_DATABASE&quot;),<br>    &quot;role&quot;: os.getenv(&quot;SNOWFLAKE_ROLE&quot;),<br>    &quot;schema&quot;: &quot;ECOM_STAGING&quot;,<br>    &quot;threads&quot;: 10<br>}<br><br># Profile config for staging schema<br>staging_profile_config = ProfileConfig(<br>    profile_name=&quot;ecom_staging&quot;,<br>    target_name=&quot;dev&quot;,<br>    profile_mapping=SnowflakeUserPasswordProfileMapping(<br>        conn_id=&quot;snowflake_conn&quot;,<br>        profile_args=snowflake_base_config<br>    )<br>)<br><br># Create DAG for staging models<br>staging_dag = DbtDag(<br>    project_config=ProjectConfig(<br>        dbt_project_path=&quot;/usr/local/airflow/dags/dbt/ecom_staging&quot;<br>    ),<br>    operator_args={<br>        &quot;install_deps&quot;: True,<br>        &quot;models&quot;: &quot;stg_*&quot;,<br>        &quot;full_refresh&quot;: True<br>    },<br>    profile_config=staging_profile_config,<br>    execution_config=ExecutionConfig(<br>        dbt_executable_path=f&quot;{os.environ[&#39;AIRFLOW_HOME&#39;]}/dbt_venv/bin/dbt&quot;<br>    ),<br>    schedule_interval=&quot;@daily&quot;,<br>    start_date=datetime(2024, 12, 1),<br>    catchup=False,<br>    dag_id=&quot;dbt_staging_dag&quot;,<br>)</pre><ul><li>dbt_intermediate_dag.py</li></ul><pre>import os<br>from datetime import datetime<br>from cosmos import DbtDag, ProjectConfig, ProfileConfig, ExecutionConfig<br>from cosmos.profiles import SnowflakeUserPasswordProfileMapping<br>from dotenv import load_dotenv<br><br># Load environment variables<br>load_dotenv()<br><br>snowflake_base_config = {<br>    &quot;type&quot;: &quot;snowflake&quot;,<br>    &quot;account&quot;: os.getenv(&quot;SNOWFLAKE_ACCOUNT&quot;),<br>    &quot;warehouse&quot;: os.getenv(&quot;SNOWFLAKE_WAREHOUSE&quot;),<br>    &quot;database&quot;: os.getenv(&quot;SNOWFLAKE_DATABASE&quot;),<br>    &quot;role&quot;: os.getenv(&quot;SNOWFLAKE_ROLE&quot;),<br>    &quot;schema&quot;: &quot;ECOM_INTERMEDIATE&quot;,<br>    &quot;threads&quot;: 10<br>}<br><br># Profile config for intermediate schema<br>intermediate_profile_config = ProfileConfig(<br>    profile_name=&quot;ecom_intermediate&quot;,<br>    target_name=&quot;dev&quot;,<br>    profile_mapping=SnowflakeUserPasswordProfileMapping(<br>        conn_id=&quot;snowflake_conn&quot;,<br>        profile_args=snowflake_base_config<br>    )<br>)<br><br># Create DAG for intermediate models<br>intermediate_dag = DbtDag(<br>    project_config=ProjectConfig(<br>        dbt_project_path=&quot;/usr/local/airflow/dags/dbt/ecom_intermediate&quot;<br>    ),<br>    operator_args={<br>        &quot;install_deps&quot;: True,<br>        &quot;full_refresh&quot;: True<br>    },<br>    profile_config=intermediate_profile_config,<br>    execution_config=ExecutionConfig(<br>        dbt_executable_path=f&quot;{os.environ[&#39;AIRFLOW_HOME&#39;]}/dbt_venv/bin/dbt&quot;<br>    ),<br>    schedule_interval=&quot;@daily&quot;,<br>    start_date=datetime(2024, 12, 1),<br>    catchup=False,<br>    dag_id=&quot;dbt_intermediate_dag&quot;,<br>)</pre><ul><li>dbt_marts_dag.py</li></ul><pre>import os<br>from datetime import datetime<br>from cosmos import DbtDag, ProjectConfig, ProfileConfig, ExecutionConfig<br>from cosmos.profiles import SnowflakeUserPasswordProfileMapping<br>from dotenv import load_dotenv<br><br># Load environment variables<br>load_dotenv()<br><br>snowflake_base_config = {<br>    &quot;type&quot;: &quot;snowflake&quot;,<br>    &quot;account&quot;: os.getenv(&quot;SNOWFLAKE_ACCOUNT&quot;),<br>    &quot;warehouse&quot;: os.getenv(&quot;SNOWFLAKE_WAREHOUSE&quot;),<br>    &quot;database&quot;: os.getenv(&quot;SNOWFLAKE_DATABASE&quot;),<br>    &quot;role&quot;: os.getenv(&quot;SNOWFLAKE_ROLE&quot;),<br>    &quot;schema&quot;: &quot;ECOM_MARTS&quot;,<br>    &quot;threads&quot;: 10<br>}<br><br># Profile config for marts schema<br>marts_profile_config = ProfileConfig(<br>    profile_name=&quot;ecom_marts&quot;,<br>    target_name=&quot;dev&quot;,<br>    profile_mapping=SnowflakeUserPasswordProfileMapping(<br>        conn_id=&quot;snowflake_conn&quot;,<br>        profile_args=snowflake_base_config<br>    )<br>)<br><br># Create DAG for marts models<br>marts_dag = DbtDag(<br>    project_config=ProjectConfig(<br>        dbt_project_path=&quot;/usr/local/airflow/dags/dbt/ecom_marts&quot;<br>    ),<br>    operator_args={<br>        &quot;install_deps&quot;: True,<br>        &quot;full_refresh&quot;: True<br>    },<br>    profile_config=marts_profile_config,<br>    execution_config=ExecutionConfig(<br>        dbt_executable_path=f&quot;{os.environ[&#39;AIRFLOW_HOME&#39;]}/dbt_venv/bin/dbt&quot;<br>    ),<br>    schedule_interval=&quot;@daily&quot;,<br>    start_date=datetime(2024, 12, 1),<br>    catchup=False,<br>    dag_id=&quot;dbt_marts_dag&quot;,<br>)</pre><p>5. Open and refresh the Airflow UI.</p><p>6. Run the staging DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kgk9vlfgegbyaN4aAjgkhg.png" /></figure><p>7. Run the intermediate DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jP9VNK1lwk3wPTRJdbv_VQ.png" /></figure><p>8. Run the marts DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5spsRlP-JxJVPWG5jJdIw.png" /></figure><h3>Wrapping Up</h3><p>This concludes the implementation section of the eCommerce data engineering solution. I hope you found this article insightful and inspiring for your own projects!</p><p>If you have suggestions for improvement, ideas to enhance the solution, or creative ways to expand its functionality, feel free to contribute by creating pull requests (PRs). Collaboration and feedback are always welcome to refine and evolve this solution further.</p><figure><a href="https://buymeacoffee.com/sai_documents"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*qWc87FphzPYiLnRQABa4qg.png" /></a></figure><p>Or connect with me on the following:</p><p><a href="https://www.linkedin.com/in/sandy-lauguico/">https://www.linkedin.com/in/sandy-lauguico/</a></p><p><a href="https://github.com/sclauguico">https://github.com/sclauguico</a></p><p><a href="https://www.facebook.com/sandy.c.lauguico/">https://www.facebook.com/sandy.c.lauguico/</a></p><p><a href="https://www.instagram.com/sai_documents/">https://www.instagram.com/sai_documents/</a></p><p>And please give a clap (or claps) below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e874d89b9906" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>