Cannot write nullable values to non-null column
In my spark jobs I am reading from JSON and merging to iceberg. In my iceberg tables I would like to have NOT NULL constraints. However, when loading data from JSON, spark doesn't enforce the schema nullability constraints. To work around this I have discovered two alternatives:
input_dataset = spark.read.schema(my_schema).json("s3://my_bucket/my_folder/").filter(col("my_key").isNotNull())
input_dataset = spark.createDataFrame(input_dataset.rdd, schema=my_schema).createOrReplaceTempView("source")
spark.sql("MERGE INTO my_table ...
or
--conf spark.sql.storeAssignmentPolicy=LEGACY
input_dataset = spark.read.schema(my_schema).json("s3://my_bucket/my_folder/").filter(col("my_key").isNotNull()).createOrReplaceTempView("source")
spark.sql("MERGE INTO my_table ...
The first option is very slow, adding 40-60 minutes to the processing time of my spark application. The second option seems too permissive. I have noticed that there is a configuration option named spark.sql.iceberg.check-nullability in the code. I'd like to propose that this option be included in the AssignmentAlignmentTrait to allow writers to bypass NULL constraints while preserving the other types of compatibility checks.
https://github.com/apache/iceberg/blob/apache-iceberg-0.11.1/spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/AssignmentAlignmentSupport.scala#L152
Thanks for consideration.
I have the same problem. Is this check too strict?Can we provide a configuration to turn off this check?
Encountering the same problem, any concerns with using this config spark.sql.iceberg.check-nullability in the SQL analysis to control nullability checking @rdblue
For others with the same problem, a workaround is setting: spark.sql.storeAssignmentPolicy to legacy since the code only does the check if the policy is strict or ansi.
Yes, if you're hitting this problem then you probably want to set spark.sql.storeAssignmentPolicy to legacy. That disables the checks that ensure you don't attempt to write null values to a required column.
This config is no longer working with latest api. I get this error:
org.apache.spark.sql.AnalysisException: LEGACY store assignment policy is disallowed in Spark data source V2.
Since this is enforced entirely within Spark, I don't think there's much that Iceberg can do. I'm not sure why it would be so much slower to enforce the null check.
coalesce the nullable field can change to not null
like coalesce(field, not_null)
@rdblue
I am seeing the same issue when writing a dataframe with df.write.format("orc").save(path) and then reading it back with df.read.format("orc").load(path) even when setting the check-nullability to false when writing the dataframe to iceberg.
@bgt-cdedels @coolderli @grantatspothero Did you find a way to overcome this problem?
@vikrambohra, I was just working on a similar problem and to fix it, I'm adding a table property that allows you to disable Spark's checks and use Iceberg's instead. Take a look at the changes in #4154.
Thanks for the reply @rdblue. We are on spark 2.3 at the moment. Will this change be back-ported to spark 2.3?
@vikrambohra, Spark 2.3 doesn't hit this issue because this is caused by Spark adding schema validation in 3.0 and later. If you're using 2.x, then you should already be using Iceberg schema checking and you can turn off the nullability check directly.
@rdblue
I am using spark version: 2.3.0 and iceberg-spark: 0.11.0.14
The code for nullability check during write is in IcebergSource
specifically here:
public Optional
I tried disabling the nullability check in the dataframewriter options but that only worked for non-list and non-map columns of the schema. This is described in https://github.com/apache/iceberg/issues/510
What was the error that you hit?
java.lang.IllegalArgumentException: Cannot write incompatible dataset to table with schema: table { 1: header: required struct<11: memberId: required int (The LinkedIn member ID of the user initiating the action. LinkedIn member IDs are integers greater than zero. Guests are represented either as zero or a negative number.), 12: viewerUrn: optional string (The LinkedIn URN of the user initiating the action. For other applications like Slideshare, this should be filled ... 2: requestHeader: required struct<59: browserId: optional string (The browserId stored within the user's bcookie. For information on the bcookie format from which browserId is derived, see: ... 3: mobileHeader: optional struct<73: osName: optional string (The name of the operating system.), 74: osVersion: optional string (The version of the operating system.), 75: deviceModel: optional string (The model of the device.), .. 4: pageType: required string (A flag which specifies what type of page this is.) 5: errorMessageKey: optional string (A unique identifier for the error message shown.) 6: trackingCode: optional string (DEPRECATED. A key for the linkedin page that referred this view) 7: trackingInfo: required map<string, string> (DEPRECATED. Misc fields supplied by the page) 8: totalTime: required int (The total server-side time required to render the page in ms) 9: datepartition: optional string 10: late: optional int } write schema:table { 1: header: optional struct<11: memberId: optional int (The LinkedIn member ID of the user initiating the action. LinkedIn member IDs are integers greater than zero. Guests are represented either as zero or a negative number.), 12: viewerUrn: optional string (The LinkedIn URN of the user initiating the action. For other applications like Slideshare, this should be filled ... 2: requestHeader: optional struct<59: browserId: optional string (The browserId stored within the user's bcookie. For information on the bcookie format from which browserId is derived, see: ... 3: mobileHeader: optional struct<73: osName: optional string (The name of the operating system.), 74: osVersion: optional string (The version of the operating system.), 75: deviceModel: optional string (The model of the device.), ... 4: pageType: optional string (A flag which specifies what type of page this is.) 5: errorMessageKey: optional string (A unique identifier for the error message shown.) 6: trackingCode: optional string (DEPRECATED. A key for the linkedin page that referred this view) 7: trackingInfo: optional map<string, string> (DEPRECATED. Misc fields supplied by the page) 8: totalTime: optional int (The total server-side time required to render the page in ms) 9: datepartition: optional string 10: late: optional int } Problems:
- header.traceData.context: values should be required, but are optional
- trackingInfo: values should be required, but are optional at org.apache.iceberg.types.TypeUtil.validateWriteSchema(TypeUtil.java:263) at org.apache.iceberg.spark.source.IcebergSource.createWriter(IcebergSource.java:95) at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:255) at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:226)
Context: I have a source iceberg table with both optional and required fields in schema. I read the source table incrementally in spark and dedupe the data using some columns as keys. I need to write the back to another iceberg table, however I want to reduce the number of output files. So I write the data to HDFS using the spark orc writer (df.write.format("orc").save(path). I read it back using spark.read.format("orc").load(path) with some filter and try to write to the destination iceberg table which has the same schema as the source iceberg table. This is where it fails with the above exception. I checked the dataframe schema after reading back from HDFS and I see all fields as optional/nullable.
@rdblue I hope I did not confuse you with all this info. LMK if the above is unclear
any ideas @rdblue ?
Edit, the below is worked around by the config option added in this ticket, though it doesn't feel like something I should ship. Use it like this:
sdf.writeTo("dev_catalog.tablename").option("check-nullability", "false").append()
This appears to be the final barrier to me actually inserting data to Iceberg. Since i can't find any way to write to Iceberg except by involving Spark, some PySpark is below. Here is my current attempt, after turning off the spark checks, to rely only on Iceberg checks. The goal is to somehow convince the dataframe that the column is not nullable, without hand-writing the whole schema or incurring ridiculous speed penalty. This dataframe is only a few kb, somehow going near createDataFrame or rdd's causes massive slowdown.
# strftime seems easier than using SQL to cast datetime to DATE logical type
if 'my_date' in df.columns:
df.my_date = df.my_date.dt.strftime('%Y-%m-%d')
# Write a parquet file for loading to spark, because spark.createDataFrame(pandas_df) is astoundingly slow
path = tempfile.mktemp(dir="/tmp/hflinner/parquet", suffix=".parquet")
df.to_parquet(path, index=False, allow_truncated_timestamps=True, coerce_timestamps='us')
spark = _get_spark()
sdf = spark.read.parquet(path)
# Undo strftime hack, also try to fix nullability of date and path column.
from pyspark.sql.functions import to_date
if 'my_date' in df.columns:
#sdf = sdf.select('*', (to_date(sdf.my_date)).alias('my_date'))
sdf = sdf.withColumn('my_date', to_date(sdf.my_date, '%Y-%m-%d'))
sdf = sdf.filter(sdf.my_date.isNotNull()).filter(sdf.backed_up_path.isNotNull())
sdf.schema['my_date'].nullable = False
sdf.schema['backed_up_path'].nullable = False
sdf.writeTo(f"dev_catalog.{tablename}").append()
-->
IllegalArgumentException: Cannot write incompatible dataset to table with schema:
table {
1: server_name: optional string
2: my_date: required date
3: backed_up_path: required string
4: backed_up_filesize: optional long
5: num_lines: optional long
}
Provided schema:
table {
1: server_name: optional string
2: my_date: optional date
3: backed_up_path: optional string
4: backed_up_filesize: optional long
}
Problems:
* my_date should be required, but is optional
* backed_up_path should be required, but is optional
I don't have a schema object (the schema is written as SQL for Iceberg) and I don't want to create an rdd.