Spark SHA 哈希返回为空

Spark SHA Hash Coming Back Empty

我正在尝试为数据帧中的每一行创建一个 SHA256 哈希值。

import org.apache.spark.sql.functions.{col, concat, sha2}
val finalResultWithHash = finalResult.withColumn("ROWHASH", sha2(concat(finalResult.columns.map(col):_*), 256))

当我在数据框中只有一列时,它似乎可以正常工作。

稍后在代码中,我将数据帧写为 CSV,并且 rowhash 列为空。 我找不到任何关于我做错了什么的文档。

提前致谢。

由于某些原因,下面的代码适用于多列

val finalResultWithHash = personDF.withColumn("ROWHASH", sha2(concat(personDF.columns.map(col): _*), 256))

+-----+-----+---+------+--------------------+
|FName|LName|Age|Gender|             ROWHASH|
+-----+-----+---+------+--------------------+
|    A|    B| 29|     M|c4ae6946a295e9d74...|
|    A|    C| 12|      |89a18fdc3ddb3c2fd...|
|    B|    D| 35|     F|ef1c89dfc765c7e1e...|
|    Q|    D| 85|      |cd91aa387a7e6a180...|
|    W|    R| 14|      |e9ff9bb78fd93a13a...|
+-----+-----+---+------+--------------------+

会不会只是支架位置错误...

另一种方法是使用 foldLeft():

val df2 = df.withColumn("rowsha",sha2(df.columns.foldLeft(lit(""))((x,y)=>concat(x,col(y))),256))

折叠将在散列之前从左到右连接所有列:

df.withColumn("rowsha",sha2(df.columns.foldLeft(lit(""))((x,y)=>concat(x,col(y))),256)).explain()
== Physical Plan ==
*(1) Project [c1#10, c2#11, c3#12, c4#13, sha2(cast(concat(, c1#10, c2#11, c3#12, 4#13) as binary), 256) AS rowsha#165]
+- *(1) ...

但是,如果串联中的任何列包含 NULL,则结果也将为 NULL。为了防止这种情况,您可能需要使用类似

的东西
val df2 = df.withColumn("rowsha",sha2(df.columns.foldLeft(lit(""))((x,y)=>concat(x,coalesce(col(y),lit("n/a"))),256))