问题:为什么下面的代码抱怨Hiring_Date列在df和SQL Table中不同的可空配置。我在这里可能少了什么?错误发生在df3.write行,其中df3应该写到SQL表中。
ERROR:ava.sql.SQLException: Spark和Server表具有不同的列可空配置,列索引为0 DF、Hiring_Date可空配置为true、table Hiring_Date可空配置为false
备注:据我所知(它在我的其他脚本中也有效),一旦您在pyspark中定义了列的数据类型并将其空值设置为某个值,那么df中的该列是不可空的。
df = spark.read.csv("myDataFile.txt", sep="|", header="true", inferSchema="false")
df1 = df.select( *[ F.when(F.col(column).isNull(),'').otherwise(F.col(column)).alias(column) for column in df.columns])
df2 = df1.withColumn("Hiring_Date", df1.Hiring_Date.cast(TimestampType())) \
.withColumn("Hiring_Fee", df1.Hiring_Fee.cast(DoubleType()))
df3 = df2.fillna( {'Hiring_Fee' : 0, 'Hiring_Date': '1753-01-01 00:00:00.000'} )
try:
df3.write \
.format("com.microsoft.sqlserver.jdbc.spark") \
.mode("append") \
.option("url", url) \
.option("dbtable", table_name) \
.option("user", myUserName) \
.option("password", myPassword) \
.save()
except ValueError as error :
print("Connector write failed", error)Server表定义
CREATE TABLE HR_History(
Hiring_Date datetime NOT NULL,
Hiring_Fee float NOT NULL
) 发布于 2022-06-11 17:08:23
你能粘贴一些样本数据,我已经采取了一些虚拟数据和复制您的代码。
>>> df = spark.read.csv("/Path to/sample1.csv", sep="|", header="true", inferSchema="false")
>>> df.show()
+------------+----------+
|Payment_Date|Hiring_Fee|
+------------+----------+
| 11-10-2022| 89296|
| 12-10-2022| 67760|
| null| 879798|
+------------+----------+
>>> df1 = df.select( *[ F.when(F.col(column).isNull(),'').otherwise(F.col(column)).alias(column) for column in df.columns])
>>> df1.show()
+------------+----------+
|Payment_Date|Hiring_Fee|
+------------+----------+
| 11-10-2022| 89296|
| 12-10-2022| 67760|
| null| 879798|
+------------+----------+
# you see in the df1 null is still there, it is not replaced.
>>> df2 = df1.withColumn("Hiring_Date", to_timestamp("Payment_Date")) \
... .withColumn("Hiring_Fee", df1.Hiring_Fee.cast('double'))
>>> df2.show()
+------------+----------+-----------+
|Payment_Date|Hiring_Fee|Hiring_Date|
+------------+----------+-----------+
| 11-10-2022| 89296.0| null|
| 12-10-2022| 67760.0| null|
| null| 879798.0| null|
+------------+----------+-----------+在这里,雇用日期col具有所有空值。
这可能是因为我使用了虚拟数据,但您必须检查df1中是否存在空值。
https://stackoverflow.com/questions/72585751
复制相似问题