map
是最简单的,它本质上说,做序列的每个元素在给定的操作并返回结果序列(非常类似于foreach)。 flatMap
是同样的事情,但不是只有一个元素每个元素返回你被允许返回一个序列(可以为空)。这是一个解释difference between map
and flatMap
的答案。最后reduceByKey
需要聚合函数(意味着它采用两个相同类型的参数和返回类型,也应该是交换和关联,否则你会得到不一致的结果),这是用于聚合每V
每个K
在你的(K,V)
对序列。
例*:
reduce (lambda a, b: a + b,[1,2,3,4])
这是说集合体+
整个列表,它会做
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
final result is 10
者皆减少,除了你同样的事情做一个减少每个独特键。
所以要解释它在你的榜样
file = spark.textFile("hdfs://...") // open text file each element of the RDD is one line of the file
counts = file.flatMap(lambda line: line.split(" ")) //flatMap is needed here to return every word (separated by a space) in the line as an Array
.map(lambda word: (word, 1)) //map each word to a value of 1 so they can be summed
.reduceByKey(lambda a, b: a + b) // get an RDD of the count of every unique word by aggregating (adding up) all the 1's you wrote in the last step
counts.saveAsTextFile("hdfs://...") //Save the file onto HDFS
那么,为什么算的话这种方式,原因是节目的MapReduce的范例是高度并行,从而扩展到这样做计算TB或甚至数PB的数据。
我不使用python多告诉我,如果我犯了一个错误。
我不是专家,但我认为flatMap建立从嵌套结构(字行的名单?)的列表,地图应用功能的所有元素,一个d reduceByKey按键对这些元素进行分组(我猜这里是相同的单词),并将函数(这里是一个和)成对地应用。这可能会计数文本中每个单词的出现次数。 – user189
如果您使用函数式语言来进行函数式编程,事情会变得更加简洁和易于阅读。即我强烈建议使用Scala而不是OO脚本语言。 Scala功能更强大,对Spark更具性能,并且更容易挖掘Spark代码。你的代码变成:'spark.textFile(“hdfs:// ...”).flatMap(_。split(“”))。map((_,1))。reduceByKey(_ + _)。saveAsTextFile “hdfs:// ...”)' – samthebest