πŸ“ŠData Engineering

ETL

Extract, Transform, Load

The three stages of a data pipeline. Extract, Transform, Load. The foundation of building a data warehouse.

πŸ“– Detailed Explanation

ETL (Extract, Transform, Load) is a basic data pipeline pattern: the process of extracting data from various sources (Extract), transforming it into a form suitable for analysis (Transform), and loading it into a destination system (Load). It forms the foundation of data warehouses, data lakes, and ML pipelines.

In the Extract stage, data is retrieved from various sources such as databases (MySQL, PostgreSQL), SaaS (Salesforce, Stripe), APIs, and files (CSV, JSON). There are Full Load, which retrieves all of the data, and Incremental Load, which retrieves only the changed data; for large volumes of data, Incremental is more efficient.

In the Transform stage, data cleansing (null handling, duplicate removal), format conversion (date formats, type casting), application of business logic (calculated fields, aggregation), and joins and integration are performed. This stage is the most complex and varies greatly depending on business requirements.

Recently, the ELT (Extract, Load, Transform) pattern is also widely used. It is a method that leverages the computing power of the cloud DW to load raw data first and then transform it. A common structure is for tools such as Fivetran and Airbyte to handle EL (Extract, Load), and for dbt to handle Transform.

πŸ’» Code Example

# Python ETL νŒŒμ΄ν”„λΌμΈ 예제

import pandas as pd
from sqlalchemy import create_engine
from datetime import datetime, timedelta
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ETLPipeline:
    def __init__(self, source_conn, target_conn):
        self.source_engine = create_engine(source_conn)
        self.target_engine = create_engine(target_conn)

    # 1. EXTRACT - μ†ŒμŠ€μ—μ„œ 데이터 μΆ”μΆœ
    def extract(self, table_name: str, incremental_col: str = None,
                last_value = None) -> pd.DataFrame:
        """증뢄 λ˜λŠ” 전체 데이터 μΆ”μΆœ"""

        if incremental_col and last_value:
            # Incremental Load: λ³€κ²½λœ λ°μ΄ν„°λ§Œ
            query = f"""
                SELECT * FROM {table_name}
                WHERE {incremental_col} > '{last_value}'
                ORDER BY {incremental_col}
            """
            logger.info(f"Incremental extract from {table_name} after {last_value}")
        else:
            # Full Load: 전체 데이터
            query = f"SELECT * FROM {table_name}"
            logger.info(f"Full extract from {table_name}")

        df = pd.read_sql(query, self.source_engine)
        logger.info(f"Extracted {len(df)} rows")
        return df

    # 2. TRANSFORM - 데이터 λ³€ν™˜
    def transform(self, df: pd.DataFrame) -> pd.DataFrame:
        """데이터 μ •μ œ 및 λ³€ν™˜"""

        # 2-1. 데이터 μ •μ œ
        df = df.drop_duplicates()
        df = df.dropna(subset=['user_id', 'event_type'])  # ν•„μˆ˜ ν•„λ“œ null 제거

        # 2-2. νƒ€μž… λ³€ν™˜
        df['created_at'] = pd.to_datetime(df['created_at'])
        df['amount'] = pd.to_numeric(df['amount'], errors='coerce').fillna(0)

        # 2-3. νŒŒμƒ 컬럼 생성
        df['event_date'] = df['created_at'].dt.date
        df['event_hour'] = df['created_at'].dt.hour
        df['is_weekend'] = df['created_at'].dt.dayofweek >= 5

        # 2-4. λΉ„μ¦ˆλ‹ˆμŠ€ 둜직 적용
        df['amount_category'] = pd.cut(
            df['amount'],
            bins=[0, 100, 500, float('inf')],
            labels=['small', 'medium', 'large']
        )

        # 2-5. 메타데이터 μΆ”κ°€
        df['etl_timestamp'] = datetime.now()
        df['etl_batch_id'] = datetime.now().strftime('%Y%m%d%H%M%S')

        logger.info(f"Transformed {len(df)} rows")
        return df

    # 3. LOAD - λͺ©μ μ§€μ— 적재
    def load(self, df: pd.DataFrame, table_name: str,
             if_exists: str = 'append') -> None:
        """데이터 적재 (append λ˜λŠ” replace)"""

        df.to_sql(
            table_name,
            self.target_engine,
            if_exists=if_exists,
            index=False,
            method='multi',  # 배치 insert둜 μ„±λŠ₯ ν–₯상
            chunksize=1000
        )
        logger.info(f"Loaded {len(df)} rows to {table_name}")

    # ETL μ‹€ν–‰
    def run(self, source_table: str, target_table: str,
            incremental_col: str = None, last_value = None):
        """ETL νŒŒμ΄ν”„λΌμΈ μ‹€ν–‰"""

        logger.info(f"Starting ETL: {source_table} -> {target_table}")

        # Extract
        raw_data = self.extract(source_table, incremental_col, last_value)

        if raw_data.empty:
            logger.info("No new data to process")
            return

        # Transform
        transformed_data = self.transform(raw_data)

        # Load
        self.load(transformed_data, target_table)

        logger.info("ETL completed successfully")
        return transformed_data[incremental_col].max() if incremental_col else None


# μ‚¬μš© μ˜ˆμ‹œ
if __name__ == "__main__":
    pipeline = ETLPipeline(
        source_conn="postgresql://source_db/production",
        target_conn="postgresql://target_db/analytics"
    )

    # 증뢄 ETL μ‹€ν–‰
    last_processed = pipeline.run(
        source_table="events",
        target_table="fact_events",
        incremental_col="created_at",
        last_value="2024-01-15 00:00:00"
    )

πŸ—£οΈ How It's Said in Practice

Data Engineer: "Yesterday's ETL job took 3 hours. There were too many joins in the transform stage."

Junior: "What if we switch to ELT? If we load the data as raw first and then transform it in BigQuery, it would be distributed processing, so I think it would be faster."

Senior: "Good idea. If we manage the transformation logic with dbt, we get version control too, and testing becomes easier."

Interviewer: "Please explain the differences between ETL and ELT and when to use each."

Candidate: "ETL transforms data before loading, so only cleansed data is stored. It was widely used in on-premises DWs. ELT loads raw data first and then transforms it. It leverages the computing power of the cloud DW, and because the raw data is preserved, other transformations can be done later as well. Nowadays, ELT is preferred because it is more flexible."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Reviewer: "This ETL has no idempotency. If you run the same data twice, it will be loaded in duplicate."

Author: "I'll add merge/upsert logic. Or I'll change it to a delete-insert pattern that deletes the data for that date before loading."

⚠️ Cautions

πŸ“š Learn More