java - 将 Spark Dataframe 写入 JSON 会丢失 MLLIB 稀疏 vector 的格式

标签 java apache-spark apache-spark-sql apache-spark-mllib

我正在将 (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/

相关文章:

java - 优点和缺点 : having Enum or Class for Message Notification types

Java Bouncy CaSTLe TLS 协议(protocol)版本顺序?

python - 在 PySpark 上将日期时间转换为日期

java - 速度响应编写器在 Solr 中不起作用

java - 将图片设置为jpanel

scala - java.lang.NoClassDefFoundError : org/apache/spark/streaming/twitter/TwitterUtils$ while running TwitterPopularTags

python - 更改 Spark Web UI 的根路径?

apache-spark - 数据集中的分割数超过数据集分割限制,Dremio + Hive + Spark

mysql - 事务 block |星火SQL,RDD

python - 将时间序列pySpark数据帧拆分为测试和训练,而无需使用随机拆分