在Spark数据集中将ujson.Value编码

时间:2018-12-10 13:17:12

标签: scala apache-spark upickle

假设我存储的这些JSON行是一个文本文件。

{"a": "...", "data": [{}]}
{"a": "...", "data": [{"b": "..."}]}
{"a": "...", "data": [{"d": "..."}]}
{"a": "...", "data": [{"b": "...", "c": "..."}]}

我想将文件处理为Spark Dataset,但是我不知道字段data的确切架构。我使用upickle将JSON转换为案例类

case class MyCC(a: String, data: Seq[ujson.Value.Obj])

implicit val r: Reader[MyCC] = macroR

sc.textFile("s3://path/to/file.txt")
  .map(uread[MyCC](_))
  .toDS                 // Dataset[MyCC]
  .show()

尝试此操作,出现以下错误:

java.lang.UnsupportedOperationException: No Encoder found for ujson.Value
- map value class: "ujson.Value"
- field (class: "scala.collection.mutable.LinkedHashMap", name: 
"value")
- array element class: "ujson.Obj"
- field (class: "scala.collection.Seq", name: "data")
- root class: "com.mycaule.MyCC"

如何解决此数据建模问题?

谢谢

1 个答案:

答案 0 :(得分:0)

我可以读取数据而无需创建所需的自定义编码器。我只是正确定义了案例类。

import scala.collection.mutable
case class CustomClass( a: String,
                        data: List[mutable.HashMap[String,String]]
                              )

val dataSourceName =  "s3/path/to/data.json"

val schema = ScalaReflection.schemaFor[CustomClass].dataType.asInstanceOf[StructType]

val data = spark.read.schema(schema).json(dataSourceName).as[CustomClass]

data.show(10, truncate = false)

以下是输出:

+---+----------------------+
|a  |data                  |
+---+----------------------+
|...|[[]]                  |
|...|[[b -> ...]]          |
|...|[[d -> ...]]          |
|...|[[b -> ..., c -> ...]]|
+---+----------------------+