首页 文章

在Scala中,我如何获取Spark RDD并输出到不同的文件,按列的值分组? [重复]

提问于
浏览
0

这个问题在这里已有答案:

如果有像这样的Spark RDD:

id  | data
----------
1   | "a"
1   | "b"
2   | "c"
3   | "d"

我怎么能把它输出到单独的json文本文件,根据id分组? part-0000-1.json将包含行“a”和“b”,part-0000-2.json包含“c”等 .

2 回答

  • 0
    df.write.partitionBy("col").json(<path_to_file>)
    

    是你需要的 .

  • 2

    感谢@thebluephantom,我能够理解出了什么问题 .

    我从根本上误解了Spark . 当我最初在@thebluephantom建议时做 df.write.partitionBy("col").json(<path_to_file>) 时,我很困惑为什么我的输出被分成许多不同的文件 .

    我已经添加 .repartition(1) 将所有数据收集到一个节点,然后 partitionBy("col") 将此处的数据拆分为多个文件输出 . 我的最终代码是:

    latestUniqueComments
      .repartition(1)
      .write
      .mode(SaveMode.Append)
      .partitionBy("_manual_file_id")
      .format("json")
      .save(outputFile)
    

相关问题