<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrii Salata on Medium]]></title>
        <description><![CDATA[Stories by Andrii Salata on Medium]]></description>
        <link>https://medium.com/@4andrij?source=rss-1758d019bf7f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Andrii Salata on Medium</title>
            <link>https://medium.com/@4andrij?source=rss-1758d019bf7f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:42:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@4andrij/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unlocking MERGE, UPDATE, and DELETE Operations in Structured Streaming on Databricks]]></title>
            <link>https://medium.com/@4andrij/unlocking-merge-update-and-delete-operations-in-structured-streaming-on-databricks-ceb9fcd18c76?source=rss-1758d019bf7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceb9fcd18c76</guid>
            <dc:creator><![CDATA[Andrii Salata]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 14:37:53 GMT</pubDate>
            <atom:updated>2026-02-19T14:37:53.054Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven world, the ability to process and analyze data in real-time is crucial for businesses to stay competitive. Databricks is a unified data analytics platform that simplifies big data processing by providing a seamless environment for working with Apache Spark™, Delta Lake, and other data technologies. Built to handle large-scale data processing, Databricks enables organizations to build robust data pipelines, perform advanced analytics, and leverage machine learning with ease.</p><p>One of the standout features of Databricks is Structured Streaming, a scalable and fault-tolerant stream processing engine built on top of Apache Spark. Structured Streaming allows users to process massive streams of data in real-time, ensuring exactly-once processing guarantees, automatic recovery from failures, and seamless integration with various data sources and sinks. The key benefits of using Structured Streaming with large-scale data include:</p><ol><li>Scalability: Structured Streaming can handle millions of events per second, making it ideal for processing large volumes of streaming data.</li><li>Fault Tolerance: Built on the distributed nature of Apache Spark, Structured Streaming automatically handles failures and ensures data integrity through its exactly-once processing semantics.</li><li>Ease of Use: With its high-level API, developers can write concise and expressive streaming queries, reducing the complexity of building and maintaining streaming applications.</li><li>Seamless Integration: Structured Streaming integrates natively with Delta Lake, providing support for ACID transactions and schema enforcement, which are crucial for maintaining data quality in large-scale pipelines.</li></ol><p>However, while Structured Streaming excels at processing data streams in real-time, it has a notable limitation: it does not natively support MERGE, UPDATE, and DELETE operations on source tables. These operations are essential in many real-world scenarios where the underlying data can change over time.</p><p>In this article, we will explore why these operations are restricted in Structured Streaming and how you can overcome this limitation using Change Data Capture (CDC) and the enableChangeDataFeed option in Databricks. By the end of this article, you’ll learn how to unlock the full potential of Structured Streaming for dynamic data processing.</p><h4>Understanding the Limitation</h4><p>Structured Streaming is designed around the concept of append-only streaming sources, where data flows continuously in a single direction — into the system. This design choice simplifies the management of stateful streaming operations and ensures high throughput and low latency. However, it also introduces a significant limitation: no built-in support for MERGE, UPDATE, or DELETE operations on the source table.</p><p>These operations are critical in many real-world applications where data in the source tables can change over time. For example, consider a customer database where records are frequently updated or deleted. Without support for these operations, you would either miss out on capturing these changes in your streaming application or be forced to adopt complex workarounds.</p><h4>Diving Deeper into Change Data Capture (CDC)</h4><p>To address the challenge of capturing and processing data changes like INSERTs, UPDATEs, and DELETEs, the data engineering community employs a technique known as Change Data Capture (CDC). CDC is a set of software design patterns used to detect and track data changes in a source system, ensuring that downstream systems receive and process these changes accurately and efficiently.</p><p><strong>Key Aspects of CDC:</strong></p><ol><li>Real-time Data Synchronization: CDC enables the real-time or near-real-time synchronization of data between systems. This is crucial for applications like real-time analytics, monitoring, and ETL processes.</li><li>Efficiency: Instead of bulk data transfers, CDC captures only the changes (deltas), reducing the amount of data that needs to be processed and transferred.</li><li>Data Consistency and Integrity: By accurately capturing and applying changes, CDC ensures that the target systems remain consistent with the source, maintaining data integrity across platforms.</li></ol><p><strong>Common CDC Techniques:</strong></p><ul><li>Log-Based CDC: This method reads the database transaction logs to identify changes. It’s efficient and has minimal impact on the source system’s performance.</li><li>Trigger-Based CDC: Database triggers are set up on the source tables to capture changes. While straightforward, this approach can introduce overhead and affect performance.</li><li>Timestamp-Based CDC: Changes are identified based on timestamp columns in the tables. While simpler, it might miss out on some changes if not implemented carefully.</li></ul><p><strong>CDC in the Context of Databricks:</strong></p><p>Databricks integrates CDC capabilities through the Change Data Feed (CDF) feature available in Delta Lake tables. By enabling CDF, Delta Lake captures changes to tables, making it easier to propagate these changes downstream.</p><h4>The Solution: Using CDC and Change Data Feed</h4><p>To overcome the limitation of not supporting MERGE, UPDATE, and DELETE operations in Structured Streaming, Databricks provides a powerful feature called Change Data Feed (CDF). When enabled, CDF captures all changes to a Delta Lake table, including INSERTs, UPDATEs, and DELETEs, and exposes them in a consumable format. This integration allows streaming applications to process not just new data but also changes to existing data.</p><p><strong>Step 1: Enable Change Data Feed on the Source Table</strong></p><p>To start using CDC with CDF, you first need to enable the Change Data Feed on your source Delta Lake table. This is achieved by setting the delta.enableChangeDataFeed table property to true. You can do this either during table creation or by altering an existing table.</p><p><strong>Enabling CDF on Table Creation:</strong></p><pre>CREATE TABLE my_source_table (<br>id LONG,<br>name STRING,<br>value DOUBLE<br>) USING delta<br>TBLPROPERTIES (delta.enableChangeDataFeed = true);</pre><p><strong>Enabling CDF on an Existing Table:</strong></p><pre>ALTER TABLE my_source_table SET TBLPROPERTIES (delta.enableChangeDataFeed = true);</pre><p>Once enabled, Delta Lake starts recording all data changes, which can then be read and processed by downstream applications.</p><p><strong>Step 2: Reading the Change Data Stream</strong></p><p>With CDF enabled, you can read the stream of changes from the source table. The changes are exposed as a DataFrame where each record includes metadata columns indicating the type of operation and other relevant details.</p><p><strong>Reading Changes Using Structured Streaming:</strong></p><pre>from pyspark.sql.functions import expr</pre><pre># Define the starting point for reading changes<br>starting_version = 0  # You can also specify a timestamp or &#39;latest&#39;</pre><pre># Read the change data stream<br>cdc_df = (<br>    spark.readStream<br>    .format(&quot;delta&quot;)<br>    .option(&quot;readChangeData&quot;, &quot;true&quot;)<br>    .option(&quot;startingVersion&quot;, starting_version)<br>    .table(&quot;my_source_table&quot;)<br>    .withColumn(<br>        &quot;operation&quot;,<br>        expr(<br>            &quot;&quot;&quot;<br>            CASE<br>                WHEN _change_type = &#39;insert&#39; THEN &#39;INSERT&#39;<br>                WHEN _change_type = &#39;update_preimage&#39; THEN &#39;UPDATE_BEFORE&#39;<br>                WHEN _change_type = &#39;update_postimage&#39; THEN &#39;UPDATE_AFTER&#39;<br>                WHEN _change_type = &#39;delete&#39; THEN &#39;DELETE&#39;<br>            END<br>            &quot;&quot;&quot;<br>        )<br>    )<br>)</pre><p>Understanding Metadata Columns:</p><ul><li><strong>_change_type</strong>: Indicates the type of change. Possible values include insert, update_preimage, update_postimage, and delete.</li><li><strong>insert</strong>: Represents new rows inserted into the table.</li><li><strong>update_preimage</strong>: The state of the row before the update.</li><li><strong>update_postimage</strong>: The state of the row after the update.</li><li><strong>delete</strong>: Rows that have been deleted.</li><li><strong>_commit_version </strong>and <strong>_commit_timestamp</strong>: Provide information about the version of the table when the change was committed and the corresponding timestamp.</li></ul><p>By processing these metadata columns, you can determine how to apply the changes to your target systems.</p><p><strong>Step 3: Applying Changes to the Target Table</strong></p><p>The final step involves applying the captured changes to the target table, ensuring it remains in sync with the source. Depending on the operation type, different actions are required.</p><p><strong>Defining the Upsert Logic:</strong></p><pre>from delta.tables import DeltaTable<br>def upsert_to_target_table(microbatch_df, batch_id):<br>    # Load the target table as a DeltaTable<br>    target_table = DeltaTable.forName(spark, &quot;target_table&quot;)<br><br>    # Process INSERT and UPDATE_AFTER operations together<br>    inserts_and_updates = microbatch_df.filter(microbatch_df.operation.isin(&quot;INSERT&quot;, &quot;UPDATE_AFTER&quot;))<br>    <br>    # Process DELETE operations<br>    deletes = microbatch_df.filter(microbatch_df.operation == &quot;DELETE&quot;)<br><br>    # Apply INSERTs and UPDATEs<br>    if not inserts_and_updates.isEmpty():<br>        (<br>            target_table.alias(&quot;t&quot;)<br>            .merge(<br>                inserts_and_updates.alias(&quot;s&quot;),<br>                &quot;t.id = s.id&quot;<br>            )<br>            .whenMatchedUpdateAll()<br>            .whenNotMatchedInsertAll()<br>            .execute()<br>        )<br>    <br>    # Apply DELETEs<br>    if not deletes.isEmpty():<br>        ids_to_delete = [row.id for row in deletes.select(&quot;id&quot;).collect()]<br>        (<br>            target_table<br>            .delete(condition=f&quot;id IN ({&#39;, &#39;.join(map(str, ids_to_delete))})&quot;)<br>        )</pre><p><strong>Starting the Structured Streaming Query:</strong></p><pre>(<br>    cdc_df.writeStream<br>    .format(&quot;delta&quot;)<br>    .foreachBatch(upsert_to_target_table)<br>    .outputMode(&quot;update&quot;)<br>    .option(&quot;checkpointLocation&quot;, &quot;/path/to/checkpoint/dir&quot;)<br>    .start()<br>)</pre><p><strong>Key Points in the Upsert Logic:</strong></p><ul><li>Merge Operations: Using Delta Lake’s MERGE functionality, the logic updates existing records and inserts new ones based on the incoming changes.</li><li>Handling Deletes: Delete operations are applied by specifying the IDs of records to be removed from the target table.</li><li>Batch Processing: The foreachBatch mechanism processes micro-batches of data, ensuring efficient and atomic operations.</li></ul><h4>Conclusion</h4><p>While Structured Streaming’s design does not support MERGE, UPDATE, and DELETE operations out-of-the-box, we still may consume key benefits of Structured Streaming with data sources, that contain such operations. The combination of Change Data Capture (CDC) and Change Data Feed (CDF) in Databricks offers this powerful and flexible solution. By leveraging these features, you can capture and apply changes from your source tables in real-time, ensuring that your streaming pipelines remain up-to-date with the latest data.</p><p>This approach not only maintains data consistency across systems but also optimizes resource utilization by processing only the changes rather than entire datasets. As data systems continue to evolve, integrating CDC patterns with streaming architectures will be pivotal in building responsive, reliable, and efficient data applications.</p><p>More over this approach allows to maintain aggregations wich handle deletions and updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceb9fcd18c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>