How do I update a large SQL table using pyspark?

Viewed 1431

I am building an etl using pyspark in databricks.

I have a source SQL table with roughly 10 million rows of data which I want to load into a SQL staging table.

I have two basic requirements:-

  1. When a row is added to the source table, it must to inserted into the staging table.
  2. When a row is updated to the source table, it must to updated into the staging table.

Source data

Thankfully the source table has two timestamp columns for created and updated time. I can query the new and updated data using these two columns and put it into a dataframe called source_df.

Target data

I load all the keys (IDs) from the staging table into a dataframe called target_df.

Working out changes

I join the two dataframe together based on the key to work out which rows already exist (which form updates), and which rows don't exist (which form inserts). This gives me two new dataframes, inserts_df and updates_df.

Inserting new rows

This is easy because I can just use inserts_df.write to directly write into the staging table. Job done!

Updating existing rows

This is what I can't figure out as there is little in the way of existing examples. I am lead to believe that you can't do updates using pyspark. I could use the "overwrite" mode to replace the SQL table, but it doesn't make a lot of sense to replace 10 million rows when I only want to update half a dozen.

How can I effectively get the rows from updates_df into SQL without overwriting the whole table?

0 Answers
Related