首页 > 解决方案 > Spark:将 Array[Byte] 数据转换为 RDD 或 DataFrame

问题描述

我有 Array[Byte] 形式的数据,我想将其转换为 Spark RDD 或 DataFrame,以便我可以将数据以文件的形式直接写入 Google 存储桶。我无法将 Array[Byte] 数据直接写入 Google 存储桶。所以寻找这种转换。

我下面的代码能够将数据写入本地 FS,但不能写入 Google 存储桶

val encrypted = encrypt(original, readPublicKey(pubKey), outFile, true, true)
val dfis = new FileOutputStream(outFile)
dfis.write(encrypted)
dfis.close()

def encrypt(clearData: Array[Byte], encKey: PGPPublicKey, fileName: String, withIntegrityCheck: Boolean, armor: Boolean): Array[Byte] = {
...
}

那么如何将 Array[Byte] 数据转换为 RDD 或 DataFrame?我正在使用斯卡拉。

标签: scalaapache-spark

解决方案


只需使用.toDF().toDF().rdd

scala> val arr: Array[Byte] = Array(192.toByte, 168.toByte, 1.toByte, 4.toByte)
arr: Array[Byte] = Array(-64, -88, 1, 4)

scala> val df = arr.toSeq.toDF()
df: org.apache.spark.sql.DataFrame = [value: tinyint]

scala> df.show()
+-----+
|value|
+-----+
|  -64|
|  -88|
|    1|
|    4|
+-----+


scala> df.printSchema()
root
 |-- value: byte (nullable = false)

推荐阅读