Data Lake
Data Lake
A repository that stores raw data in its original form. Accepts both structured and unstructured data. S3-based.
Data Lake
A repository that stores raw data in its original form. Accepts both structured and unstructured data. S3-based.
A Data Lake is a centralized repository that can store structured, semi-structured, and unstructured data in its raw form. Unlike a traditional data warehouse, which stores only structured data according to a predefined schema, a data lake adopts a Schema-on-Read approach, storing data first and applying the schema at the time of analysis. This flexibility makes it possible to quickly ingest and store large volumes of data generated from diverse sources.
A data lake architecture is generally designed as a three-tier structure of Bronze (Raw), Silver (Cleansed), and Gold (Curated). The Bronze layer stores raw data as it is, the Silver layer performs cleansing and transformation, and the Gold layer stores aggregated data that can be used immediately for business analytics. This layered approach is called the Medallion Architecture, and it enables data quality management and governance to be carried out systematically.
Object storage such as AWS S3, Azure Data Lake Storage (ADLS), and Google Cloud Storage (GCS) is used as the main implementation technology. These can store petabyte-scale data at low cost, and compute and storage can be separated so that each can be scaled independently. Columnar formats such as Parquet, ORC, and Avro are widely used as data formats, which can significantly improve analytical query performance.
For a data lake to operate successfully, a data catalog, metadata management, access control, and data quality monitoring are essential. Data can be discovered and managed through AWS Glue Data Catalog, Apache Hive Metastore, Unity Catalog, and others. A data lake operated without proper governance can become a "Data Swamp," so it is important to establish data quality and governance policies from the initial design stage.
This is an example of implementing the Medallion Architecture on an AWS S3-based Data Lake and processing data with PySpark.
# Data Lake Medallion Architecture ꡬν
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from delta import * # Delta Lake μ¬μ© μ
import boto3
# Spark Session μμ± (S3 μ°λ)
spark = SparkSession.builder \
.appName("DataLakePipeline") \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
.config("spark.hadoop.fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem") \
.config("spark.hadoop.fs.s3a.aws.credentials.provider",
"com.amazonaws.auth.DefaultAWSCredentialsProviderChain") \
.getOrCreate()
# Data Lake κ²½λ‘ μ μ
DATA_LAKE_BUCKET = "s3a://company-data-lake"
BRONZE_PATH = f"{DATA_LAKE_BUCKET}/bronze"
SILVER_PATH = f"{DATA_LAKE_BUCKET}/silver"
GOLD_PATH = f"{DATA_LAKE_BUCKET}/gold"
# ============================================
# Bronze Layer: μμ λ°μ΄ν° μμ§
# ============================================
def ingest_to_bronze(source_path: str, table_name: str):
"""μμ λ°μ΄ν°λ₯Ό Bronze λ μ΄μ΄μ μ μ¬"""
# λ€μν ν¬λ§· μ§μ
if source_path.endswith('.json'):
df = spark.read.json(source_path)
elif source_path.endswith('.csv'):
df = spark.read.option("header", "true").csv(source_path)
elif source_path.endswith('.parquet'):
df = spark.read.parquet(source_path)
else:
# μ€νΈλ¦¬λ° λ°μ΄ν° (Kafka λ±)
df = spark.read.format("kafka") \
.option("kafka.bootstrap.servers", "kafka:9092") \
.option("subscribe", source_path) \
.load()
# λ©νλ°μ΄ν° μΆκ°
df_with_metadata = df \
.withColumn("_ingestion_timestamp", current_timestamp()) \
.withColumn("_source_file", lit(source_path)) \
.withColumn("_ingestion_date", current_date())
# Bronze λ μ΄μ΄μ μ μ₯ (νν°μ
: λ μ§λ³)
bronze_table_path = f"{BRONZE_PATH}/{table_name}"
df_with_metadata.write \
.format("delta") \
.mode("append") \
.partitionBy("_ingestion_date") \
.save(bronze_table_path)
print(f"Ingested {df_with_metadata.count()} records to Bronze: {table_name}")
return bronze_table_path
# ============================================
# Silver Layer: λ°μ΄ν° μ μ λ° λ³ν
# ============================================
def transform_to_silver(bronze_table: str, silver_table: str):
"""Bronze λ°μ΄ν°λ₯Ό μ μ νμ¬ Silver λ μ΄μ΄λ‘ λ³ν"""
bronze_path = f"{BRONZE_PATH}/{bronze_table}"
silver_path = f"{SILVER_PATH}/{silver_table}"
# Bronze λ°μ΄ν° μ½κΈ°
df_bronze = spark.read.format("delta").load(bronze_path)
# λ°μ΄ν° μ μ λ° λ³ν
df_silver = df_bronze \
.dropDuplicates(["id"]) \
.filter(col("id").isNotNull()) \
.withColumn("email", lower(trim(col("email")))) \
.withColumn("phone", regexp_replace(col("phone"), "[^0-9]", "")) \
.withColumn("created_at", to_timestamp(col("created_at"))) \
.withColumn("_processed_timestamp", current_timestamp())
# λ°μ΄ν° νμ§ κ²μ¦
quality_checks = {
"null_check": df_silver.filter(col("id").isNull()).count() == 0,
"email_format": df_silver.filter(~col("email").rlike("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$")).count() == 0,
"duplicate_check": df_silver.count() == df_silver.dropDuplicates(["id"]).count()
}
print("Data Quality Checks:", quality_checks)
# Silver λ μ΄μ΄μ Merge (Upsert)
if DeltaTable.isDeltaTable(spark, silver_path):
delta_table = DeltaTable.forPath(spark, silver_path)
delta_table.alias("target").merge(
df_silver.alias("source"),
"target.id = source.id"
).whenMatchedUpdateAll() \
.whenNotMatchedInsertAll() \
.execute()
else:
df_silver.write.format("delta").mode("overwrite").save(silver_path)
return silver_path
# ============================================
# Gold Layer: λΉμ¦λμ€ μ§κ³ λ°μ΄ν°
# ============================================
def aggregate_to_gold(silver_tables: list, gold_table: str):
"""Silver λ°μ΄ν°λ₯Ό μ§κ³νμ¬ Gold λ μ΄μ΄ μμ±"""
# μ¬λ¬ Silver ν
μ΄λΈ μ‘°μΈ
df_users = spark.read.format("delta").load(f"{SILVER_PATH}/users")
df_orders = spark.read.format("delta").load(f"{SILVER_PATH}/orders")
df_products = spark.read.format("delta").load(f"{SILVER_PATH}/products")
# λΉμ¦λμ€ λ©νΈλ¦ μ§κ³
df_gold = df_orders \
.join(df_users, "user_id") \
.join(df_products, "product_id") \
.groupBy(
date_trunc("month", col("order_date")).alias("month"),
col("category"),
col("region")
) \
.agg(
countDistinct("user_id").alias("unique_customers"),
count("order_id").alias("total_orders"),
sum("amount").alias("total_revenue"),
avg("amount").alias("avg_order_value"),
percentile_approx("amount", 0.5).alias("median_order_value")
) \
.withColumn("_aggregation_timestamp", current_timestamp())
# Gold λ μ΄μ΄μ μ μ₯
gold_path = f"{GOLD_PATH}/{gold_table}"
df_gold.write \
.format("delta") \
.mode("overwrite") \
.partitionBy("month") \
.save(gold_path)
return gold_path
# ============================================
# λ°μ΄ν° μΉ΄νλ‘κ·Έ λ±λ‘ (AWS Glue)
# ============================================
def register_to_glue_catalog(table_path: str, database: str, table_name: str):
"""Glue Data Catalogμ ν
μ΄λΈ λ±λ‘"""
# Glue μΉ΄νλ‘κ·Έμ ν
μ΄λΈ μμ±
spark.sql(f"""
CREATE TABLE IF NOT EXISTS glue_catalog.{database}.{table_name}
USING DELTA
LOCATION '{table_path}'
""")
# ν
μ΄λΈ ν΅κ³ μμ§
spark.sql(f"ANALYZE TABLE glue_catalog.{database}.{table_name} COMPUTE STATISTICS")
print(f"Registered table: {database}.{table_name}")
# ============================================
# λ°μ΄ν° λ μ΄ν¬ νμ΄νλΌμΈ μ€ν
# ============================================
if __name__ == "__main__":
# Bronze: μμ λ°μ΄ν° μμ§
ingest_to_bronze("s3a://raw-data/users/*.json", "users")
ingest_to_bronze("s3a://raw-data/orders/*.csv", "orders")
ingest_to_bronze("s3a://raw-data/products/*.parquet", "products")
# Silver: λ°μ΄ν° μ μ
transform_to_silver("users", "users")
transform_to_silver("orders", "orders")
transform_to_silver("products", "products")
# Gold: λΉμ¦λμ€ μ§κ³
aggregate_to_gold(
["users", "orders", "products"],
"monthly_sales_summary"
)
# Glue Catalog λ±λ‘
register_to_glue_catalog(f"{GOLD_PATH}/monthly_sales_summary", "analytics", "monthly_sales")
print("Data Lake Pipeline completed successfully!")
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free