Incremental data warehouse with Delta Lake CDC

Updated at:

This article describes the parameters, schema, and usage examples for the Delta Lake Change Data Capture (CDC) feature.

Background information

Change Data Capture (CDC) is a design pattern used to identify and capture changes made to data in a database and deliver these changes to a downstream system. The Delta Lake CDC feature gets change data directly from a Delta Lake source table.

Delta Lake CDC uses the Change Data Feed (CDF) feature, which allows you to track row-level changes in a Delta Lake table. When CDF is enabled, the runtime records and persists change data in directory files under the table path. With CDC, you can easily build an incremental data warehouse.

Limitations

The Delta Lake CDC feature is supported only on EMR clusters running version 3.41.0 (with Delta Lake 0.6.1) or later, or on clusters running version 5.9.0 (with Delta Lake 2.0) or later.

Parameters

SparkConf parameters

Parameter

Description

spark.sql.externalTableValuedFunctions

An EMR-specific Spark configuration that extends table-valued function capabilities in Spark 2.4.x. To run a CDF query with Spark SQL, set this parameter to table_changes.

spark.databricks.delta.changeDataFeed.timestampOutOfRange.enabled

Valid values:

  • false (Default): The CDF query throws an error if the specified startingTimestamp or endingTimestamp is invalid.

  • true: If the startingTimestamp is invalid, the query returns an empty result. If the endingTimestamp is invalid, the query returns data from the latest available snapshot.

Note

This parameter takes effect only in Delta Lake 2.x versions.

CDC write parameters

Parameter

Description

delta.enableChangeDataFeed

Specifies whether to enable CDF. Valid values:

  • false (Default): CDF is not enabled.

  • true: CDF is enabled.

CDC read parameters

The following parameters are required only for DataFrame and Spark Streaming modes.

Parameter

Description

readChangeFeed

If set to true, the query returns the change data from the table. This option requires either the startingVersion or startingTimestamp parameter.

startingVersion

Takes effect only when readChangeFeed is set to true. This parameter specifies the starting version of the change data to read.

endingVersion

Takes effect only when readChangeFeed is set to true. This parameter specifies the ending version of the change data to read.

startingTimestamp

Takes effect only when readChangeFeed is set to true. This parameter specifies the starting timestamp of the change data to read.

endingTimestamp

Takes effect only when readChangeFeed is set to true. This parameter specifies the ending timestamp of the change data to read.

Schema

A Delta Lake CDF query returns a schema that includes the columns from the original table, plus the following three additional fields:

  • _change_type: Indicates the type of change event. Valid values:

    • insert: A newly inserted row.

    • delete: A deleted row.

    • update_preimage and update_postimage: Two rows represent each update. update_preimage contains the values before the update, and update_postimage contains the values after the update.

  • _commit_version: The version of the Delta table commit that contains the change.

  • _commit_timestamp: The timestamp of the Delta table commit that contains the change.

Usage examples

Spark SQL example

Important

The Spark SQL syntax is supported only in EMR Spark 2 with Delta Lake 0.6.1.

To use Spark SQL syntax on EMR Spark 2, configure the following parameter:

spark-sql --conf spark.sql.externalTableValuedFunctions=table_changes

The following example shows the SQL syntax:

-- Create a Delta table with CDF enabled
CREATE TABLE cdf_tbl (id int, name string, age int) USING delta
TBLPROPERTIES ("delta.enableChangeDataFeed" = "true");
-- Insert Into
INSERT INTO cdf_tbl VALUES (1, 'XUN', 32), (2, 'JING', 30);
-- Insert Overwrite
INSERT OVERWRITE TABLE cdf_tbl VALUES (1, 'a1', 30), (2, 'a2', 32), (3, "a3", 32);
-- Update
UPDATE cdf_tbl set age = age + 1;
-- Merge Into
CREATE TABLE merge_source (id int, name string, age int) USING delta;
INSERT INTO merge_source VALUES (1, "a1", 31), (2, "a2_new", 33), (4, "a4", 30);
MERGE INTO cdf_tbl target USING merge_source source
ON target.id = source.id
WHEN MATCHED AND target.id % 2 == 0 THEN UPDATE SET name = source.name
WHEN MATCHED THEN DELETE
WHEN NOT MATCHED THEN INSERT *;
-- Delete
DELETE FROM cdf_tbl WHERE age >= 32;
-- CDF Query
-- Query all change data starting from version 0.
select * from table_changes("cdf_tbl", 0);
select * from table_changes("cdf_tbl", '2023-02-03 15:33:34'); --'2023-02-03 15:33:34' is the commit timestamp for version 0.
-- Query the change data for version 4.
select * from table_changes("cdf_tbl", 4, 4);
select * from table_changes("cdf_tbl", '2023-02-03 15:34:06', '2023-02-03 15:34:06'); --'2023-02-03 15:34:06' is the commit timestamp for version 4.

The following code blocks show the results of the two queries.

Figure 1. Result of query 1

1       XUN     32      insert  1       2023-02-03 15:33:44
2       JING    30      insert  1       2023-02-03 15:33:44
1       a1      30      insert  2       2023-02-03 15:33:47
2       a2      32      insert  2       2023-02-03 15:33:47
3       a3      32      insert  2       2023-02-03 15:33:47
1       XUN     32      delete  2       2023-02-03 15:33:47
2       JING    30      delete  2       2023-02-03 15:33:47
1       a1      30      update_preimage 3       2023-02-03 15:33:50
1       a1      31      update_postimage        3       2023-02-03 15:33:50
2       a2      32      update_preimage 3       2023-02-03 15:33:50
2       a2      33      update_postimage        3       2023-02-03 15:33:50
3       a3      32      update_preimage 3       2023-02-03 15:33:50
3       a3      33      update_postimage        3       2023-02-03 15:33:50
2       a2      33      update_preimage 4       2023-02-03 15:34:06
2       a2_new  33      update_postimage        4       2023-02-03 15:34:06
1       a1      31      delete  4       2023-02-03 15:34:06
4       a4      30      insert  4       2023-02-03 15:34:06
2       a2_new  33      delete  5       2023-02-03 15:34:10
3       a3      33      delete  5       2023-02-03 15:34:10
Time taken: 1.705 seconds, Fetched 19 row(s)

Figure 2. Result of query 2

2        a2      33      update_preimage 4       2023-02-03 15:34:06
2        a2_new  33      update_postimage        4               2023-02-03 15:34:06
1        a1      31      delete 4        2023-02-03 15:34:06
4        a4      30      insert 4        2023-02-03 15:34:06
Time taken: 1.058 seconds, Fetched 4 row(s)

DataFrame example

// Create and write to a Delta table with CDF enabled
val df = Seq((1, "XUN", 32), (2, "JING", 30)).toDF("id", "name", "age")
df.write.format("delta").mode("append")
  .option("delta.enableChangeDataFeed", "true") // Enable CDF when you first write to the table. This option is not needed for subsequent writes.
  .saveAsTable("cdf_table")
// Query the change data by using a DataFrame
spark.read.format("delta")
  .option("readChangeFeed", "true")
  .option("startingVersion", 0)
  .option("endingVersion", 4) // This option is optional.
  .table("cdf_table")

Spark Streaming example

// Streaming CDF Query Using Dats
spark.read.format("delta")
  .option("readChangeFeed", "true")
  .option("startingVersion", 0)
  .option("endingVersion", 4) // This option is optional.
  .table("cdf_table")