我正在将 (Java) Spark Dataframe 写入 json。其中一列是 mllib 稀疏 vector 。后来我将 json 文件读入第二个数据帧,但是稀疏 vector 列现在是一个 WrappedArray,在第二个数据帧中没有被读取为稀疏 vector 。我的问题:为了获得稀疏 vector 列而不是 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 将保留 vector 类型并提供模式发现机制。
关于java - 将 Spark Dataframe 写入 JSON 会丢失 MLLIB 稀疏 vector 的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37839646/