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

writing Spark Dataframe to JSON loses format for MLLIB Sparse Vector

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

写作:

initialDF.coalesce(1).write().json("initial_dataframe");

阅读中:

DataFrame secondDF = hiveContext.read().json("initial_dataframe");

答案很简单。为 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)

提供正确的架构时

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])|
// +---+-------------------+

一般来说,如果您使用不提供模式发现机制的来源 providing schema explicitly is a good idea

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