Help Center/ AI DataLake/ devg/ Iceberg Development Guide/ Iceberg on Spark/ Stored Procedures for Iceberg Tables
Updated on 2026-11-06 GMT+08:00

Stored Procedures for Iceberg Tables

To use Iceberg in Spark, first configure Spark catalogs. For details about how to configure spark_catalog and prod catalogs, see Iceberg Configurations and Types. Stored procedures are only available when you use Iceberg SQL extensions in Spark 3.

How to Use

Stored procedures can be used from any configured Iceberg catalog with CALL. All procedures are in the namespace system.

CALL supports passing arguments by name (recommended) or by position. Mixing position and named arguments is not supported.

  • Named arguments

    All procedure arguments are named. When passing arguments by name, arguments can be in any order and any optional argument can be omitted.

    CALL spark_catalog.system.{Storage name} (arg_name_2 => 'arg_2_value', arg_name_1 => 'arg_1_value');
  • Positional arguments
    When you pass arguments by position, only the ending arguments may be omitted if they are optional.
    CALL spark_catalog.system.{Storage name} (arg_1, arg_2, ... arg_n);

Snapshot Management

  • rollback_to_snapshot

    You can use rollback_to_snapshot to roll back a table to a specific snapshot ID. The following command rolls back table db.sample to the snapshot whose ID is 1:

    CALL catalog_name.system.rollback_to_snapshot('db.sample', 1);

    The table name field is of the string type, and the snapshot ID field is of the long type.

    Table 1 describes the output results.

    Table 1 Output result

    Parameter

    Type

    Description

    previous_snapshot_id

    long

    The current snapshot ID before the rollback

    current_snapshot_id

    long

    The new current snapshot ID after the rollback

  • rollback_to_timestamp

    You can use rollback_to_timestamp to roll back a table to the snapshot that was current at some time. The following command rolls back table db.sample to a specific day and time.

    CALL spark_catalog.system.rollback_to_timestamp('db.sample', TIMESTAMP '2021-06-30 00:00:00.000');

    The table name field is of the string type, and the timestamp field is of the timestamp type, which indicates the target timestamp to roll back to.

    Table 1 describes the output results.

  • set_current_snapshot

    You can use set_current_snapshot to set the current snapshot ID of a table. Unlike rollback, the snapshot is not required to be an ancestor of the current table state. For example:

    Set the current snapshot for table db.sample to the snapshot whose ID is 1.

    CALL spark_catalog.system.set_current_snapshot('db.sample', 1);

    Set the current snapshot for table db.sample to the snapshot whose tag is s1.

    CALL spark_catalog.system.set_current_snapshot(table => 'db.sample', ref => 's1');

    The table name field is of the string type, the snapshot ID field is of the long type, and ref is the snapshot reference (branch or tag) of the current snapshot, which is of the string type. Either snapshot_id or ref must be provided but not both.

    Table 2 describes the output results.

    Table 2 Snapshot setting output

    Parameter

    Type

    Description

    previous_snapshot_id

    long

    The table's current snapshot ID before the setting

    current_snapshot_id

    long

    The table's new snapshot ID after the setting

  • cherrypick_snapshot

    You can use cherrypick_snapshot to pick changes from a specified snapshot and apply them to the current table state. Cherry-picking creates a new snapshot from an existing snapshot without altering or removing the original. Only append and dynamic overwrite snapshots can be cherry-picked. For example:

    Cherry-pick changes from snapshot 1.

    CALL spark_catalog.system.cherrypick_snapshot('my_table', 1);

    Cherry-pick change from snapshot 1 with named arguments.

    CALL spark_catalog.system.cherrypick_snapshot(snapshot_id => 1, table => 'my_table' );

    Parameter table indicates the name of the table to update. The value is of the string type. Parameter snapshot_id indicates the ID of the snapshot to cherry-pick. The value is of the long type.

    Table 3 describes the output results.

    Table 3 Snapshot change output

    Parameter

    Type

    Description

    source_snapshot_id

    long

    The table's current snapshot ID before the cherry-pick

    current_snapshot_id

    long

    The snapshot ID created by applying the cherry-pick

  • publish_changes

    You can use publish_changes to publish changes from a staged WAP ID into the current table state. publish_changes creates a new snapshot from an existing snapshot without altering or removing the original. Only append and dynamic overwrite snapshots can be successfully published. For example:

    Publish changes with WAP ID wap_id_1.

    CALL spark_catalog.system.publish_changes('my_table', 'wap_id_1');

    Publish changes with named arguments.

    CALL spark_catalog.system.publish_changes(wap_id => 'wap_id_2', table => 'my_table');

    Parameter table indicates the name of the table to update. The value is of the string type. Parameter wap_id indicates the WAP ID to be published from the staging environment. The value is of the long type.

    Table 4 describes the output results.

    Table 4 Snapshot change output

    Parameter

    Type

    Description

    source_snapshot_id

    long

    The table's current snapshot ID before publishing the change

    current_snapshot_id

    long

    The snapshot ID created by applying the change

  • fast_forward

    You can use fast_forward to fast-forward the current snapshot of one branch to the latest snapshot of another. For example:

    Fast-forward the current snapshot of the main branch to the latest snapshot of the audit-branch branch.

    CALL spark_catalog.system.fast_forward('my_table', 'main', 'audit-branch');

    Both the table field and branch field are of the string type.

    Table 5 describes the output results.

    Table 5 Snapshot update output

    Parameter

    Type

    Description

    branch_updated

    string

    The name of the branch that has been fast-forwarded

    previous_ref

    long

    The snapshot ID before applying fast-forward

    updated_ref

    long

    The current snapshot ID after applying fast-forward

