<?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 Sophonie NGAKOUTOU GUELBE on Medium]]></title>
        <description><![CDATA[Stories by Sophonie NGAKOUTOU GUELBE on Medium]]></description>
        <link>https://medium.com/@ngakoutousophonie?source=rss-32c2d22e7db7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C6uY-dkHpPUeunX6noxGnw.jpeg</url>
            <title>Stories by Sophonie NGAKOUTOU GUELBE on Medium</title>
            <link>https://medium.com/@ngakoutousophonie?source=rss-32c2d22e7db7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:42:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ngakoutousophonie/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[Apache Superset: The Open-Source BI Platform Challenging Tableau and Power BI]]></title>
            <link>https://medium.com/@ngakoutousophonie/apache-superset-the-open-source-bi-platform-challenging-tableau-and-power-bi-e3ba78ab6063?source=rss-32c2d22e7db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3ba78ab6063</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[apache-superset]]></category>
            <dc:creator><![CDATA[Sophonie NGAKOUTOU GUELBE]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 16:41:12 GMT</pubDate>
            <atom:updated>2026-09-30T16:45:53.030Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What it is, how it works, and whether it can replace your paid dashboard tool</em></p><p>We are drowning in data. Every app click, payment, sensor reading, and support ticket gets logged somewhere, and most companies now store more data than they can reasonably look at. The bottleneck is no longer collecting information but turning it into decisions. A warehouse full of tables helps no one until someone can see what those tables say.</p><p>That is the gap business intelligence (BI) tools fill, and for years the choices were limited: pay for a proprietary platform with per-user licensing, or stitch together spreadsheets and hope for the best. <strong>Apache Superset</strong> offers a third path. It is a modern, enterprise-ready, open-source BI web application that lets teams explore data, build interactive dashboards, and share insights without paying a license fee.</p><p>Superset began as a hackathon-style side project at <strong>Airbnb</strong>, created by <strong>Maxime Beauchemin</strong> (who also created Apache Airflow) to help employees explore data at scale. Airbnb open-sourced it, it entered the Apache Incubator, and it later graduated to a <strong>top-level project of the Apache Software Foundation</strong>. Today it is used by thousands of organizations worldwide.</p><p>In this guide, I’ll walk through what Superset does, how it works under the hood, how it compares to Tableau and Power BI, and how to get started.</p><h3>The Core Problem: Why Do We Need Superset?</h3><p>Traditional BI tools are powerful, but they come with trade-offs that hurt startups and growing teams especially.</p><p><strong>1. Expensive licensing.</strong> Most commercial BI platforms charge per user, per month, often with different prices for creators, viewers, and administrators. When you want everyone in the company to see a dashboard, costs multiply fast.</p><p><strong>2. Data extracts and slow performance.</strong> Many tools copy data into their own engine to make it fast. That works until your data grows to hundreds of millions of rows. Refresh schedules lag, extracts break, and the “single source of truth” quietly becomes three slightly different versions of it.</p><p><strong>3. Limited customization.</strong> Proprietary platforms give you what the vendor built. If you need a custom authentication flow, a bespoke chart, or a dashboard embedded in your own product, you are often stuck with workarounds or premium add-ons.</p><p><strong>4. Vendor lock-in.</strong> Years of dashboards built in a closed format are hard to move.</p><p><strong>How Superset solves these problems</strong></p><ul><li><strong>No license fees.</strong> It is released under the Apache 2.0 license. You pay for infrastructure and people, not seats.</li><li><strong>It queries your database directly.</strong> There is no proprietary extract to maintain, so you get fresh data and let your warehouse do the heavy lifting.</li><li><strong>It is extensible.</strong> The code is open, the plugin system is real, and the community is large.</li><li><strong>It is portable.</strong> Your data stays in your own systems, and your definitions live in metadata you control.</li></ul><h3>Key Features and Capabilities</h3><h3>Visualization: from no-code to SQL</h3><p>Superset serves two kinds of users, and it treats both seriously.</p><p><strong>The no-code chart builder.</strong> Analysts and business users can pick a dataset, choose a chart type, drag in metrics and dimensions, and get a result without writing any SQL. The library covers dozens of chart types, including:</p><ul><li>Bar, line, area, and scatter charts</li><li>Pivot tables and heatmaps</li><li>Treemaps and sunbursts</li><li>Geospatial maps</li><li>Big number displays and gauges</li><li>Time-series charts with rolling averages and comparisons</li></ul><p><strong>SQL Lab.</strong> For people who live in SQL, SQL Lab is a browser-based IDE with multi-tab editing, autocomplete, query history, saved queries, and schema browsing. You can write a query, inspect the results, and turn them into a chart with one click. It is a nice bridge between exploration and presentation, since the query you wrote while investigating a problem becomes the foundation of the dashboard you share with the team.</p><h3>Data connectivity</h3><p>Superset connects to almost anything that speaks SQL, through <strong>SQLAlchemy </strong>and database drivers. Commonly used connections include:</p><ul><li><strong>PostgreSQL</strong> and <strong>MySQL</strong></li><li><strong>Snowflake</strong></li><li><strong>Google BigQuery</strong></li><li><strong>Amazon Redshift</strong></li><li><strong>Apache Druid</strong> and <strong>ClickHouse</strong></li><li><strong>Trino/Presto</strong></li><li><strong>Databricks</strong>, <strong>SQL Server</strong>, <strong>Oracle</strong>, and many more</li></ul><p>If your warehouse has a compatible driver, there is a good chance Superset can query it. That flexibility matters for teams that use more than one database or expect to change platforms someday.</p><h3>Interactive dashboards</h3><p>Charts become useful when they are assembled into a story. Superset’s dashboard editor is drag-and-drop, and dashboards can include:</p><ul><li><strong>Native filters</strong> that apply across multiple charts at once</li><li><strong>Cross-filtering</strong>, where clicking a bar in one chart filters the others</li><li><strong>Drill-to-detail</strong> and drill-by, so a viewer can go from a summary number to the rows behind it</li><li><strong>Tabs, markdown blocks, and headers</strong> for layout and context</li><li><strong>Scheduled alerts and reports</strong> delivered by email or Slack</li><li><strong>Embedding</strong> in your own web application</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtLvYY9wLhA3CfU-r_XZNA.png" /><figcaption><em>An example dashboard built in Apache Superset: a sales revenue dashboard on Snowflake sample data, combining a KPI card, pie chart, world map, and regional trend lines with a shared filter.</em></figcaption></figure><p>The dashboard above shows how these pieces fit together: a headline number with month-over-month change, a market segment breakdown, a country-level map, and regional trends over time, all controlled by a single filter bar at the top.</p><h3>Security: access control and authentication</h3><p>For any tool that touches company data, security is not optional. Superset ships with a flexible model:</p><ul><li><strong>Role-based access control (RBAC):</strong> Built-in roles such as Admin, Alpha, Gamma, and SQL Lab, plus custom roles with permissions down to individual datasets and dashboards.</li><li><strong>Row-level security:</strong> Restrict which rows a user or group can see, so a regional manager only sees their own region’s numbers from the same dashboard.</li><li><strong>Authentication integration:</strong> Because Superset is built on Flask AppBuilder, it supports database logins, <strong>LDAP</strong>, <strong>OAuth</strong> (Google, GitHub, Okta, Azure AD, and others), OpenID, and remote-user authentication, which makes single sign-on practical.</li></ul><h3>Architecture: A Technical Overview</h3><p>You don’t need to be an engineer to use Superset, but understanding the architecture helps you decide whether it fits your organization.</p><ul><li><strong>Backend:</strong> Python, using the <strong>Flask</strong> web framework, with SQLAlchemy for database connectivity.</li><li><strong>Frontend:</strong> <strong>React</strong> and TypeScript, which gives a responsive interface and a modern plugin system for custom visualizations.</li><li><strong>Metadata database:</strong> Superset keeps its own configuration (users, dashboards, chart definitions, saved queries) in a small relational database such as PostgreSQL or MySQL.</li><li><strong>Caching and async:</strong> Optional components like <strong>Redis</strong> and <strong>Celery</strong> handle query caching, background jobs, and scheduled reports for larger deployments.</li></ul><h3>The “thin layer” advantage</h3><p>The most important architectural idea is that Superset is a <strong>thin layer over your database</strong>. It does not ingest and store your business data. When someone opens a dashboard, Superset generates SQL, sends it to your database, and renders the results.</p><p>This has real benefits:</p><ol><li><strong>Single source of truth.</strong> There are no stale copies, because the dashboard reflects what is in the warehouse.</li><li><strong>Scalability rides on your database.</strong> If you use a strong engine like Snowflake, BigQuery, or ClickHouse, Superset inherits that performance.</li><li><strong>Simpler governance.</strong> Data stays where your security team already controls it.</li><li><strong>Lower infrastructure cost.</strong> You are not paying to store and sync a second copy of everything.</li></ol><p>The trade-off is that dashboard speed depends on your database and how well your queries and tables are modeled. That is where caching, aggregated tables, and good data modeling come in.</p><h3>Superset vs. Tableau vs. Power BI</h3><p>How does Superset stack up against the two giants of the BI world? Here is a high-level, criterion-by-criterion comparison. Exact pricing changes often, so check current vendor pages before making a purchase decision.</p><p><strong>Cost</strong></p><ul><li><strong>Superset:</strong> Free software; you pay for hosting and maintenance.</li><li><strong>Tableau:</strong> Per-user licensing, on the higher end.</li><li><strong>Power BI:</strong> Per-user licensing, generally cheaper, especially in Microsoft-centric organizations.</li></ul><p><strong>Ease of use</strong></p><ul><li><strong>Superset:</strong> Friendly for analysts and SQL users; less polished for non-technical users.</li><li><strong>Tableau:</strong> Excellent drag-and-drop experience, mature and polished.</li><li><strong>Power BI:</strong> Very approachable, especially for Excel users.</li></ul><p><strong>Scalability</strong></p><ul><li><strong>Superset:</strong> Excellent, because queries run on your database.</li><li><strong>Tableau:</strong> Strong, but often depends on extracts or a server tier.</li><li><strong>Power BI:</strong> Strong, with size limits and capacity tiers to plan around.</li></ul><p><strong>Customization</strong></p><ul><li><strong>Superset:</strong> Very high: open source, plugins, embedding, custom authentication.</li><li><strong>Tableau:</strong> Moderate; extensions available within vendor limits.</li><li><strong>Power BI:</strong> Moderate; custom visuals available within the Microsoft ecosystem.</li></ul><p><strong>Setup effort</strong></p><ul><li><strong>Superset:</strong> Higher if self-hosted.</li><li><strong>Tableau:</strong> Low to moderate.</li><li><strong>Power BI:</strong> Low, especially with Microsoft 365.</li></ul><p><strong>Vendor lock-in</strong></p><ul><li><strong>Superset:</strong> None.</li><li><strong>Tableau:</strong> Yes.</li><li><strong>Power BI:</strong> Yes.</li></ul><blockquote><strong><em>The short version:</em></strong><em> Tableau and Power BI are polished and easy to adopt, especially for business users. Superset wins on cost, flexibility, and control, and asks more of your technical team in return.</em></blockquote><h3>Pros and Cons</h3><h3>Advantages</h3><ul><li><strong>Free and open source,</strong> with no per-seat costs</li><li><strong>Connects to a huge range of SQL databases</strong></li><li><strong>Scales with your warehouse</strong> rather than being limited by its own engine</li><li><strong>Highly customizable,</strong> from authentication to embedding to custom charts</li><li><strong>Strong security features,</strong> including RBAC and row-level security</li><li><strong>Active community</strong> and steady development under the Apache Software Foundation</li><li><strong>SQL Lab</strong> gives data teams a powerful exploration environment</li></ul><h3>Limitations</h3><ul><li><strong>Setup and maintenance complexity.</strong> Production deployments need someone comfortable with Python services, databases, and caching.</li><li><strong>Learning curve for non-technical users.</strong> Building charts from scratch is easier than in some competitors but still assumes some data literacy.</li><li><strong>Less polished in places.</strong> Some advanced formatting and pixel-perfect design options lag behind Tableau.</li><li><strong>Data preparation lives elsewhere.</strong> Superset expects clean, well-modeled tables. It is not a full ETL or transformation tool, so you will usually pair it with something like <strong>dbt</strong>.</li><li><strong>Support is community-driven</strong> unless you use a commercial provider.</li></ul><h3>Practical Use Cases</h3><p><strong>1. A SaaS company tracking churn.</strong> A subscription business connects Superset to its warehouse and builds a dashboard showing monthly recurring revenue, cohort retention, and churn by plan and acquisition channel. Customer success teams filter by segment to find at-risk accounts, while executives see the big-picture trend.</p><p><strong>2. A hospital tracking patient metrics.</strong> An administrative team monitors average wait times, bed occupancy, and readmission rates. Row-level security ensures each department sees only its own data, and everything stays inside the organization’s own infrastructure, which is valuable when data privacy is a concern.</p><p><strong>3. An e-commerce store tracking sales.</strong> A retailer visualizes daily revenue, top products, conversion funnels, and inventory levels. Scheduled email reports send the previous day’s numbers to the team every morning, and a geospatial chart shows where orders are coming from.</p><h3>How to Get Started</h3><h3>Option 1: Docker (the easiest way to try it)</h3><p>For evaluation, Docker is by far the fastest route. In broad strokes:</p><ol><li><strong>Install Docker</strong> and Docker Compose on your machine.</li><li><strong>Clone the Superset repository</strong> from GitHub.</li><li><strong>Run the provided Docker Compose setup</strong> to start Superset with its supporting services.</li><li><strong>Open your browser</strong> on the local port, log in, and connect your first database.</li></ol><p>Follow the official documentation for the current commands, since they change between releases. Also, never run a production instance with default credentials or the default secret key. Change them before exposing Superset to anyone.</p><h3>Option 2: Other self-hosting methods</h3><p>For production, teams often deploy with <strong>Kubernetes</strong> using the official Helm chart, or install via <strong>pip</strong> on a managed server. Plan for a proper metadata database, Redis for caching, and Celery workers if you need async queries or scheduled reports.</p><h3>Option 3: Managed services</h3><p>If you’d rather not maintain servers, managed Superset is available. <strong>Preset</strong>, founded by Superset’s creator, offers a hosted version, and other providers offer managed deployments too. You get the Superset experience without handling upgrades, scaling, and uptime yourself.</p><h3>Conclusion</h3><p>Apache Superset is a game-changer because it removes the biggest barriers to business intelligence: cost, lock-in, and rigidity. It lets a five-person startup and a multinational enterprise use the same modern analytics platform, backed by a healthy open-source community and the governance of the Apache Software Foundation.</p><p>It isn’t perfect. You will invest time in setup, and non-technical users may need some onboarding. But for teams with even modest technical capacity, the payoff is control over your data, your costs, and your tooling.</p><p>If you are evaluating BI tools, spin up a Docker instance this week, connect a sample database, and build one dashboard. You will learn more in an afternoon than from any comparison chart.</p><p><strong>Have you used Apache Superset, or are you considering it?</strong> Share your experience in the comments, and if this guide helped, give it a clap and pass it along to a colleague who is wrestling with BI costs.</p><h3>Frequently Asked Questions</h3><p><strong>What is Apache Superset used for?</strong> Apache Superset is used to explore data, build charts, and create interactive dashboards on top of SQL databases. Teams use it for business reporting, product analytics, operations monitoring, and embedded analytics.</p><p><strong>Is Apache Superset really free?</strong> Yes. The software is open source under the Apache 2.0 license. You still pay for hosting, maintenance, and your team’s time, or for a managed service if you choose one.</p><p><strong>Who created Apache Superset?</strong> It was created at Airbnb by Maxime Beauchemin, then open-sourced and adopted by the Apache Software Foundation, where it is now a top-level project.</p><p><strong>Is Superset better than Tableau or Power BI?</strong> It depends on your priorities. Superset is stronger on cost, customization, and scalability. Tableau and Power BI tend to be more polished and easier for non-technical users. Many teams choose Superset when they have technical resources and want to avoid licensing costs.</p><p><strong>Does Superset store my data?</strong> No. Superset queries your existing databases and does not keep a copy of your business data. It stores only its own metadata, such as dashboard and chart definitions.</p><p><strong>Which databases does Superset support?</strong> Any database with a SQLAlchemy driver, including PostgreSQL, MySQL, Snowflake, BigQuery, Redshift, Druid, ClickHouse, Trino, and many others.</p><p><strong>Do I need to know how to code to use Superset?</strong> Not to build charts and dashboards, since the no-code builder handles that. SQL knowledge helps with SQL Lab and advanced datasets, and technical skills are needed for installation and administration.</p><p><strong>Can I embed Superset dashboards in my own application?</strong> Yes. Superset supports embedding dashboards, which makes it popular for customer-facing analytics.</p><p><strong>How do I get started with Superset?</strong> The easiest way is Docker for local testing. For production, consider Kubernetes or a managed service such as Preset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3ba78ab6063" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an End-to-End Healthcare Data Pipeline with Airflow + PostgreSQL + Docker-Compose &…]]></title>
            <link>https://medium.com/@ngakoutousophonie/building-an-end-to-end-healthcare-data-pipeline-with-airflow-postgresql-docker-compose-992f09050218?source=rss-32c2d22e7db7------2</link>
            <guid isPermaLink="false">https://medium.com/p/992f09050218</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Sophonie NGAKOUTOU GUELBE]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 14:53:00 GMT</pubDate>
            <atom:updated>2025-11-10T14:53:00.646Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an End-to-End Healthcare Data Pipeline with Airflow + PostgreSQL + Docker-Compose &amp; openFDA API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8kBOWJGkSFZtiMI37vHOQ.png" /></figure><p>In the healthcare sector, timely and accurate data can save lives. As a data engineer, I recently built a complete data pipeline that processes drug adverse event data from the openFDA (Food and Drug Administration). This project demonstrates how to build a production-ready ETL system using modern tools like Airflow, Polars, and PostgreSQL — all containerized with Docker.</p><h3>🎯 What We’re Building</h3><p>This pipeline automates the entire data lifecycle for healthcare analytics:</p><ol><li><strong>Ingestion:</strong> Pull raw JSON data from <strong>openFDA</strong> API</li><li><strong>Transformation:</strong> Flatten nested structures and clean data using Polars</li><li><strong>Modeling:</strong> Load into PostgreSQL and build analytics marts</li><li><strong>Orchestration</strong>: Schedule and monitor with Airflow</li><li><strong>Containerization</strong>: Run everything in Docker containers</li></ol><h3>📁 Project Structure</h3><p>OPENFDA-PIPELINE/<br> ├── airflow/<br> │ ├── dags/<br> │ │ └── openfda_pipeline_dag.py<br> │ ├── logs/<br> │ └── plugins/<br> │<br> ├── scripts/<br> │ ├── ingest.py<br> │ ├── model.py<br> │ ├── orchestrate.py<br> │ └── transform.py<br> │<br> ├── .dockerignore<br> ├── .env<br> ├── .gitignore<br> ├── docker-compose.yml<br> ├── Dockerfile<br> ├── Makefile<br> ├── README.md<br> └── requirements.txt</p><h3>🚀 Step 1: Environment Setup</h3><p>First, let’s set up our environment configuration (.env file):</p><pre># .env<br>POSTGRES_USER=airflow<br>POSTGRES_PASSWORD=airflow<br>POSTGRES_DB=airflow<br>POSTGRES_PORT=5432<br>POSTGRES_HOST=postgres<br><br>AIRFLOW_UID=50000<br>AIRFLOW_PORT=8080<br>AIRFLOW_FERNET_KEY=your_fernet_key_here<br>AIRFLOW_SECRET_KEY=your_secret_key_here<br><br>OPENFDA_ENDPOINT=https://api.fda.gov/drug/event.json?limit=1000</pre><h3>🐳 Step 2: Docker Compose Setup</h3><p>Here’s our docker-compose.yml that defines all services:</p><pre># =====================================================================<br># Shared Airflow configuration for all airflow containers<br># =====================================================================<br>x-airflow-common:<br>  &amp;airflow-common<br>  image: apache/airflow:2.8.1<br>  environment:<br>    &amp;airflow-common-env<br>    AIRFLOW__CORE__EXECUTOR: LocalExecutor<br>    AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres/${POSTGRES_DB}<br>    AIRFLOW__CORE__FERNET_KEY: ${AIRFLOW_FERNET_KEY}<br>    AIRFLOW__WEBSERVER__SECRET_KEY: ${AIRFLOW_SECRET_KEY}<br>    AIRFLOW__CORE__LOAD_EXAMPLES: &#39;false&#39;<br>    AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: &#39;true&#39;<br>    AIRFLOW__API__AUTH_BACKENDS: &quot;airflow.api.auth.backend.basic_auth&quot;<br>    _PIP_ADDITIONAL_REQUIREMENTS: &quot;polars&quot;<br>  volumes:<br>    - ./airflow/dags:/opt/airflow/dags<br>    - ./airflow/logs:/opt/airflow/logs<br>    - ./airflow/plugins:/opt/airflow/plugins<br>    - ./scripts:/opt/airflow/scripts<br>    - ./.env:/opt/airflow/.env<br>  user: &quot;${AIRFLOW_UID}:0&quot;<br>  depends_on:<br>    - postgres<br><br># =====================================================================<br># Services<br># =====================================================================<br>services:<br><br>  # --------------------------------------------------------------<br>  # PostgreSQL Database<br>  # --------------------------------------------------------------<br>  postgres:<br>    image: postgres:13<br>    container_name: postgres<br>    environment:<br>      POSTGRES_USER: ${POSTGRES_USER}<br>      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}<br>      POSTGRES_DB: ${POSTGRES_DB}<br>    ports:<br>      - &quot;${POSTGRES_PORT}:5432&quot;<br>    volumes:<br>      - ./postgres-db-volume:/var/lib/postgresql/data<br><br>  # --------------------------------------------------------------<br>  # Airflow Webserver<br>  # --------------------------------------------------------------<br>  airflow-webserver:<br>    &lt;&lt;: *airflow-common<br>    command: webserver<br>    ports:<br>      - &quot;${AIRFLOW_PORT}:8080&quot;<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:8080/health&quot;]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br><br>  # --------------------------------------------------------------<br>  # Airflow Scheduler<br>  # --------------------------------------------------------------<br>  airflow-scheduler:<br>    &lt;&lt;: *airflow-common<br>    command: scheduler<br><br>  # --------------------------------------------------------------<br>  # Airflow Triggerer<br>  # Needed when using LocalExecutor for deferred tasks<br>  # --------------------------------------------------------------<br>  airflow-triggerer:<br>    &lt;&lt;: *airflow-common<br>    command: triggerer<br><br>  # --------------------------------------------------------------<br>  # One-time Initialization Service<br>  # Creates Airflow DB + Admin User<br>  # --------------------------------------------------------------<br>  airflow-init:<br>    &lt;&lt;: *airflow-common<br>    command: bash -c &quot;airflow db migrate &amp;&amp; airflow users create \<br>      --username admin \<br>      --password admin \<br>      --firstname Admin \<br>      --lastname User \<br>      --role Admin \<br>      --email admin@example.com&quot;<br>    depends_on:<br>      - postgres<br><br># =====================================================================<br># Volumes<br># =====================================================================<br>volumes:<br>  postgres-db-volume:</pre><h3>📥 Step 3: Data Ingestion</h3><p>Let’s start with the ingestion script that fetches data from openFDA:</p><pre># scripts/ingest.py<br>import logging<br>import os<br>from pathlib import Path<br>import requests<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>API_URL = os.getenv(&quot;OPENFDA_ENDPOINT&quot;)<br>RAW_PATH = Path(&quot;data/raw/openfda_raw.json&quot;)<br><br>logging.basicConfig(level=logging.INFO, format=&quot;%(asctime)s - %(levelname)s - %(message)s&quot;)<br><br><br>def ingest():<br>    logging.info(&quot;Starting ingestion from openFDA API: %s&quot;, API_URL)<br>    if API_URL is None:<br>        logging.error(&quot;OPENFDA_ENDPOINT not set in environment.&quot;)<br>        raise RuntimeError(&quot;OPENFDA_ENDPOINT not set&quot;)<br><br>    resp = requests.get(API_URL, timeout=30)<br>    resp.raise_for_status()<br><br>    RAW_PATH.parent.mkdir(parents=True, exist_ok=True)<br>    RAW_PATH.write_text(resp.text, encoding=&quot;utf-8&quot;)<br><br>    logging.info(&quot;Saved raw openFDA response to %s&quot;, RAW_PATH)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    ingest()</pre><h3>🔄 Step 4: Data Transformation</h3><p>Now, let’s transform the raw JSON into a structured format:</p><pre># scripts/transform.py<br>import logging<br>from pathlib import Path<br>import json<br>from dotenv import load_dotenv<br>import os<br>import polars as pl<br>from datetime import datetime<br><br>load_dotenv()<br><br>RAW_PATH = Path(&quot;data/raw/openfda_raw.json&quot;)<br>PROCESSED_PATH = Path(&quot;data/processed/openfda_events.parquet&quot;)<br><br>logging.basicConfig(level=logging.INFO, format=&quot;%(asctime)s - %(levelname)s - %(message)s&quot;)<br><br><br>def _safe_get(dct, *keys, default=None):<br>    &quot;&quot;&quot;Nested safe get for dicts.&quot;&quot;&quot;<br>    cur = dct<br>    for k in keys:<br>        if not isinstance(cur, dict):<br>            return default<br>        cur = cur.get(k)<br>        if cur is None:<br>            return default<br>    return cur<br><br><br>def _extract_flat(record: dict):<br>    &quot;&quot;&quot;<br>    Given one &#39;results&#39; record from openFDA drug/event endpoint,<br>    return a flattened dict with the fields we care about.<br>    &quot;&quot;&quot;<br>    # Many fields live under nested structures<br>    # doc-level id if present<br>    safety_id = record.get(&quot;safetyreportid&quot;) or record.get(&quot;safety_report_id&quot;) or record.get(&quot;safetyreportid&quot;, None) or record.get(&quot;primaryid&quot;, None)<br>    # event-level fields<br>    serious = record.get(&quot;serious&quot;) or record.get(&quot;seriousness&quot;, None) or None<br>    receivedate = record.get(&quot;receivedate&quot;)  # often YYYYMMDD or similar<br><br>    # patient/drug: take first drug if present<br>    patient: dict = record.get(&quot;patient&quot;, {})<br>    drugs = patient.get(&quot;drug&quot;) or []<br>    drug0 = drugs[0] if isinstance(drugs, list) and drugs else {}<br>    medicinalproduct = drug0.get(&quot;medicinalproduct&quot;) or drug0.get(&quot;drugname&quot;) or None<br>    drugindication = drug0.get(&quot;drugindication&quot;) or None<br><br>    # patient/reactions: list of reactionmeddrapt<br>    reactions = patient.get(&quot;reaction&quot;) or []<br>    reaction_list = []<br>    if isinstance(reactions, list):<br>        for r in reactions:<br>            if isinstance(r, dict):<br>                reaction_list.append(r.get(&quot;reactionmeddrapt&quot;) or r.get(&quot;reaction&quot;, None))<br>    reactions_joined = &quot;, &quot;.join([r for r in reaction_list if r])<br><br>    # event outcomes or seriousness if present<br>    outcome = patient.get(&quot;patientonsetageunit&quot;, None)  # optional example; leave flexible<br><br>    return {<br>        &quot;safety_id&quot;: safety_id,<br>        &quot;serious&quot;: serious,<br>        &quot;receivedate&quot;: receivedate,<br>        &quot;drug_name&quot;: medicinalproduct,<br>        &quot;drug_indication&quot;: drugindication,<br>        &quot;reactions&quot;: reactions_joined<br>    }<br><br><br>def transform():<br>    logging.info(&quot;Starting transform step...&quot;)<br><br>    if not RAW_PATH.exists():<br>        logging.error(&quot;Raw file not found: %s&quot;, RAW_PATH)<br>        raise FileNotFoundError(RAW_PATH)<br><br>    raw_text = RAW_PATH.read_text(encoding=&quot;utf-8&quot;)<br>    payload: dict = json.loads(raw_text)<br><br>    results = payload.get(&quot;results&quot;) or []<br>    logging.info(&quot;Found %d results in raw payload&quot;, len(results))<br><br>    flat_records = []<br>    for rec in results:<br>        flat = _extract_flat(rec)<br>        # Normalize basic fields<br>        # ensure strings and basic cleaning<br>        flat[&quot;drug_name&quot;] = flat[&quot;drug_name&quot;].upper() if flat.get(&quot;drug_name&quot;) else None<br>        flat[&quot;drug_indication&quot;] = flat[&quot;drug_indication&quot;].title() if flat.get(&quot;drug_indication&quot;) else None<br>        flat[&quot;reactions&quot;] = flat[&quot;reactions&quot;].title() if flat.get(&quot;reactions&quot;) else None<br><br>        # parse receivedate to ISO date if it&#39;s in YYYYMMDD<br>        rd = flat.get(&quot;receivedate&quot;)<br>        parsed_date = None<br>        if rd:<br>            try:<br>                parsed_date = datetime.strptime(rd, &quot;%Y%m%d&quot;).date()<br>            except Exception:<br>                parsed_date = None<br>        flat[&quot;received_date&quot;] = parsed_date.isoformat() if parsed_date else None<br><br>        flat_records.append(flat)<br><br>    if not flat_records:<br>        logging.warning(&quot;No flat records extracted.&quot;)<br>    else:<br>        logging.info(&quot;Writing %d processed records to parquet&quot;, len(flat_records))<br>        df = pl.from_records(flat_records)<br>        PROCESSED_PATH.parent.mkdir(parents=True, exist_ok=True)<br>        df.write_parquet(PROCESSED_PATH)<br>        logging.info(&quot;Processed data saved to %s&quot;, PROCESSED_PATH)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    transform()</pre><h3>🗄️ Step 5: Data Modeling</h3><p>Now let’s load the data into PostgreSQL and create analytical models:</p><pre># scripts/model.py<br>import logging<br>import os<br>from dotenv import load_dotenv, find_dotenv<br>import polars as pl<br>from pathlib import Path<br>import psycopg2<br>from psycopg2.extras import execute_values<br><br>load_dotenv(find_dotenv())<br><br>DB_NAME = os.getenv(&quot;POSTGRES_DB&quot;)<br>DB_USER = os.getenv(&quot;POSTGRES_USER&quot;)<br>DB_PASS = os.getenv(&quot;POSTGRES_PASSWORD&quot;)<br>DB_HOST = os.getenv(&quot;POSTGRES_HOST&quot;)<br>DB_PORT = int(os.getenv(&quot;POSTGRES_PORT&quot;, 5432))<br><br>PROCESSED_PATH = Path(&quot;data/processed/openfda_events.parquet&quot;)<br><br>logging.basicConfig(level=logging.INFO, format=&quot;%(asctime)s - %(levelname)s - %(message)s&quot;)<br><br><br># log credentials for debugging (remove in production)<br>logging.info(&quot;Postgres connection details: DB_NAME=%s, DB_USER=%s, DB_HOST=%s, DB_PORT=%s&quot;,<br>             DB_NAME, DB_USER, DB_HOST, DB_PORT)<br><br>def _connect(dbtname=DB_NAME):<br>    conn = psycopg2.connect(<br>        dbname=dbtname,<br>        user=DB_USER,<br>        password=DB_PASS,<br>        host=DB_HOST,<br>        port=DB_PORT<br>    )<br>    return conn<br><br>def _connect_db_assigment():<br>    conn = _connect()<br>    conn.autocommit = True<br>    cur = conn.cursor()<br>    try:<br>        cur.execute(f&quot;CREATE DATABASE assignment_db;&quot;)<br>        conn.commit()<br>        cur.close()<br>        conn.close()<br>    except psycopg2.errors.DuplicateDatabase:<br>        logging.info(&quot;Database assignment_db already exists, skipping creation.&quot;)<br><br>    # reconnect to the specific database<br>    conn = _connect(dbtname=&#39;assignment_db&#39;)<br>    return conn<br><br><br>def model():<br>    logging.info(&quot;Starting model step, connecting to Postgres at %s:%s&quot;, DB_HOST, DB_PORT)<br>    conn = _connect_db_assigment()<br>    cur = conn.cursor()<br><br>    logging.info(&quot;Creating staging table stg_openfda_events if not exists.&quot;)<br>    cur.execute(&quot;&quot;&quot;<br>    CREATE TABLE IF NOT EXISTS stg_openfda_events (<br>        safety_id TEXT PRIMARY KEY,<br>        serious TEXT,<br>        received_date DATE,<br>        drug_name TEXT,<br>        drug_indication TEXT,<br>        reactions TEXT<br>    );<br>    &quot;&quot;&quot;)<br><br>    if not PROCESSED_PATH.exists():<br>        logging.error(&quot;Processed parquet not found at %s&quot;, PROCESSED_PATH)<br>        raise FileNotFoundError(PROCESSED_PATH)<br><br>    df = pl.read_parquet(PROCESSED_PATH)<br>    logging.info(&quot;Loaded processed parquet into polars DataFrame with %d rows&quot;, df.height)<br><br>    # convert nulls to None and prepare list of tuples<br><br>    rows = []<br>    for r in df.to_dicts():<br>        rows.append((<br>            r.get(&quot;safety_id&quot;),<br>            r.get(&quot;serious&quot;),<br>            r.get(&quot;received_date&quot;),<br>            r.get(&quot;drug_name&quot;),<br>            r.get(&quot;drug_indication&quot;),<br>            r.get(&quot;reactions&quot;),<br>        ))<br><br>    logging.info(&quot;Inserting %d rows into stg_openfda_events (upsert)&quot;, len(rows))<br>    execute_values(<br>        cur,<br>        &quot;&quot;&quot;<br>        INSERT INTO stg_openfda_events (<br>            safety_id, serious, received_date, drug_name, drug_indication, reactions<br>        ) VALUES %s<br>        ON CONFLICT (safety_id) DO UPDATE SET<br>            serious = EXCLUDED.serious,<br>            received_date = EXCLUDED.received_date,<br>            drug_name = EXCLUDED.drug_name,<br>            drug_indication = EXCLUDED.drug_indication,<br>            reactions = EXCLUDED.reactions;<br>        &quot;&quot;&quot;,<br>        rows,<br>        page_size=100<br>    )<br><br>    # Build analytics mart 1: aggregated counts per drug<br>    logging.info(&quot;Creating mart: mart_drug_summary (aggregations per drug_name)&quot;)<br>    cur.execute(&quot;DROP TABLE IF EXISTS mart_drug_summary;&quot;)<br>    cur.execute(&quot;&quot;&quot;<br>        CREATE TABLE mart_drug_summary AS<br>        SELECT<br>            COALESCE(drug_name, &#39;UNKNOWN&#39;) AS drug_name,<br>            COUNT(*) AS total_reports,<br>            SUM(CASE WHEN serious = &#39;1&#39; THEN 1 ELSE 0 END) AS serious_reports,<br>            MAX(received_date) AS last_report_date<br>        FROM stg_openfda_events<br>        GROUP BY drug_name;<br>    &quot;&quot;&quot;)<br><br>    # Marty 2: top reactions per drug (materialized as a table of drug -&gt; reaction -&gt; count)<br>    logging.info(&quot;Creating mart: mart_drug_reactions&quot;)<br>    cur.execute(&quot;DROP TABLE IF EXISTS mart_drug_reactions;&quot;)<br>    cur.execute(&quot;&quot;&quot;<br>        CREATE TABLE mart_drug_reactions AS<br>        SELECT<br>            drug_name,<br>            reactions,<br>            COUNT(*) AS reaction_count<br>        FROM stg_openfda_events<br>        WHERE reactions IS NOT NULL AND reactions &lt;&gt; &#39;&#39;<br>        GROUP BY drug_name, reactions;<br>    &quot;&quot;&quot;)<br><br>    # indexes for optimization<br>    logging.info(&quot;Creating indexes for optimization&quot;)<br>    cur.execute(&quot;CREATE INDEX IF NOT EXISTS idx_stg_drug ON stg_openfda_events(drug_name);&quot;)<br>    cur.execute(&quot;CREATE INDEX IF NOT EXISTS idx_mart_drug ON mart_drug_summary(drug_name);&quot;)<br><br>    conn.commit()<br>    cur.close()<br>    conn.close()<br>    logging.info(&quot;Model step completed successfully.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    model()</pre><h3>🔄 Step 6: Airflow Orchestration</h3><p>Now let’s orchestrate everything with Airflow:</p><pre># airflow/dags/openfda_pipeline_dag.py<br>import sys<br>import os<br><br><br># For local imports from scripts/<br>sys.path.append(os.path.join(os.path.dirname(__file__), &quot;../scripts&quot;))<br><br><br>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from datetime import datetime<br><br><br>from ingest import ingest<br>from transform import transform<br>from model import model<br><br>default_args = {<br>    &quot;owner&quot;: &quot;airflow&quot;,<br>    &quot;start_date&quot;: datetime(2025, 11, 7),<br>}<br><br>with DAG(<br>    &quot;openfda_pipeline&quot;,<br>    default_args=default_args,<br>    schedule_interval=&quot;*/5 * * * *&quot;,  # every 5 minutes<br>    catchup=False,<br>    description=&quot;Pipeline for ingesting and modeling openFDA health data&quot;<br>):<br><br>    ingest_task = PythonOperator(<br>        task_id=&quot;ingest_openfda&quot;,<br>        python_callable=ingest,<br>    )<br><br>    transform_task = PythonOperator(<br>        task_id=&quot;transform_openfda&quot;,<br>        python_callable=transform,<br>    )<br><br>    model_task = PythonOperator(<br>        task_id=&quot;load_and_model_openfda&quot;,<br>        python_callable=model,<br>    )<br><br>    ingest_task &gt;&gt; transform_task &gt;&gt; model_task</pre><h3>🚀 Step 7: Running the Pipeline</h3><p>Let’s create a Makefile to simplify operations:</p><pre>postgres:<br> docker compose up -d postgres<br><br>airflow-init:<br> docker compose up airflow-init<br><br>up:<br> docker compose up -d<br><br>down:<br> docker compose down -v<br><br>ps:<br> docker compose ps<br><br>logs-webserver:<br> docker compose logs airflow-webserver<br><br>logs-scheduler:<br> docker compose logs airflow-scheduler<br><br><br>db-shell:<br> docker exec -it postgres psql -U postgres -d assignment_db<br><br>local-run:<br> python3 scripts/orchestrate.py</pre><p><strong>Step-by-Step Commands to run everything:</strong></p><pre># First command to run to start the project<br>make postgres<br><br># Second command to Initialize Airflow<br># (migrate database and create the admin user):<br><br>make airflow-init<br><br># Last command to Start all services<br>make up<br><br><br># Wait for a few seconds for all services to be up<br># Open your browser at:<br>http://localhost:8080<br><br># Default Login creadentials (username: admin, Password: admin)<br># After logged in, you can simply unpause the dag and let the pipeline finish to run<br></pre><p><strong>NOTE</strong>: When you run the command make airflow-initfor the very first time, you might end up into this error below and to fix this all you have to do is to delete the file airflow/logswith admin privilege then create a new one manually with this command (mkdir -p airflow/logs) then change the mode (chmod 777 airflow/logs)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3TA_0tq-aN3o6TuLKzpFw.png" /></figure><h3>📊 Step 8: Analyzing the Results</h3><p>Once the pipeline runs, use this command make db-shellto connect to the database so you can query the analytical marts:</p><pre>-- Top drugs by adverse event reports<br>SELECT drug_name, total_reports, serious_reports<br>FROM mart_drug_summary <br>ORDER BY total_reports DESC <br>LIMIT 10;<br><br>-- Common reactions for a specific drug<br>SELECT reactions, reaction_count<br>FROM mart_drug_reactions <br>WHERE drug_name = &#39;IBUPROFEN&#39;<br>ORDER BY reaction_count DESC <br>LIMIT 5;</pre><h3>🎯 Key Features &amp; Best Practices</h3><p>This implementation demonstrates several important data engineering concepts:</p><ol><li><strong>Modular Design</strong>: Separate concerns with dedicated scripts for ingestion, transformation, and modeling</li><li><strong>Error Handling</strong>: Comprehensive logging and safe data access patterns</li><li><strong>Performance</strong>: Using Polars for fast data processing and Parquet for efficient storage</li><li><strong>Data Quality</strong>: Data cleaning, standardization, and validation</li><li><strong>Monitoring</strong>: Airflow provides built-in monitoring and alerting</li><li><strong>Reproducibility</strong>: Docker ensures consistent environments across deployments</li></ol><h3>🔮 Potential Enhancements</h3><p>This pipeline can be extended with:</p><ul><li>Data validation tests with Great Expectations</li><li>Automated data quality checks</li><li>ML model integration for predicting serious adverse events</li><li>Real-time streaming with Kafka</li><li>Cloud deployment on AWS/GCP/Azure</li></ul><h3>💡 Conclusion</h3><p>Building this end-to-end pipeline demonstrates how modern data engineering tools can transform raw healthcare data into actionable insights. The containerized approach ensures reproducibility, while the modular design makes it maintainable and extensible.</p><p>This pipeline provides a solid foundation for healthcare analytics, enabling researchers and analysts to quickly understand drug safety patterns and make data-driven decisions.</p><p>What interesting data pipelines have you built? Share your experiences and questions in the comments below!</p><p><em>The complete source code is available on </em><a href="https://github.com/Sopho-Ngak/openFDA-Data-Engineering-Pipeline">openFDA-Data-Engineering-Pipeline</a><em>.</em></p><p>#DataEngineering #HealthcareAnalytics #Airflow #Python #Polars #PostgreSQL #Docker #ETL #DataPipeline #OpenFDA</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=992f09050218" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>