You can create an Iceberg table in HDFS using HadoopTables and SparkSchemaUtil. SparkSchemaUtil allows you to derive the schema and partition specification directly from an existing Spark table, which is useful for migrating data to Iceberg.
Note: When using Spark objects inside transformations or closures, use a code block to avoid capturing Spark configurations in closures.
import org.apache.hadoop.fs.Path
import com.netflix.iceberg.hadoop.HadoopTables
import com.netflix.iceberg.spark.SparkSchemaUtil
val path = "hdfs:/tmp/tables/job_metrics_tmp"
{
val conf = spark.sparkContext.hadoopConfiguration
val fs = new Path(path).getFileSystem(conf)
fs.delete(new Path(path), true /* recursive */ )
val tables = new HadoopTables(conf)
// Derive schema and spec from an existing Spark table
val schema = SparkSchemaUtil.schemaForTable(spark, "default.job_metrics")
val spec = SparkSchemaUtil.specForTable(spark, "default.job_metrics")
tables.create(schema, spec, path)
// Verify the schema
tables.load(path).schema
}