In Apache Iceberg, you can insert nested fields into a table as long as the schema of the table supports nested types, such as structs, arrays, or maps. Iceberg has excellent support for complex types, and you can use Spark SQL or the DataFrame API to insert such data.
🔧 Example: Inserting Nested Fields in Iceberg (Using Spark in Java)
Suppose you have an Iceberg table with the following schema:
CREATE TABLE my_catalog.db.users (
id INT,
name STRING,
address STRUCT<
city: STRING,
zip: STRING
>
);
✅ 1. Set Up Your SparkSession (with Iceberg)
SparkSession spark = SparkSession.builder()
.appName("Iceberg Nested Field Insert")
.master("local[*]")
.config("spark.sql.catalog.my_catalog", "org.apache.iceberg.spark.SparkCatalog")
.config("spark.sql.catalog.my_catalog.type", "hadoop")
.config("spark.sql.catalog.my_catalog.warehouse", "hdfs:///user/hive/warehouse")
.getOrCreate();
✅ 2. Create Sample Data with a Struct (address)
import org.apache.spark.sql.Row;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.types.*;
import java.util.*;
List<Row> data = Arrays.asList(
RowFactory.create(1, "Alice", RowFactory.create("New York", "10001")),
RowFactory.create(2, "Bob", RowFactory.create("San Francisco", "94105"))
);
// Define schema with a nested struct
StructType schema = new StructType(new StructField[]{
new StructField("id", DataTypes.IntegerType, false, Metadata.empty()),
new StructField("name", DataTypes.StringType, false, Metadata.empty()),
new StructField("address", new StructType(new StructField[]{
new StructField("city", DataTypes.StringType, false, Metadata.empty()),
new StructField("zip", DataTypes.StringType, false, Metadata.empty())
}), false, Metadata.empty())
});
Dataset<Row> df = spark.createDataFrame(data, schema);
✅ 3. Write to Iceberg Table (Append Mode)
df.write()
.format("iceberg")
.mode("append")
.save("my_catalog.db.users");
Or using SQL-like insert (if registered):
df.createOrReplaceTempView("temp_data");
spark.sql("INSERT INTO my_catalog.db.users SELECT * FROM temp_data");
✅ 4. Verify Insert
spark.sql("SELECT * FROM my_catalog.db.users").show(false);
💡 Notes
- Make sure the already, or modify the schema if needed.