0

假设我将这些 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"

我该如何解决这个数据建模问题?

谢谢

4

1 回答 1

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 -> ...]]|
+---+----------------------+
于 2018-12-10T13:42:44.817 回答