Java 如何使用spark UDF返回复杂类型
你好,先谢谢你 我的程序是用java编写的,我不能使用scala 我目前正在使用从json文件中提取的spark数据帧,使用以下行:Java 如何使用spark UDF返回复杂类型,java,json,apache-spark,user-defined-functions,udf,Java,Json,Apache Spark,User Defined Functions,Udf,你好,先谢谢你 我的程序是用java编写的,我不能使用scala 我目前正在使用从json文件中提取的spark数据帧,使用以下行: DataFrame dff=sqlContext.read().json(“filePath.son”) SQLContext和SparkContext已正确初始化并运行良好 问题是我从中读取的json具有嵌套结构,我希望在不更改模式的情况下清理/验证内部数据 数据帧的一个列特别具有“GenericRowWithSchema”类型 假设我只想清除那个列,名为“da
DataFrame dff=sqlContext.read().json(“filePath.son”)代码>
SQLContext和SparkContext已正确初始化并运行良好
问题是我从中读取的json具有嵌套结构,我希望在不更改模式的情况下清理/验证内部数据
数据帧的一个列特别具有“GenericRowWithSchema”类型
假设我只想清除那个列,名为“data”
我想到的解决方案是定义一个名为“cleanDataField”的用户定义函数(UDF),然后在“data”列上运行它。代码如下:
UDF1<GenericRowWithSchema,GenericRowWithSchema> cleanDataField = new UDF1<GenericRowWithSchema, GenericRowWithSchema>(){
public GenericRowWithSchema call( GenericRowWithSchema grws){
cleanGenericRowWithSchema(grws);
return grws;
}
};
然后我会打电话给你
df.selectExpr(“cleanDataField(data)”).show(10,false)代码>
以查看包含干净数据的前10行
最后,问题的结果是:我可以返回复杂的数据(例如自定义类对象)吗?
如果可能的话,我该怎么做?我想我必须更改udf注册的第3个参数,因为我没有返回字符串,但是我应该替换它做什么呢
谢谢假设您希望将数据类型构造为struct
为此,您可以执行以下操作:
// I am just copying the json string as is but you will need to escape it properly for java.
DataType dt = DataType.fromJson({"type":"struct","fields":[{"name":"companyid","type":"string","nullable":false,"metadata":{}},{"name":"loyaltynum","type":"integer","nullable":false,"metadata":{}},{"name":"totalprice","type":"integer","nullable":false,"metadata":{}},{"name":"itemcount","type":"integer","nullable":false,"metadata":{}}]})
然后,您可以在注册自定义项时使用该数据类型作为返回类型。我不知道您的问题是否仍然有效,但如果是这样,下面是答案:
您需要将第三个参数替换为Encoders.bean(GenericRowWithSchema).schema()
// I am just copying the json string as is but you will need to escape it properly for java.
DataType dt = DataType.fromJson({"type":"struct","fields":[{"name":"companyid","type":"string","nullable":false,"metadata":{}},{"name":"loyaltynum","type":"integer","nullable":false,"metadata":{}},{"name":"totalprice","type":"integer","nullable":false,"metadata":{}},{"name":"itemcount","type":"integer","nullable":false,"metadata":{}}]})