谁能给我解释一下map和flatMap之间的区别,以及它们各自的良好用例是什么?

“flatten the results”是什么意思? 它有什么好处?


当前回答

如果您正在询问RDD之间的区别。map和RDD。在Spark中,map将一个大小为N的RDD转换为另一个大小为N的RDD。如。

myRDD.map(x => x*2)

例如,如果myRDD由double组成。

而flatMap可以将RDD转换为另一个不同大小的RDD: 如:

myRDD.flatMap(x =>new Seq(2*x,3*x))

这将返回一个大小为2*N的RDD 或

myRDD.flatMap(x =>if x<10 new Seq(2*x,3*x) else new Seq(x) )

其他回答

区别可以从下面的pyspark代码示例中看到:

rdd = sc.parallelize([2, 3, 4])
rdd.flatMap(lambda x: range(1, x)).collect()
Output:
[1, 1, 2, 1, 2, 3]


rdd.map(lambda x: range(1, x)).collect()
Output:
[[1], [1, 2], [1, 2, 3]]

抽样。Map返回单个数组中的所有元素

抽样。flatMap返回数组数组中的元素

让我们假设在text.txt文件中有文本

Spark is an expressive framework
This text is to understand map and faltMap functions of Spark RDD

使用地图

val text=sc.textFile("text.txt").map(_.split(" ")).collect

输出:

text: **Array[Array[String]]** = Array(Array(Spark, is, an, expressive, framework), Array(This, text, is, to, understand, map, and, faltMap, functions, of, Spark, RDD))

使用flatMap

val text=sc.textFile("text.txt").flatMap(_.split(" ")).collect

输出:

 text: **Array[String]** = Array(Spark, is, an, expressive, framework, This, text, is, to, understand, map, and, faltMap, functions, of, Spark, RDD)

map(func)返回一个新的分布式数据集,该数据集通过func声明的函数传递源的每个元素。map()是单个项

其间

flatMap(func)类似于map,但是每个输入项可以映射到0个或多个输出项,因此func应该返回一个Sequence而不是单个项。

map和flatMap输出的差异:

1. flatmap

val a = sc.parallelize(1 to 10, 5)

a.flatMap(1 to _).collect()

输出:

 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

2.地图:

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)

val b = a.map(_.length).collect()

输出:

3 6 6 3 8

如果您正在询问RDD之间的区别。map和RDD。在Spark中,map将一个大小为N的RDD转换为另一个大小为N的RDD。如。

myRDD.map(x => x*2)

例如,如果myRDD由double组成。

而flatMap可以将RDD转换为另一个不同大小的RDD: 如:

myRDD.flatMap(x =>new Seq(2*x,3*x))

这将返回一个大小为2*N的RDD 或

myRDD.flatMap(x =>if x<10 new Seq(2*x,3*x) else new Seq(x) )