gpt4 book ai didi

scala - 何时使用 countByValue 何时使用 map().reduceByKey()

转载 作者:行者123 更新时间:2023-12-03 18:14:21 26 4
gpt4 key购买 nike

我是 Spark 和 Scala 的新手,正在研究一个简单的 wordCount 示例。

因此,我使用 countByValue 如下:

val words = lines.flatMap(x => x.split("\\W+")).map(x => x.toLowerCase())
val wordCount = words.countByValue();

这工作正常。

同样的事情可以实现:
val words = lines.flatMap(x => x.split("\\W+")).map(x => x.toLowerCase())
val wordCounts = words.map(x => (x, 1)).reduceByKey((x, y) => x + y)
val sortedWords = wordCounts.map(x => (x._2, x._1)).sortByKey()

这也很好用。

现在,我的问题是什么时候使用哪些方法?
哪一个比另一个更受欢迎?

最佳答案

至少在 PySpark 中,它们是不同的东西。
countByKey使用 reduce 实现,这意味着驱动程序将收集分区的部分结果并自行进行合并。如果你的结果很大,那么驱动就得合并大量的大词典,这会让驱动抓狂。
reduceByKey shuffle key 给不同的executor,对每个worker做reduce,所以数据量大更有利。

总之,当你的数据很大时,使用 map , reduceByKeycollect会让你的司机更开心。如果你的数据很小,countByKey将引入更少的网络流量(少一个阶段)。

关于scala - 何时使用 countByValue 何时使用 map().reduceByKey(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52915466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com