昨天(实际上是完整的日记),我试图找出一种优雅的方式来表示带有 Scala / Spark SQL 2.2.1 的循环引用的模型。
让我们说这是原始的模型方法,它当然不起作用(请记住,实际模型具有数十个属性):
case class Branch(id: Int, branches: List[Branch] = List.empty)
case class Tree(id: Int, branches: List[Branch])
val trees = Seq(Tree(1, List(Branch(2, List.empty), Branch(3, List(Branch(4, List.empty))))))
val ds = spark.createDataset(trees)
ds.show
这是它引发的错误:
java.lang.UnsupportedOperationException: cannot have circular references in class, but got the circular reference of class Branch
我知道我们拥有的最高等级为5 。因此,作为一种解决方法,我虽然使用以下方法:
case class BranchLevel5(id: Int)
case class BranchLevel4(id: Int, branches: List[BranchLevel5] = List.empty)
case class BranchLevel3(id: Int, branches: List[BranchLevel4] = List.empty)
case class BranchLevel2(id: Int, branches: List[BranchLevel3] = List.empty)
case class BranchLevel1(id: Int, branches: List[BranchLevel2] = List.empty)
case class Tree(id: Int, branches: List[BranchLevel1])
当然可以了。但这一点都不优雅,您可以想象实现过程中的痛苦(可读性,耦合性,维护性,可用性,代码重复性等)
问题是,如何处理模型中带有循环引用的案例?
答案 0 :(得分:0)
如果您可以使用私有API,那么我发现了一种可行的方法:将整个自引用结构视为用户定义的类型。我正在遵循以下答案中的方法:https://stackoverflow.com/a/51957666/1823254。
package org.apache.spark.custom.udts // we're calling some private API so need to be under 'org.apache.spark'
import java.io._
import org.apache.spark.sql.types.{DataType, UDTRegistration, UserDefinedType}
class BranchUDT extends UserDefinedType[Branch] {
override def sqlType: DataType = org.apache.spark.sql.types.BinaryType
override def serialize(obj: Branch): Any = {
val bos = new ByteArrayOutputStream()
val oos = new ObjectOutputStream(bos)
oos.writeObject(obj)
bos.toByteArray
}
override def deserialize(datum: Any): Branch = {
val bis = new ByteArrayInputStream(datum.asInstanceOf[Array[Byte]])
val ois = new ObjectInputStream(bis)
val obj = ois.readObject()
obj.asInstanceOf[Branch]
}
override def userClass: Class[Branch] = classOf[Branch]
}
object BranchUDT {
def register() = UDTRegistration.register(classOf[Branch].getName, classOf[BranchUDT].getName)
}
只需创建并注册一个自定义的UDT,就是这样!
BranchUDT.register()
val trees = Seq(Tree(1, List(Branch(2, List.empty), Branch(3, List(Branch(4, List.empty))))))
val ds = spark.createDataset(trees)
ds.show(false)
//+---+----------------------------------------------------+
//|id |branches |
//+---+----------------------------------------------------+
//|1 |[Branch(2,List()), Branch(3,List(Branch(4,List())))]|
//+---+----------------------------------------------------+