在 Spark UDF 中传递额外变量 JAVA

passing extra variables in Spark UDF JAVA

我在 JAVA 中编写了 spark UDF 来加密数据帧中的特定列。它是type 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 class:

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();