[英]Spark UDF for sequence Generator
全部,
我正在尝试为 spark dataframe 创建 UDF,它将用于生成每行的唯一 ID。 为了确保唯一性,我依赖于:ID 生成器将采用“时间戳的纪元值(bigint)+”作为参数传递的唯一源 ID + randomNumber 5 位数字
我有两个问题:
error:Type mismatch;
found : String(SRC_")
required : org.apache.spark.sql.Column
df.withColumn("rowkey",SequenceGeneratorUtil.GenID("SRC_") )
请提供任何指针...
Object SequenceGeneratorUtil extends Serializable {
val random = new scala.util.Random
val start = 10000
val end = 99999
//CustomEpochGenerator - this is custom function to generate the epoch value for current timestamp in milliseconds
// ID Generator will take "epoch value of timestamp ( bigint ) + "unique Source ID passed as argument + randomNumber 5 digit
def idGenerator(SrcIdentifier: String ): String = SrcIdentifier + CustomEpochGenerator.nextID.toString + (start + random.nextInt((end - start) + 1)).toString // + monotonically_increasing_id ( not working )
val GenID = udf[String, String](idGenerator __)
}
val df2 = df.withColumn("rowkey",SequenceGeneratorUtil.GenID("SRC_") )
下面改function
def idGenerator(SrcIdentifier: String ): String = SrcIdentifier + CustomEpochGenerator.nextID.toString + (start + random.nextInt((end - start) + 1)).toString // + monotonically_increasing_id ( not working )
到 function 以下,在idGenerator
中添加mId
额外参数以保存monotonically_increasing_id
值。
def idGenerator(SrcIdentifier: String,mId: Long): String = SrcIdentifier + CustomEpochGenerator.nextID.toString + (start + random.nextInt((end - start) + 1)).toString + mId
在udf
以下更改
val GenID = udf[String, String](idGenerator __)
到
val GenID = udf(idGenerator _)
因以下错误而失败:错误:类型不匹配; 发现:字符串(SRC_")需要:org.apache.spark.sql.Column df.withColumn(“rowkey”,SequenceGeneratorUtil.GenID(“SRC_”))
因为SequenceGeneratorUtil.GenID
udf 期望org.apache.spark.sql.Column
类型的值,但您传递的值SRC_
是String
类型。
要解决此问题,请使用lit
function。
df.withColumn("rowkey",SequenceGeneratorUtil.GenID(lit("SRC_")) )
下面更改withColumn
val df2 = df.withColumn("rowkey",SequenceGeneratorUtil.GenID("SRC_") )
到
val df2 = df
.withColumn(
"rowkey",
SequenceGeneratorUtil.GenID(
lit("SRC_"), // using lit function to pass static string.
monotonically_increasing_id
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.