Writing Data to an Iceberg Table Using Spark
Iceberg uses Apache Spark's DataSourceV2 API for data source and catalog implementations. Spark DSv2 is an evolving API with different levels of support in Spark versions. Table 1 lists the detailed API functions. Some functions are only available when using Iceberg SQL extensions in Spark 3.
| Function | Description | Usage Requirements |
|---|---|---|
| INSERT INTO | SQL statement used to append new data to a table. | Requires spark.sql.storeAssignmentPolicy=ANSI (default since Spark 3.0) |
| MERGE INTO | SQL statement used for row-level updates. | Requires Iceberg Spark extensions. |
| INSERT OVERWRITE | SQL statement used to replace data in the table with the result of a query. | Requires spark.sql.storeAssignmentPolicy=ANSI (default since Spark 3.0) |
| DELETE FROM | SQL statement used to remove data that meets criteria from tables. | Row-level delete requires Iceberg Spark extensions. |
| UPDATE | SQL statement used by update queries to accept a filter to match rows to update and update fields in the rows. | Requires Iceberg Spark extensions. |
| DataFrame appending | You can use append to append a dataframe to an Iceberg table. | - |
| DataFrame overwriting | You can use overwritePartitions() to overwrite partitions dynamically. | - |
| DataFrame CTAS and RTAS | You can use the create, replace, or createOrReplace to run a CTAS or RTAS to perform creation and replacement operations. | Requires the DataSourceV2 API. |
Writing Data with SQL
Spark 3 supports SQL INSERT INTO, MERGE INTO, and INSERT OVERWRITE, as well as the new DataFrameWriterV2 API.
- INSERT INTO
To append new data to a table, use INSERT INTO.
Create a table.
CREATE TABLE prod.db.table (id bigint, data string) USING iceberg;
Write data.
- Example 1:
INSERT INTO prod.db.table VALUES (1, 'a'), (2, 'b');
- Example 2:
INSERT INTO prod.db.table SELECT ...;
- Example 1:
- MERGE INTO
Spark 3 added support for MERGE INTO queries that can express row-level updates.
Iceberg supports MERGE INTO by rewriting data files that contain rows that need to be updated in an overwrite commit. MERGE INTO is recommended instead of INSERT OVERWRITE because Iceberg can replace only the affected data files, and the data overwritten by a dynamic overwrite may change if the table's partitioning changes.
MERGE INTO updates the target table using a set of updates from another query. The update for a row in the target table is found using the ON clause.
MERGE INTO prod.db.target t USING (SELECT ...) s ON t.id = s.id WHEN ...;
Updates to rows in the target table are listed using WHEN MATCHED ... THEN ..... Multiple MATCHED clauses can be added with conditions that determine when each match should be applied. The first matching expression is used.
- Example 1:
WHEN MATCHED AND s.op = 'delete' THEN DELETE
- Example 2:
WHEN MATCHED AND t.count IS NULL AND s.op = 'increment' THEN UPDATE SET t.count = 0
- Example 3:
WHEN MATCHED AND s.op = 'increment' THEN UPDATE SET t.count = t.count + 1
Source rows (updates) that do not match can be inserted into the target table using WHEN NOT MATCHED.WHEN NOT MATCHED THEN INSERT *
Inserts also support additional conditions.
WHEN NOT MATCHED AND s.event_time > still_valid_threshold THEN INSERT (id, count) VALUES (s.id, 1)
Only one record in the source data can update any given row of the target table, or else an error will be thrown.
- Example 1:
- INSERT OVERWRITE
INSERT OVERWRITE can replace data in the table with the result of a query. Overwrites are atomic operations for Iceberg tables.
The partitions that will be replaced by INSERT OVERWRITE depends on Spark's partition overwrite mode and the partitioning of a table. MERGE INTO can rewrite only affected data files and has more easily understood behavior, so it is recommended instead of INSERT OVERWRITE.
- Overwrite behavior
The Spark's default overwrite mode is static, but the dynamic overwrite mode is recommended when you write data to Iceberg tables. The static overwrite mode determines which partitions to overwrite in a table by converting the PARTITION clause to a filter, but the PARTITION clause can only reference table columns.
The dynamic overwrite mode is configured by setting spark.sql.sources.partitionOverwriteMode=dynamic.
The following example demonstrates the behavior of dynamic and static overwrites:
Create a logs table defined by the following DDL:
CREATE TABLE prod.my_app.logs (uuid string NOT NULL, level string NOT NULL, ts timestamp NOT NULL, message string) USING iceberg PARTITIONED BY (level, hours(ts));
- Dynamic overwrite
When the Spark's overwrite mode is dynamic, partitions that have rows in the query result will be replaced.
For example, this query removes duplicate log events from the logs table.
INSERT OVERWRITE prod.my_app.logs SELECT uuid, first(level), first(ts), first(message) FROM prod.my_app.logs WHERE cast(ts as date) = '2020-07-01' GROUP BY uuid;
In dynamic mode, this operation will replace any partition with rows in the query result. Because the date of all rows is restricted to July 1, only hours of that day will be replaced.
- Static overwrite
When the Spark's overwrite mode is static, the PARTITION clause is converted to a filter that is used to delete data from the table. If the PARTITION clause is omitted, all partitions will be replaced.
Because there is no PARTITION clause in the query above, it will drop all existing rows in the table when in static mode, but will only write the logs from July 1.
To overwrite just the partitions that were loaded, add a PARTITION clause that aligns with the SELECT query filter.
INSERT OVERWRITE prod.my_app.logs PARTITION (level = 'INFO') SELECT uuid, first(level), first(ts), first(message) FROM prod.my_app.logs WHERE level = 'INFO' GROUP BY uuid;
Note that this mode cannot replace hourly partitions like the dynamic example query because the PARTITION clause can only reference table columns, not hidden partitions.
- Dynamic overwrite
- Overwrite behavior
- DELETE FROM
Spark 3 added support for DELETE FROM queries to remove data from tables.
Delete queries accept a filter (WHERE clause) to match rows to delete. Only the rows that match the filter are deleted, and the operation is atomic for Iceberg tables.
Example 1:
DELETE FROM prod.db.table WHERE ts >= '2020-05-01 00:00:00' and ts < '2020-06-01 00:00:00';
Example 2:
DELETE FROM prod.db.all_events WHERE session_time < (SELECT min(session_time) FROM prod.db.good_events);
Example 3:
DELETE FROM prod.db.orders AS t1 WHERE EXISTS (SELECT oid FROM prod.db.returned_orders WHERE t1.oid = oid);
If the delete filter matches entire partitions of the table, Iceberg will perform a metadata-only delete without rewriting data files, providing high performance.
If the filter matches individual rows of a table, then Iceberg will rewrite only the affected data files. It reads the original data file, filters out the rows to be deleted, writes to a new file, and updates the metadata to reference the new file. This approach minimizes the amount of data processed.
- UPDATE
UPDATE queries accept a filter to match rows to update and update fields of the rows.
Example 1:
UPDATE prod.db.table SET c1 = 'update_c1', c2 = 'update_c2' WHERE ts >= '2020-05-01 00:00:00' and ts < '2020-06-01 00:00:00';
Example 2:
UPDATE prod.db.all_events SET session_time = 0, ignored = true WHERE session_time < (SELECT min(session_time) FROM prod.db.good_events);
Example 3:
UPDATE prod.db.orders AS t1 SET order_status = 'returned' WHERE EXISTS (SELECT oid FROM prod.db.returned_orders WHERE t1.oid = oid);
For more complex row-level updates based on incoming data, see the section on MERGE INTO.
Writing to Branches
The branch must exist before performing the write. The operation does not create the branch if it does not exist. For more information on branches, refer to Branching and Tagging DDL.
- Writing to a branch using SQL statements
Branch writes can be performed via SQL by providing a branch identifier, branch_yourBranch, in the operation. Branch writes can also be performed as part of a write-audit-publish (WAP) workflow by specifying the spark.wap.branch configuration. Note that the WAP branch and branch identifier cannot both be specified.
MERGE INTO branch data:
MERGE INTO prod.db.table.branch_audit t USING (SELECT ...) s ON t.id = s.id WHEN ...;
UPDATE branch data:
UPDATE prod.db.table.branch_audit AS t1 SET val = 'c';
Delete branch data.
DELETE FROM prod.dbl.table.branch_audit WHERE id = 2;
WAP branch write:
- Configure spark.wap.branch.
SET spark.wap.branch = audit-branch;
- Insert data.
INSERT INTO prod.db.table VALUES (3, 'c');
- Configure spark.wap.branch.
- Writing data to a branch using DataFrames
When writing data to a branch using DataFrames, you also need to specify the branch identifier branch_yourBranch in the operation.
Example 1:
val data: DataFrame = ... data.writeTo("prod.db.table.branch_audit").append();Example 2:
val data: DataFrame = ... data.writeTo("prod.db.table.branch_audit").overwritePartitions();
Writing with DataFrames
Spark 3 introduced the new DataFrameWriterV2 API for writing to tables using data frames. The v2 API is recommended for several reasons:
- CTAS, RTAS, and overwrite by filter are supported.
- All operations consistently write columns to a table by name.
- Hidden partition expressions are supported in partitionedBy.
- Overwrite behavior is explicit, either dynamic or by a user-supplied filter.
- The behavior of each operation corresponds to SQL statements.
- df.writeTo(t).create() is equivalent to CREATE TABLE AS SELECT.
- df.writeTo(t).replace() is equivalent to REPLACE TABLE AS SELECT.
- df.writeTo(t).append() is equivalent to INSERT INTO.
- df.writeTo(t).overwritePartitions() is equivalent to dynamic INSERT OVERWRITE.
The v1 DataFrame write API is still supported, but is not recommended.
- Appending data
To append a dataframe to an Iceberg table, use append.
val data: DataFrame = ... data.writeTo("prod.db.table").append() - Overwriting data
To overwrite partitions dynamically, use overwritePartitions().
val data: DataFrame = ... data.writeTo("prod.db.table").overwritePartitions()To explicitly overwrite partitions, use overwrite to supply a filter.
data.writeTo("prod.db.table").overwrite($"level" === "INFO") - Creating tables
To run a CTAS or RTAS, use create, replace, or createOrReplace operations.
val data: DataFrame = ... data.writeTo("prod.db.table").create()If you have replaced the default Spark catalog (spark_catalog) with Iceberg's SparkSessionCatalog, use the following:
val data: DataFrame = ... data.writeTo("db.table").using("iceberg").create()Create and replace operations support table configuration methods, like partitionedBy and tableProperty.
data.writeTo("prod.db.table").tableProperty("write.format.default", "orc").partitionedBy($"level", days($"ts")).createOrReplace()The Iceberg table location can also be specified by the location table property.
data.writeTo("prod.db.table").tableProperty("location", "/path/to/location").createOrReplace() - Schema merge
While inserting or updating, Iceberg is capable of resolving schema mismatch at runtime. If properly configured, Iceberg will perform an automatic schema evolution as follows:
- A new column is present in the source but not in the target table: The new column is added to the target table. Column values are set to NULL in all the rows already present in the table.
- A column is present in the target but not in the source: The target column value is set to NULL during inserting or left unchanged during row updating.
The target table must be configured to accept any schema change by setting the property write.spark.accept-any-schema to true.
ALTER TABLE prod.db.sample SET TBLPROPERTIES ('write.spark.accept-any-schema'='true');The writer must enable the mergeSchema option.
data.writeTo("prod.db.sample").option("mergeSchema","true").append()
Writing Distribution Modes
Iceberg's default Spark writers require that the data in each spark task is clustered by partition values. This distribution is required to minimize the number of file handles that are held open while writing. By default, starting in Iceberg 1.2.0, Iceberg also requests that Spark pre-sort data to be written to fit this distribution. The request to Spark is done through the table property write.distribution-mode with the value hash. In Spark 3.5.0 and earlier, Spark does not respect the distribution mode in CTAS and RTAS operations or apply the write.distribution-mode setting.
The following examples demonstrate the writing distribution modes:
Create a table.
CREATE TABLE prod.db.sample (id bigint, data string, category string, ts timestamp) USING iceberg PARTITIONED BY (days(ts), category);
To write data to the table, data needs to be sorted by days(ts) and category but this is done automatically by the default hash distribution. For example:
INSERT INTO prod.db.sample SELECT id, data, category, ts FROM another_table;
The write.distribution-mode parameter supports three options, each affecting how Spark handles data partitions and sorts data.
- none: This is the previous default value for Iceberg prior to 1.2.0.
- Core logic: This mode does not request any shuffles or sort to be performed automatically by Spark.
- Data requirements: The data must be manually sorted by partition value (either within each spark task, or globally within the entire dataset). A global sort will minimize the number of output files.
- Special processing: A sort can be avoided by using the Spark write fanout property but this will cause all file handles to remain open until each write task has completed, increasing resource usage.
- Applicable scenarios: Data is already sorted by partition values (for example, the upstream task output is in required order), and no additional shuffle overhead is required.
- hash: This is the new default value for Iceberg 1.2.0 and later.
- Core logic: This mode requests that Spark uses a hash-based exchange to shuffle the incoming write data before writing.
- Procedure: Each row is hashed based on the row's partition value and then placed in a corresponding Spark task based on that value. Further spiting and coalescing of tasks may take place because of Spark's Adaptive Query planning.
- Advantages: Data is automatically clustered by partition values, eliminating manual sorting and balancing performance with resource efficiency.
- Applicable scenarios: Most common write scenarios, particularly when data is not pre-sorted and requires automatic adaptation to partition distribution.
- range:
- Core logic: This mode requests that Spark perform a range-based exchange to shuffle the data and globally sort data before writing.
- Procedure (two stages)
- Sampling stage: The first stage samples the data to be written based on the partition and sort columns to determine range distribution information about the data.
- Shuffle stage: The second stage uses the obtained range information to shuffle the input data into Spark tasks. Each task gets an exclusive range of the input data which clusters the data by partition and also globally sorts.
- Characteristics:
- It is more expensive than the hash distribution, requiring additional sampling and global ordering.
- Global ordering can be beneficial for read performance if sorted columns are used during queries. Pre-sorted data reduces computational overhead during reads.
- Triggered by default: This mode is used by default if a table is created with a sort-order. Parameter write.distribution-mode is automatically set to range.
- Applicable scenarios: Tables that require sorting (for example, by time) and workloads where read performance is prioritized over write overhead.
Controlling File Sizes
When you write data to Iceberg with Spark, it is important to note that:
- Spark cannot write a file larger than a Spark task and a file cannot span an Iceberg partition boundary. This means although Iceberg will always roll over a file when it grows to the write.target-file-size-bytes threshold, this rollover may not occur unless the Spark task produces a file large enough to exceed that size.
- The size of the file created on disk will also be much smaller than the Spark task since the disk data will be both compressed and in columnar format as opposed to Spark's uncompressed row representation. This means a 100 MB Spark task will create a file much smaller than 100 MB even if that task is writing to a single Iceberg partition. If the task writes to multiple partitions, the files will be even smaller than that.
To control what data ends up in each Spark task, use a write distribution mode or manually repartition the data.
To adjust Spark's task size, it is important to become familiar with Spark's various Adaptive Query Execution (AQE) parameters. When write.distribution-mode is not none, AQE will control the coalescing and splitting of Spark tasks during the exchange to try to create tasks of spark.sql.adaptive.advisoryPartitionSizeInBytes size. These settings will also affect any user-performed re-partitions or sorts. It is important again to note that this is the in-memory Spark row size and not the on-disk, columnar-compressed size, so a larger value than the target file size will need to be specified. The ratio of in-memory size to on-disk size is data dependent.
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot