from delta.tables import DeltaTable from pyspark.sql import SparkSession spark = SparkSession.builder.appName('DeltaExample').getOrCreate() # Create initial DataFrame initial_data = [(1, 'apple'), (2, 'banana')] df = spark.createDataFrame(initial_data, ['id', 'fruit']) df.write.format('delta').mode('overwrite').save('/tmp/delta-table') deltaTable = DeltaTable.forPath(spark, '/tmp/delta-table') # Start transaction: update and insert (deltaTable.alias('t') .merge( spark.createDataFrame([(2, 'blueberry'), (3, 'cherry')], ['id', 'fruit']).alias('s'), 't.id = s.id') .whenMatchedUpdate(set={'fruit': 's.fruit'}) .whenNotMatchedInsert(values={'id': 's.id', 'fruit': 's.fruit'}) .execute()) # Read final table final_df = spark.read.format('delta').load('/tmp/delta-table') print(final_df.count())
The merge updates the row with id=2 and inserts a new row with id=3. The original row with id=1 remains unchanged. So total rows are 3.
Delta Lake provides full ACID guarantees: atomic commits, consistent data state, isolation of concurrent transactions, and durable storage of committed data.
from delta.tables import DeltaTable from pyspark.sql import SparkSession spark = SparkSession.builder.appName('DeltaDebug').getOrCreate() # Create initial Delta table initial_data = [(1, 'apple')] df = spark.createDataFrame(initial_data, ['id', 'fruit']) df.write.format('delta').mode('overwrite').save('/tmp/delta-table') deltaTable = DeltaTable.forPath(spark, '/tmp/delta-table') # Attempt to update without condition (deltaTable.update(set={'fruit': 'orange'}))
The update() method requires a condition argument to specify which rows to update. Omitting it causes a TypeError.
from delta.tables import DeltaTable from pyspark.sql import SparkSession spark = SparkSession.builder.appName('DeltaConcurrent').getOrCreate() # Initial data initial_data = [(1, 'apple'), (2, 'banana'), (3, 'cherry')] df = spark.createDataFrame(initial_data, ['id', 'fruit']) df.write.format('delta').mode('overwrite').save('/tmp/delta-table') deltaTable = DeltaTable.forPath(spark, '/tmp/delta-table') # Simulate Transaction 1 (deltaTable.alias('t') .merge( spark.createDataFrame([(4, 'date')], ['id', 'fruit']).alias('s'), 't.id = s.id') .whenNotMatchedInsertAll() .execute()) # Simulate Transaction 2 deltaTable.update(condition="id = 2", set={"fruit": "blackberry"}) final_df = spark.read.format('delta').load('/tmp/delta-table') final_df.orderBy('id').show()
Both transactions commit successfully. Transaction 1 inserts a new row with id=4. Transaction 2 updates id=2. The final table has all four rows with updated values.
Delta Lake uses optimistic concurrency control with a transaction log to ensure ACID compliance and prevent write conflicts in concurrent environments.
