将 Spark 数据帧写入 JSON 会丢失 MLLIB 稀疏向量的格式

Kai*_*Kai 3 java apache-spark apache-spark-sql apache-spark-mllib

我正在将(Java)Spark Dataframe 写入 json。其中一列是 mllib 稀疏向量。后来我将 json 文件读入第二个数据帧,但稀疏向量列现在是 WrappedArray 并且在第二个数据帧中没有作为稀疏向量读取。我的问题:有什么我可以在写入端或读取端做的,以获得一个稀疏向量列而不是一个wrappedArray列?

写作:

initialDF.coalesce(1).write().json("initial_dataframe");
Run Code Online (Sandbox Code Playgroud)

读:

DataFrame secondDF = hiveContext.read().json("initial_dataframe");
Run Code Online (Sandbox Code Playgroud)

zer*_*323 5

答案很简单。提供架构DataFrameReader

import org.apache.spark.mllib.linalg.VectorUDT

val path: String = ???
val df = Seq((1L, Vectors.parse("(5, [1.0, 3.0], [2.0, 3.0])"))).toDF
df.write.json(path)

spark.read.json(path).printSchema
// root
//  |-- _1: long (nullable = true)
//  |-- _2: struct (nullable = true)
//  |    |-- indices: array (nullable = true)
//  |    |    |-- element: long (containsNull = true)
//  |    |-- size: long (nullable = true)
//  |    |-- type: long (nullable = true)
//  |    |-- values: array (nullable = true)
//  |    |    |-- element: double (containsNull = true)
Run Code Online (Sandbox Code Playgroud)

当提供正确的架构时

import org.apache.spark.mllib.linalg.VectorUDT
import org.apache.spark.sql.types.{LongType, StructField, StructType}

val schema = StructType(Seq(
  StructField("_1", LongType, true),
  StructField("_2", new VectorUDT, true)))

spark.read.schema(schema).json(path).printSchema
root
 |-- _1: long (nullable = true)
 |-- _2: vector (nullable = true)

spark.read.schema(schema).json(path).show(1)
// +---+-------------------+
// | _1|                 _2|
// +---+-------------------+
// |  1|(5,[1,3],[2.0,3.0])|
// +---+-------------------+
Run Code Online (Sandbox Code Playgroud)

一般来说,如果您使用不提供模式发现机制的源,显式提供模式是一个好主意

如果 JSON 不是硬性要求,Parquet 将保留向量类型并提供模式发现机制。