2: Ingest and transform data

    Design and implement full and incremental data loads

    Full and incremental loading are the two primitives at the base of every data engineering pipeline in Microsoft Fabric. A full load reads the entire source and writes the entire target. An incremental load reads only what changed since the last successful run and applies those changes to the target. The choice between the two is driven by source size, source change rate, target latency requirements, downstream consumers, and the schema enforcement needs of the destination table.

    Full load patterns

    A full load is implemented in two forms: overwrite and snapshot. The overwrite form truncates the destination Delta table and writes the source in a single atomic transaction. With Delta tables in a Lakehouse, this is a single Spark write with mode overwrite and an optional overwriteSchema flag when the source schema has drifted.

    (
     spark.read.format("parquet")
     .load("Files/raw/customers/")
     .write.format("delta")
     .mode("overwrite")
     .option("overwriteSchema", "true")
     .saveAsTable("lkh_sales.dim_customer_full")
    )
    

    The snapshot form preserves history by appending a partition keyed on the load date, so each run produces an independent copy of the source. Snapshots are common for type-2 dimensions where the prior state must be queryable, and for compliance scenarios that demand point-in-time reconstruction.

    Full loads work when the source is small enough that a complete read fits inside the available capacity unit budget, or when the source lacks a reliable change marker. They are simple, idempotent, and avoid the watermark bookkeeping that incremental patterns require, but they consume time and capacity proportional to the source size on every run.

    Incremental load patterns

    Incremental loads come in three flavors: watermark, change feed, and changelog. Watermark loads pick a monotonically increasing column (an UpdatedAt timestamp or a sequential LoadId), record the maximum value seen on the prior run, and filter the source on column > last_watermark on the next run. The watermark itself is stored in a control table inside the Lakehouse or Warehouse, or in a pipeline variable persisted between runs.

    SELECT *
    FROM dbo.sales_orders
    WHERE LastModifiedUtc > '@{activity('LookupWatermark').output.firstRow.last_value}'
    

    Change feed loads read a database's native CDC stream. For mirrored Azure SQL Database or Fabric SQL Database, the change feed is exposed inside the mirrored Delta tables, with an operation indicator column distinguishing inserts, updates, and deletes following SQL Server CDC conventions.

    Changelog loads consume an append-only event source (an Eventstream output, a Kafka topic, or an external append-only Delta path) and apply each row as a discrete change.

    The MERGE operation

    Once a delta of source rows is in hand, applying it to the target requires a MERGE. Delta Lake's MERGE syntax matches rows on a business key, updates matching rows, inserts unmatched source rows, and optionally deletes target rows that no longer appear in source.

    MERGE INTO lkh_sales.dim_customer AS target
    USING (SELECT * FROM staging.customer_delta) AS source
    ON target.customer_id = source.customer_id
    WHEN MATCHED AND source.is_deleted = 1 THEN DELETE
    WHEN MATCHED AND target.row_hash <> source.row_hash THEN UPDATE SET *
    WHEN NOT MATCHED THEN INSERT *
    

    The MERGE is atomic at the Delta transaction level. Two concurrent MERGE statements against the same partition will be serialized by Delta's optimistic concurrency control, and the loser will be retried or fail with a ConcurrentAppendException. Partition the target by a column that aligns with the merge predicate to reduce file rewrite scope.

    Transform data by using PySpark, SQL, and KQL

    The same transformation can be expressed in PySpark, T-SQL inside a Warehouse, Spark SQL inside a notebook, or KQL inside an Eventhouse, and the choice has consequences for capacity consumption, latency, and team skills.

    PySpark is the strongest fit for code-heavy transformations: complex joins across many tables, UDFs that need Python libraries, streaming pipelines that materialize Delta tables, and machine learning feature engineering. A Lakehouse notebook running on a Spark pool reads Delta tables, applies DataFrame operations, and writes back to Delta. Spark SQL inside the same notebook is the same engine with SQL syntax, suitable when the transformation is expressible as a query plan.

    from pyspark.sql import functions as F
    
    orders = spark.table("lkh_sales.fact_orders")
    customers = spark.table("lkh_sales.dim_customer")
    
    enriched = (
     orders.join(customers, "customer_id", "left")
     .withColumn("order_year", F.year("order_date"))
     .groupBy("order_year", "customer_segment")
     .agg(F.sum("order_total").alias("revenue"))
    )
    
    enriched.write.mode("overwrite").saveAsTable("lkh_sales.agg_revenue_by_segment")
    

    T-SQL inside a Warehouse is the right surface when the transformation needs full DML (INSERT, UPDATE, DELETE, MERGE), when stored procedures are required, or when downstream tools expect a SQL Server style endpoint. The Warehouse engine is a distributed MPP engine over Parquet, and T-SQL there compiles to distributed query plans.

    KQL is the choice for transformations over append-only telemetry stored in an Eventhouse KQL Database. KQL queries can be materialized as functions or as update policies that automatically transform rows as they land in a source table.

    .create function 
    with (folder = "transform", docstring = "Enrich raw events with device metadata")
    EnrichEvents() {
     raw_events
     | lookup kind=leftouter device_metadata on device_id
     | extend event_hour = bin(timestamp, 1h)
     | project event_id, device_id, device_type, event_hour, payload
    }
    

    Process data by using Spark Structured Streaming

    Spark Structured Streaming inside a Fabric notebook reads from a streaming source (an Eventstream output to a Lakehouse, an Event Hub, a Kafka topic, or a Delta change feed), applies DataFrame operations, and writes to a Delta sink. The same DataFrame API is used for batch and streaming, with the addition of trigger configuration, watermarks for late data, and checkpoint locations for fault tolerance.

    from pyspark.sql import functions as F
    
    stream = (
     spark.readStream
     .format("delta")
     .option("ignoreChanges", "true")
     .table("lkh_sales.raw_events_bronze")
    )
    
    aggregated = (
     stream
     .withWatermark("event_time", "10 minutes")
     .groupBy(F.window("event_time", "5 minutes"), "device_id")
     .agg(F.count("*").alias("event_count"))
    )
    
    query = (
     aggregated.writeStream
     .format("delta")
     .outputMode("append")
     .option("checkpointLocation", "Files/checkpoints/events_5min/")
     .trigger(processingTime="1 minute")
     .toTable("lkh_sales.agg_events_5min")
    )
    

    The checkpoint location stores stream state (offsets, watermark progress, and aggregation state). Deleting the checkpoint forces a restart from the source's earliest available position and discards in-flight aggregation state. The trigger controls latency: processingTime triggers a micro-batch at the specified cadence, availableNow processes all available data and stops, and continuous is reserved for low-latency single-row processing scenarios with limited operator support.

    💡 Exam Trap: A watermark of "10 minutes" means rows arriving more than 10 minutes after their event time are dropped, not that the stream waits 10 minutes before emitting. Confusing watermark slack with trigger interval is a frequent error.

    📊 Limit: Delta MERGE rewrites every file that contains at least one matched row. With a partition key aligned to the merge predicate, only the affected partitions' files are rewritten. With no partitioning, the entire table can rewrite for a small delta.

    ⚠️ Anti-Pattern: Running a full overwrite load against a source larger than the available Spark pool's memory budget. Memory pressure spills to disk and inflates wall-clock time. Switch to an incremental MERGE or a partitioned snapshot pattern.

    🎯 Scenario: A daily sales feed loads 200 million rows from an on-premises SQL Server into a Lakehouse fact table. The source exposes a LastModifiedUtc column updated by every insert and update, but deletes are soft-deleted with an IsDeleted flag. The correct pattern is an incremental watermark load using LastModifiedUtc to filter source rows, followed by a MERGE that handles updates and converts the IsDeleted flag into a DELETE action against the target. A full overwrite would consume capacity proportional to the full 200 million rows on every run.

    Decision Anchor: Choose a full load when the source is small (under a few million rows) or lacks a reliable change marker. Choose an incremental watermark load when the source has a monotonically increasing change column and is too large to fully refresh. Choose a change feed or CDC load when the source's CDC stream is available and deletes must be captured.

    Watermark bookkeeping requires a control table or a persisted pipeline variable. The control table approach is preferred because it survives pipeline rewrites and provides an audit trail. A common schema for a watermark control table includes source_name, last_watermark_value, last_run_utc, row_count, and status, with a row per source and an update inside the same notebook session that produced the load.

    When the watermark column is a string-encoded timestamp, take care to convert to a comparable type before filtering. A naive string comparison of ISO 8601 timestamps is correct for UTC strings with consistent precision, but a comparison of mixed-format strings will produce silently wrong results. Cast to TIMESTAMP in the source query.

    Incremental loads also need a strategy for backfills. When a source's schema or business logic changes, prior periods may need to be reloaded. A backfill pattern reloads a specific date range with an explicit watermark override, then resets the control table to the maximum of the original watermark and the backfilled range. Pipelines support this through a parameterized notebook with a start_date and end_date parameter that, when set, overrides the watermark lookup.

    For incremental loads against a source without a reliable change column, two fallback patterns apply. The first is a full hash compare: compute a row hash on every source row, MERGE on the business key, and update when hashes differ. This produces correct results but reads the entire source on every run. The second is a partial scan keyed on a coarse column such as CreatedDate, accepting that updates to rows older than the scan window will be missed.

    The transformation surface choice also affects the partitioning strategy of the destination. PySpark writes to a Lakehouse Delta table support partitioning by one or more columns via partitionBy. T-SQL writes to a Warehouse use distribution and partition hints set at table creation. KQL update policies write to a source table, and partitioning there follows the table's ingestion-time partitioning rules.

    The relationship between batch incremental loads and the Spark Structured Streaming pattern is closer than it appears. A streaming query with trigger(availableNow=True) runs as a batch but uses the streaming checkpoint to track progress in source files or Delta versions. This pattern is valuable for incremental ingestion of files arriving in a folder: the checkpoint records which files have been processed, so a subsequent run picks up only new files. It is also a natural fit for incremental MERGE patterns where the source is a Delta change feed.

    changes = (
     spark.readStream
     .format("delta")
     .option("readChangeFeed", "true")
     .option("startingVersion", "5")
     .table("lkh_sales.fact_orders_source")
    )
    
    def upsert_to_target(batch_df, batch_id):
     batch_df.createOrReplaceTempView("source_changes")
     spark.sql("""
     MERGE INTO lkh_sales.fact_orders AS target
     USING (
     SELECT * FROM source_changes
     WHERE _change_type IN ('insert', 'update_postimage')
     ) AS src
     ON target.order_id = src.order_id
     WHEN MATCHED THEN UPDATE SET *
     WHEN NOT MATCHED THEN INSERT *
     """)
    
    changes.writeStream \
     .foreachBatch(upsert_to_target) \
     .option("checkpointLocation", "Files/checkpoints/fact_orders_cdf/") \
     .trigger(availableNow=True) \
     .start()
    

    The Delta change feed pattern combines the strengths of streaming (checkpointed progress, ordered changes) with batch MERGE (transactional upserts), and is one of the standard patterns for incremental loading inside Fabric.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Microsoft - DP-700 learning hub.