在Spark UDF JAVA中传递额外的变量



我在JAVA中编写了一个spark UDF来加密数据帧中的特定列。它是类型 1 UDF,一次只接受需要加密或解密的字符串。我也想传递相应的密码。我尝试了柯里方法,但无法正确编写函数。谁能给我任何解决方案?

public class EncryptString implements UDF1<String, String> {

@Override
public String call(String s) throws Exception {
return Aes256.encrypt(s);  
//Aes.encrypt needs to have another variable password.
//So that while calling the UDF we can pass the required password.
}
}

您可以将密码以及任何其他参数作为构造函数参数传递给EncryptString类:

public static class EncryptString implements UDF1<String, String> {
private final String password; 
public EncryptString(String password) {
this.password = password;
}
public String call(String s) throws Exception { 
return Aes256.encrypt(s, password);
}
}

实例化 udf 时,可以传递实际密码:

spark.sqlContext().udf().register("EncryptUdf", new EncryptString("secret"), DataTypes.StringType);
[...]
spark.sql("select EncryptUdf(_c2) from df").show();

最新更新