Metadata Management

expire_snapshots

Each write, update, delete, upsert, compaction in Iceberg produces a new snapshot while keeping the old data and metadata around for snapshot isolation and time travel. The expire_snapshots procedure can be used to remove older snapshots and their files which are no longer needed.

This procedure will remove old snapshots and data files which are uniquely required by those old snapshots. This means the expire_snapshots procedure will never remove files which are still required by a non-expired snapshot. For example:

  • Remove snapshots older than specific day and time, but retain the last 100 snapshots.
    CALL spark_catalog.system.expire_snapshots('db.sample', TIMESTAMP '2021-06-30 00:00:00.000', 100);
  • Remove snapshots with snapshot ID 123 (note that this snapshot ID should not belong to the current snapshot).
    CALL spark_catalog.system.expire_snapshots('db.sample', snapshot_ids => array(123));

For details about related parameters, see Table 6.

Table 6 expire_snapshots parameters

Parameter

Type

Description

table

string

The name of the table to update. This parameter is mandatory.

older_than

timestamp

The timestamp before which snapshots will be removed (default: 5 days ago)

retain_last

int

The number of ancestor snapshots to preserve regardless of parameter older_than (defaults to 1)

max_concurrent_deletes

int

The size of the thread pool used for delete file actions (by default, no thread pool is used)

stream_results

boolean

When it is set to true, delete files will be sent to the Spark driver by RDD partition (by default, all the files will be sent to the Spark driver).

It is recommended that you set this option to true to prevent Spark driver OOM from a large file size.

snapshot_ids

array of long

The array of snapshot IDs to expire

clean_expired_metadata

boolean

If this parameter is set to true, metadata that is no longer referenced by snapshots will be cleared, such as partition specs and schemas.

If older_than and retain_last are omitted, the table's expiration properties will be used. Snapshots that are still referenced by branches or tags will not be removed. By default, branches and tags never expire, but their retention policy can be changed with the table property history.expire.max-ref-age-ms. The main branch never expires.

Table 7 describes the output results.

Table 7 expire_snapshots output

Parameter

Type

Description

deleted_data_files_count

long

The number of data files deleted by this operation

deleted_position_delete_files_count

long

Number of position delete files deleted by this operation

deleted_equality_delete_files_count

long

Number of equality delete files deleted by this operation

deleted_manifest_files_count

long

The number of manifest files deleted by this operation

deleted_manifest_lists_count

long

The number of manifest list files deleted by this operation

deleted_statistics_files_count

long

Number of statistics files deleted by this operation

remove_orphan_files

remove_orphan_files can be used to remove files which are not referenced in any metadata files of an Iceberg table and can thus be considered "orphaned".

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

Name of the table to be removed

older_than

No

timestamp

Removes orphaned files created before this timestamp (default: 3 days ago).

location

No

string

Directory where files are to be searched (default: table storage location)

dry_run

No

boolean

If set to true, files are not actually deleted (default value: false).

max_concurrent_deletes

No

int

The size of the thread pool used for delete file actions (by default, no thread pool is used)

file_list_view

No

string

The dataset to look for files in (skipping the directory listing)

equal_schemes

No

map

The mapping of file system schemes to be considered equal. The key is a comma-separated list of schemes, and the value is a scheme (defaults to map('s3a,s3n','s3')).

equal_authorities

No

map

The mapping of file system authorities to be considered equal. The key is a comma-separated list of authorities, and the value is an authority.

prefix_mismatch_mode

No

string

The action behavior when the location prefix (scheme/authority) does not match:

  • ERROR (default): Throw an exception.
  • IGNORE: Do not perform any operation. DELETE: Delete the file.

prefix_listing

No

boolean

When set to true, prefix-based file listing is used through the SupportsPrefixOperations API. When this flag is enabled, the FileIO implementation of the table must support the SupportsPrefixOperations API (default value: false).

Output result

Output Parameter

Type

Description

orphan_file_location

String

The path to each file determined to be an orphan by this command

Examples

List all the files that are candidates for removal by performing a dry run of the remove_orphan_files command on this table without actually removing them.

CALL spark_catalog.system.remove_orphan_files(table => 'db.sample', dry_run => true);

Remove any files in the tablelocation/data folder that are not known to the table db.sample.

CALL spark_catalog.system.remove_orphan_files(table => 'db.sample', location => 'tablelocation/data');

Remove any files in the files_view view that are not known to the table db.sample.

Dataset<Row> compareToFileList = spark.createDataFrame(allFiles, FilePathLastModifiedRecord.class).withColumnRenamed("filePath", "file_path").withColumnRenamed("lastModified", "last_modified");
String fileListViewName = "files_view";
compareToFileList.createOrReplaceTempView(fileListViewName);
CALL spark_catalog.system.remove_orphan_files(table => 'db.sample', file_list_view => 'files_view');

When a file matches references in metadata files except for location prefix (scheme/authority), an error is thrown by default. The error can be ignored and the file will be skipped by setting prefix_mismatch_mode to IGNORE.

CALL spark_catalog.system.remove_orphan_files(table => 'db.sample', prefix_mismatch_mode => 'IGNORE');

The file can still be deleted by setting prefix_mismatch_mode to DELETE.

CALL spark_catalog.system.remove_orphan_files(table => 'db.sample', prefix_mismatch_mode => 'DELETE');

The file can also be deleted by considering the mismatched prefixes equal.

CALL spark_catalog.system.remove_orphan_files(table => 'db.sample', equal_schemes => map('file', 'file1'));
CALL spark_catalog.system.remove_orphan_files(table => 'db.sample', equal_authorities => map('ns1', 'ns2'));

Lists all candidate files that meet the deletion conditions and scans them using prefix listing.

CALL catalog_name.system.remove_orphan_files(table => 'db.sample', prefix_listing => true);

rewrite_data_files

Iceberg tracks each data file in the table. A large volume of data files increases the metadata stored in manifest files. Specifically, small data files create excessive metadata and reduce query efficiency due to increased file-opening overhead.

Iceberg can compact data files in parallel using Spark with the rewriteDataFiles action. This will combine small files into larger files to reduce metadata overhead and runtime file open cost.

How to use

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the table to be updated

strategy

No

string

The policy name. The value can be binpack (default) or sort.

sort_order

No

string

The sorting order. Available values include:

  • Zorder: A comma-separated list of columns, in the format of zorder(c1,c2,c3).
  • Other: Comma-separated sorting orders in the format of ColumnName SortDirection NullOrder, where SortDirection can be ASC or DESC and NullOrder can be NULLSFIRST or NULLSLAST. By default, the table sorting order is used.

options

No

map

The options to be used for actions

where

No

string

The predicate as a string used for filtering the files. Note that all files that may contain data matching the filter criteria will be selected for rewriting.

Configuration options

Parameter

Default Value

Description

max-concurrent-file-group-rewrites

5

The maximum number of file groups to be simultaneously rewritten

partial-progress.enabled

false

Whether to enable committing file groups prior to the entire rewrite completing

partial-progress.max-commits

10

The maximum number of commits allowed for this rewrite operation if partial progress is enabled

partial-progress.max-failed-commits

value of partial-progress.max-commits

The maximum number of failed commits allowed before job failure, if partial progress is enabled.

use-starting-sequence-number

true

Whether to use the sequence number of the snapshot at compaction start time rather than that of the newly produced snapshot

rewrite-job-order

none

The order of forcibly rewriting jobs. The options are as follows:

  • bytes-asc: Rewrites the smallest job groups first.
  • bytes-desc: Rewrites the largest job groups first.
  • files-asc: Rewrites the job groups with the least files first.
  • files-desc: Rewrites the job groups with the most files first.
  • none: Rewrites job groups in the order they were planned (no specific ordering).

target-file-size-bytes

536870912 (512 MB; the default value inherits from the table property write.target-file-size-bytes)

The target output file size

min-file-size-bytes

75% of target file size

Files below this threshold will be considered for rewriting, regardless of other criteria

max-file-size-bytes

180% of target file size

Files above this threshold will be considered for rewriting, regardless of other criteria.

min-input-files

5

Any file group with more files than this value will be rewritten, regardless of other criteria

rewrite-all

false

Whether to forcibly rewrite all provided files and overwrite other options

max-file-group-size-bytes

107374182400 (100 GB)

Largest amount of data that should be rewritten in a single file group. The entire rewrite operation is broken down into pieces based on partitioning and within partitions based on size into file groups. This helps with breaking down the rewriting of very large partitions which may not be rewritable otherwise due to the resource constraints of the cluster.

delete-file-threshold

2147483647

The minimum number of deletes that needs to be associated with a data file for it to be considered for rewriting

delete-ratio-threshold

0.3

The minimum deletion ratio required for a data file to be included in the rewriting scope

output-spec-id

Spec ID of the current partition

The identifier of the output partition specifications. Data will be reorganized during the rewrite to align with the output partitioning.

remove-dangling-deletes

false

Whether to remove dangling position and equality delete files after rewriting. A delete file is considered dangling if it does not apply to any live data files. Enabling this option will generate an additional commit to perform the removal.

Sorting policy options

Parameter

Default Value

Description

compression-factor

1.0

The number of shuffle partitions and consequently the number of output files created by the Spark sort is based on the size of the input data files used in this file rewriter. Due to compression, the disk file sizes may not accurately represent the size of files in the output. This parameter lets the user adjust the file size used for estimating the actual output data size. A factor greater than 1.0 would generate more files than expected based on the on-disk file size. A value less than 1.0 would create fewer files than expected based on the on-disk file size.

shuffle-partitions-per-file

1

The number of shuffle partitions to use for each output file. Iceberg will use a custom coalesce operation to stitch these sorted partitions back together into a single sorted file.

ZORDER sorting policy options

Parameter

Default Value

Description

var-length-contribution

8

The number of bytes considered from an input column of a type with variable length (String, Binary).

max-output-size

2147483647

The number of bytes interleaved in the ZORDER algorithm.

Output result

Output Parameter

Type

Description

rewritten_data_files_count

int

The number of data files which were re-written by this command

added_data_files_count

int

The number of new data files which were written by this command

rewritten_bytes_count

long

The number of bytes which were written by this command

failed_data_files_count

int

The number of data files that failed to be rewritten when partial-progress.enabled is true

removed_delete_files_count

int

The number of files which were deleted by this command

Examples

Rewrite the data files in table db.sample using the default rewrite algorithm of bin-packing to combine small files and also split large files according to the default write size of the table.

CALL spark_catalog.system.rewrite_data_files('db.sample');

Rewrite the data files in table db.sample by sorting all data by id and name. Use the same default values as bin-pack to determine the files to be rewritten.

CALL spark_catalog.system.rewrite_data_files(table => 'db.sample', strategy => 'sort', sort_order => 'id DESC NULLS LAST,name ASC NULLS FIRST');

Rewrite the data files in table db.sample by performing ZORDER sorting on columns c1 and c2, and use the same default values as bin-pack to determine which files need to be rewritten:

CALL spark_catalog.system.rewrite_data_files(table => 'db.sample', strategy => 'sort', sort_order => 'zorder(c1,c2)');

Use the bin-pack policy to rewrite the data files in the partitions where at least two files in table db.sample need to be rewritten, and then remove all the dangling files.

CALL spark_catalog.system.rewrite_data_files(table => 'db.sample', options => map('min-input-files', '2', 'remove-dangling-deletes', 'true'));

Rewrite the data files in table db.sample and select the files that may contain data matching the filter criteria (id=3 and name="foo") for rewriting:

CALL spark_catalog.system.rewrite_data_files(table => 'db.sample', where => 'id = 3 and name = "foo"');

rewrite_manifests

Rewrite the manifest files for a table to optimize scan planning efficiency.

Data files in manifest files are sorted by fields in the partition specifications. This process is executed in parallel using Spark jobs.

How to use

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the table to be updated

use_caching

No

boolean

Whether to use Spark caching during operations (defaults to true)

spec_id

No

int

The specification ID of the manifest files to rewrite (defaults to the current specification ID)

Output result

Output Parameter

Type

Description

rewritten_manifests_count

int

The number of manifests which were re-written by this command

added_manifests_count

int

The number of new manifest files which were written by this command

Examples

Rewrite the manifests in table db.sample and align manifest files with table partitioning.

CALL spark_catalog.system.rewrite_manifests('db.sample');

Rewrite the manifests in table db.sample and disable Spark caching (to avoid memory issues on the executor).

CALL spark_catalog.system.rewrite_manifests('db.sample', false);

rewrite_position_delete_files

Iceberg can rewrite positional delete files, which serves two main purposes:

  • Lightweight compression: Merges mall locational delete files into larger file to reduce the amount of metadata stored in the manifest files and lower the overhead of opening small delete files.
  • Removing dangling deletes: Filters out locational delete records that point to inactive data files. After rewrite_data_files is executed, locational delete records pointing to rewritten data files may not be marked for removal and may still be tracked by the active snapshot metadata of the table. This phenomenon is called "dangling delete."

How to use

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the table to be updated

options

No

map

Configuration options used for this procedure

where

No

string

Filter criteria of the string type used to filter files

Configuration options

Parameter

Default Value

Description

max-concurrent-file-group-rewrites

5

The maximum number of file groups to be simultaneously rewritten

partial-progress.enabled

false

Whether to enable committing some file groups prior to the entire rewrite completing

partial-progress.max-commits

10

The maximum number of commits allowed for this rewrite operation if partial progress is enabled

rewrite-job-order

none

The order of forcibly rewriting jobs. The options are as follows:

  • bytes-asc: Rewrites the file groups with the least data volume first.
  • bytes-desc: Rewrites the file group with the largest data volume first.
  • files-asc: Rewrites the file groups with the least files first.
  • files-desc: Rewrites the file groups with the most files first.
  • none: Rewrites jobs in the order they were planned (no specific ordering).

target-file-size-bytes

67108864 (64 MB; the default value inherits from the table property write.delete.target-file-size-bytes)

Target size of the output file

min-file-size-bytes

75% of target file size

Files below this threshold will be included in the rewrite scope, regardless of other criteria

max-file-size-bytes

180% of target file size

Files above this threshold will be included in the rewrite scope, regardless of other criteria

min-input-files

5

Any file group with more files than this value will be rewritten, regardless of other criteria

rewrite-all

false

Whether to forcibly rewrite all provided files and overwrite other criteria

max-file-group-size-bytes

107374182400 (100 GB)

Largest amount of data that can be rewritten in a single file group The entire rewrite operation is broken down into pieces based on partitioning and within partitions based on size into file groups. This prevents large partitions from failing to be rewritten due to resource constraints of the cluster.

max-files-to-rewrite

null

The maximum number of files that will be rewritten. If this option is not specified, all files that meet the criteria will be rewritten.

Output result

Output Parameter

Type

Description

rewritten_delete_files_count

int

Number of old positional delete files removed by this command

added_delete_files_count

int

Number of new positional delete files added by this command

rewritten_bytes_count

long

Total number of bytes in all old positional delete files removed by this command

added_bytes_count

long

Total number of bytes in all new positional delete files added by this command

Examples

Rewrite the positional delete files of table db.sample: Select the files to be rewritten based on the default filter criteria, generate new files that meet the target-file-size-bytes target size, and automatically remove dangling delete records during the rewriting process.

CALL spark_catalog.system.rewrite_position_delete_files('db.sample');

Rewrite all positional delete files of table db.sample: Overwrite the filter criteria, generate new files that meet the target size, and remove dangling delete records.

CALL spark_catalog.system.rewrite_position_delete_files(table => 'db.sample', options => map('rewrite-all', 'true'));

Rewrite positional delete files of table db.sample by file quantity: Rewrite only the positional delete files in partitions where the number of files to be rewritten by size is greater than or equal to 2, and remove dangling delete records.

CALL spark_catalog.system.rewrite_position_delete_files(table => 'db.sample', options => map('min-input-files','2'));

Migrating Tables

Snapshot and migration stored procedures help test existing Hive or Spark tables and migrate them to Iceberg tables.

snapshot

The snapshot operation creates a lightweight temporary copy of the source table for testing purposes, without modifying the source table itself.

The newly created snapshot table can be modified or written to without affecting the source table. However, the snapshot table references the raw data files of the source table. When an insert or overwrite operation is performed on the snapshot table, the newly generated files are stored in the specified location of the snapshot table, not in the storage location of the source table.

After the snapshot table test is complete, you can run the DROP TABLE statement to clear the table.

How to use

Parameter

Mandatory (Yes/No)

Type

Description

source_table

Yes

string

The name of the source table for which a snapshot is to be generated

table

Yes

string

The name of the new Iceberg snapshot table to be created

location

No

string

The location where the new snapshot table is stored. By default, the directory is automatically allocated. Currently, this parameter cannot be set in the AI DataLake table migration scenario.

properties

No

map

Properties (such as table-level configurations) to be added to the new snapshot table

parallelism

No

int

The number of threads used to read files. The default value is 1.

Output result

Output Parameter

Type

Description

imported_files_count

long

The number of files added to the new snapshot table (that is, the number of data files referenced from the source table)

Examples

Create an isolated Iceberg snapshot table: Reference the source table db.sample, set the new table name to db.snap, and store the table in the default location allocated for db.snap.

CALL spark_catalog.system.snapshot('db.sample', 'db.snap');

migrate

Replace an existing table with an Iceberg table and load the data files of the source table.

Copy the table structure, partition configurations, table properties, and storage location of the source table to the new Iceberg table.

If there is an unsupported file format in any partition of the source table, the migration will fail. Currently, the Avro, Parquet, and ORC file formats are supported. The existing data files of the source table will be added to the metadata of the Iceberg table. These data files can be read through the name-ID mapping generated based on the source table structure.

To keep the source table intact during testing, you can use the snapshot process to create a temporary table to share the data files and structure of the source table.

By default, the source table is retained and named table_BACKUP_.

How to use

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the source table to be migrated

properties

No

map

Properties to be added to the new Iceberg table (which will overwrite the properties with the same name in the source table)

drop_backup

No

boolean

If this parameter is set to true, the source table will not be retained as a backup. The default value is false.

backup_table_name

No

string

The name of the retained backup source table (the default value is the Source table name_BACKUP_)

parallelism

No

int

The number of threads used to read files. The default value is 1.

Output result

Output Parameter

Type

Description

migrated_files_count

long

The number of data files migrated to the new Iceberg table

Examples

Migrate tables in the default Spark directory and add properties: Migrate spark_catalog.db.sample to an Iceberg table and add the 'foo'='bar' property to the new table.

CALL spark_catalog.system.migrate('spark_catalog.db.sample', map('foo', 'bar'));

Conduct a basic migration (without adding additional properties): Migrate the db.sample file in the current directory to the Iceberg table without adding additional properties.

CALL spark_catalog.system.migrate('db.sample');

add_files

The add_files command is used to add files in a Hive table or file-based table to a specified Iceberg table. Unlike migration or snapshot, the add_files command can import files from a specific partition and does not create a new Iceberg table. This command generates metadata for the files to be added, but does not move the files themselves. This process does not analyze the schema of the files to verify whether it matches the schema of the Iceberg table. After the operation is complete, the Iceberg table treats these files as part of its own managed file set. This means that when expired snapshots are executed later, these added files can be physically deleted. The migrate or snapshot method is preferentially recommended when applicable.

How to use

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the target Iceberg table to which files are to be added

source_table

Yes

string

The source table of the file (which can be a table registered with Hive/Spark or a file path in the format of file_format.path, for example, parquet./data/path)

partition_filter

No

map

Mapping used to filter partitions in the source table (only files from partitions that meet the filter criteria are imported)

check_duplicate_files

No

boolean

Whether to prevent files that already exist in the target table from being added again (default: true)

parallelism

No

int

The number of threads used to read files. The default value is 1.

Output result

Output Parameter

Type

Description

added_files_count

long

The number of files that were successfully added by this command

changed_partition_count

long

Number of affected partitions (if countable)

Examples

Import files from a specified partition: Add the files from the partition where part_col_1 equals A in the Hive/Spark table db.src_tbl registered in the session directory to the Iceberg table db.tbl.

CALL spark_catalog.system.add_files( table => 'db.tbl', source_table => 'db.src_tbl', partition_filter => map('part_col_1', 'A') );

Import all files from a file path: Add all files from the Parquet table located at path/to/table to the Iceberg table db.tbl (without filtering partitions).

CALL spark_catalog.system.add_files( table => 'db.tbl',   source_table => '`parquet`.`path/to/table`' );

register_table

The register_table command creates a directory entry for the existing metadata.json file that has not been associated with a directory identifier. By performing this operation, an independent Iceberg metadata file can be registered as a formal table in a specified directory so that it can be identified and managed by the directory.

How to use

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the table to be registered

metadata_file

Yes

string

The path of the metadata.json file to be registered

Output result

Output Parameter

Type

Description

current_snapshot_id

long

The current snapshot ID of the newly registered Iceberg table

total_records_count

long

The total number of records in the newly registered Iceberg table

total_data_files_count

long

The total number of data files in the newly registered Iceberg table

Examples

In the spark_catalog directory, register the metadata.json file located at path/to/metadata/file.json as the table db.tbl.

CALL spark_catalog.system.register_table( table => 'db.tbl', metadata_file => 'path/to/metadata/file.json' );

Metadata

ancestors_of

The ancestors_of command queries the active snapshot IDs of the parent snapshots for a specified snapshot, returning the chain of ancestor snapshots.

How to use

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the table for which to query the ancestor snapshots

snapshot_id

No

long

The ID of the snapshot whose parent snapshot active ID is to be queried

Output result

Output Parameter

Type

Description

snapshot_id

long

The ID of the ancestor snapshot

timestamp

long

The time when the ancestor snapshot was created

Examples

Query all ancestor snapshots of the current snapshot (default behavior):

CALL spark_catalog.system.ancestors_of('db.tbl');

Query all ancestor snapshots of a specified snapshot ID (using positional parameters):

CALL spark_catalog.system.ancestors_of('db.tbl', 1);

Query all ancestor snapshots of a specified snapshot ID (using named parameters, which is recommended for better readability):

CALL spark_catalog.system.ancestors_of(snapshot_id => 1, table => 'db.tbl');

Change Data Capture

create_changelog_view

The create_changelog_view creates a view that contains the change records of a specified table. This view can be used to track all data changes between different snapshots or timestamps of the table.

How to use

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the source table for which change records are generated

changelog_view

No

string

Name of the change view to be created. If this parameter is not specified, the default view name associated with the source table is generated.

options

No

map

A map of Spark read options, which is used to specify the time range for change records (see below for common options)

net_changes

No

boolean

Whether to output only the net changes (removing intermediate changes and retaining only the final result). The default value is false. When compute_updates is set to true, this parameter must be set to false.

compute_updates

No

boolean

Whether to calculate the pre/post update images (identifying the combination of delete and insert as an update). The default rule is as follows: If identifier_columns is provided, the default value is true. If it is not provided, the default value is false.

identifier_columns

No

array

A list of identifier columns, for example, array ('id', 'name'), used to identify update operations. If compute_updates is set to true and this parameter is not specified, the current identifier column of the table is used.

The options parameter can be used to specify the time range of change records using two dimensions (snapshot ID or timestamp). If this parameter is not specified, the full snapshot of the table is overwritten by default.

  • start-snapshot-id: exclusive start snapshot ID (excluding changes in this snapshot). By default, the first snapshot (inclusive) of the table is used.
  • end-snapshot-id: inclusive end snapshot ID (including changes to the snapshot). By default, the current snapshot of the table is used.
  • start-timestamp: exclusive start timestamp, in milliseconds. By default, the first snapshot (inclusive) of the table is used.
  • end-timestamp: inclusive end timestamp, in milliseconds. By default, the current snapshot of the table is used.

Output result

Output Parameter

Type

Description

changelog_view

string

The name of the created change view

Examples

Create a view tbl_changes that contains the changes of the source table db.tbl between snapshot 1 (exclusive) and snapshot 2 (inclusive).

CALL spark_catalog.system.create_changelog_view(  table => 'db.tbl',  options => map('start-snapshot-id','1','end-snapshot-id', '2'));

Create a view my_changelog_view that contains the changes of the source table db.tbl between timestamps 1678335750489 (exclusive) and 1678992105265 (inclusive).

CALL spark_catalog.system.create_changelog_view(   table => 'db.tbl',   options => map('start-timestamp','1678335750489','end-timestamp', '1678992105265'),   changelog_view => 'my_changelog_view' );

Create a view that contains changes between snapshots 1 and 2, in which the combination of delete and insert is identified as an update operation based on the identifier columns id and name.

CALL spark_catalog.system.create_changelog_view(   table => 'db.tbl',   options => map('start-snapshot-id','1','end-snapshot-id', '2'),   identifier_columns => array('id', 'name') )

After the view is created, you can directly query the change records using SQL statements.

SELECT * FROM tbl_changes;
SELECT * FROM tbl_changes where _change_type = 'INSERT' AND id = 3 ORDER BY _change_ordinal;

Note that the change log view contains change data capture (CDC) metadata columns, which provide additional information about the tracked changes. These columns are as follows:

  • _change_type: The type of the change. The value can be INSERT, DELETE, UPDATE_BEFORE, or UPDATE_AFTER.
  • _change_ordinal: The order of the change.
  • _commit_snapshot_id: The ID of the snapshot where the change occurs.

The following example shows that two records were inserted into the first snapshot and one record was deleted from the second snapshot.

id

name

_change_type

_change_ordinal

_commit_snapshot_id

1

Alice

INSERT

0

5390529835796506035

2

Bob

INSERT

0

5390529835796506035

1

Alice

DELETE

1

8764748981452218370

Net Changes

This process removes intermediate changes between multiple snapshots and outputs only the net changes. The following is an example of creating a change log view to calculate net changes:

CALL spark_catalog.system.create_changelog_view(   table => 'db.tbl',   options => map('end-snapshot-id', '87647489814522183702'),   net_changes => true );

Since Alice was inserted in the first snapshot and deleted in the second snapshot, the preceding change log view, after net changes are enabled, contains only the following rows:

id

name

_change_type

_change_ordinal

_commit_snapshot_id

2

Bob

INSERT

0

5390529835796506035

Carry-over Rows

This procedure removes the carry-over rows by default. Carry-over rows are the results of row-level operations (MERGE, UPDATE, and DELETE) performed in copy-on-write mode. For example, there is a file containing row 1 (id=1,name='Alice') and row 2 (id=2,name='Bob'). When row 2 is deleted in copy-on-write mode, the file needs to be deleted and row 1 needs to be retained in a new file. Although this is not an actual change to the table, the change log table still records the following two rows:

id

name

_change_type

1

Alice

DELETE

1

Alice

INSERT

You can query the SparkChangelogTable to view the carry-over rows.

SELECT * FROM spark_catalog.db.tbl.changes;

Pre/Post Update Images

If configured, this process can calculate the pre/post update images. Pre/post update images are derived from a set of delete and insert rows. Identifier columns are used to determine whether an insert record and a delete record refer to the same row. If the values of the identifier columns are the same, the two records are regarded as the same row's before and after states. You can set identifier columns in the table schema or pass them as procedure parameters.

The following example demonstrates the process of calculating pre/post update images using the identifier column id. Rows with the same identifier column value for delete and insert operations are considered as a single update operation. Specifically, assume there are the following two rows of records:

id

name

_change_type

3

Robert

DELETE

3

Dan

INSERT

In this case, the process marks the row before the update as an UPDATE_BEFORE image and the row after the update as an UPDATE_AFTER image, resulting in the following pre/post update images:

id

name

_change_type

3

Robert

UPDATE_BEFORE

3

Dan

UPDATE_AFTER

Table Statistics

compute_table_stats

This procedure is used to calculate the number of distinct values (NDV) statistics for a specific table. By default, statistics are calculated for all columns using the current snapshot of the table. This procedure can be optionally configured to calculate statistics for a specific snapshot and/or a subset of columns.

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the table

snapshot_id

No

string

The ID of the snapshot for which to collect statistics

columns

No

array

The column for which to collect statistics

Output result

Output Parameter

Type

Description

statistics_file

string

The path of the statistics file created by this command

Examples

Collect statistics for the latest snapshot of the my_table table.

CALL catalog_name.system.compute_table_stats('my_table'); 

Collect statistics for the snapshot whose ID is snap1 in the my_table table.

CALL catalog_name.system.compute_table_stats(table => 'my_table', snapshot_id => 'snap1' ); 

Collect statistics for columns col1 and col2 of the snapshot whose ID is snap1 in the my_table table.

CALL catalog_name.system.compute_table_stats(table => 'my_table', snapshot_id => 'snap1', columns => array('col1', 'col2')); 

Partition Statistics

compute_partition_stats

This process incrementally calculates partition statistics from the last snapshot that has a PartitionStatisticsFile to a given snapshot (or the current snapshot if none is specified) and writes the results to the PartitionStatisticsFile. If the previous PartitionStatisticsFile does not exist, a full calculation is performed. It also registers the PartitionStatisticsFile in the table metadata.

Parameter

Mandatory (Yes/No)

Type

Description

table

Yes

string

The name of the table

snapshot_id

No

string

The ID of the snapshot for which to calculate partition statistics. The default value is the current snapshot ID.

Output result

Output Parameter

Type

Description

partition_statistics_file

string

The path of the partition statistics file created by this command

Examples

Collect partition statistics for the latest snapshot of the my_table table.

CALL catalog_name.system.compute_partition_stats('my_table'); 

Collect partition statistics for the snapshot whose ID is snap1 in the my_table table.

CALL catalog_name.system.compute_partition_stats(table => 'my_table', snapshot_id => 'snap1'); 

Table Replication

The rewrite_table_path procedure is used to prepare for replication of the Iceberg table to another location.

It creates a staged replica of the Iceberg table metadata file, where each absolute path source prefix is replaced with the specified target prefix. This can serve as the starting point for fully or incrementally replicating the Iceberg table to a new location.

This procedure only stages the rewritten metadata file and prepares the list of files to be replicated. The actual file replication is not included in this procedure.

Parameter

Mandatory (Yes/No)

Default Value

Type

Description

table

Yes

-

string

The name of the table

source_prefix

Yes

-

string

The existing prefix to be replaced

target_prefix

Yes

-

string

The target prefix for source_prefix

start_version

No

The first metadata.json in the table metadata log

string

The name or path of the first metadata.json file to be rewritten in chronological order

end_version

No

The latest metadata.json in the table metadata log

string

The name or path of the last metadata.json file to be rewritten in chronological order

staging_location

No

The new directory in the table metadata directory

string

The output location of the newly rewritten metadata file

Operation modes

  • Full rewrite: Rewrites all accessible metadata files (including metadata.json, manifest lists, manifests, and position delete files) and returns all accessible files in file_list_location. This is the default operation mode of this procedure.
  • Incremental rewrite (optional): Limits the scope to incremental rewrite by providing start_version and end_version. An incremental rewrite rewrites only the metadata files added between start_version and end_version, and returns only the files added within this range in file_list_location.

Output result

Output Parameter

Type

Description

latest_version

string

The name of the latest metadata file rewritten by this procedure

file_list_location

string

The path of the CSV file that contains the mapping from the source path to the target path.

File list

This file contains the replication plan for all files added to the table between start_version and end_version.

For each file, it specifies:

  • Source path: The original file path in the table, or the staging location if the file has been rewritten.
  • Target path: The path with the replaced prefix.

The following example shows the replication plans for three files:

sourcepath/datafile1.parquet,targetpath/datafile1.parquet
sourcepath/datafile2.parquet,targetpath/datafile2.parquet 
stagingpath/manifest.avro,targetpath/manifest.avro 

Examples

This example completely rewrites the metadata path of the table my_table from the source location in OBS to the target location in OBS. It generates a new set of metadata in the default staging location under the table metadata directory.

CALL catalog_name.system.rewrite_table_path(
     table => 'db.my_table',
     source_prefix => 'obs://bucket/path/to/source_table',
     target_prefix => 'obs://bucket/prefix/db.db/my_table' ); 

This example incrementally rewrites the metadata path of the table my_table between metadata versions v2.metadata.json and v20.metadata.json, and writes the new metadata file to the specified staging location.

CALL catalog_name.system.rewrite_table_path(
     table => 'db.my_table',
     source_prefix => 'obs://bucketOne/prefix/db.db/my_table',
     target_prefix => 'obs://bucketTwo/prefix/db.db/my_table',
     start_version => 'v2.metadata.json',
     end_version => 'v20.metadata.json',
     staging_location => 'obs://bucketStaging/my_table' ); 

After the rewriting is complete, a third-party tool (such as DistCp) can replicate the newly created metadata files and data files to the target location.

Finally, you can register the replicated table with the catalog using the registry method.