ETL
Extract, Transform, Load
The three stages of a data pipeline. Extract, Transform, Load. The foundation of building a data warehouse.
Extract, Transform, Load
The three stages of a data pipeline. Extract, Transform, Load. The foundation of building a data warehouse.
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.
# 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"
)
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."