Spark核心之top、take和takeOrdered |
您所在的位置:网站首页 › take和make的用法 › Spark核心之top、take和takeOrdered |
top、take和takeOrdered三种算子都是Spark中的Action操作,当原始数据集太大时,可以采用上述三个算子展示数据,下面分别介绍三个算子: (1)takeOrdered算子 takeOrdered(num: Int)(implicit ord: Ordering[T]): Array[T]关于top算子在源码中的解释如下: /** * Returns the first k (smallest) elements from this RDD as defined by the specified * implicit Ordering[T] and maintains the ordering. This does the opposite of [[top]]. * For example: * {{{ * sc.parallelize(Seq(10, 4, 2, 12, 3)).takeOrdered(1) * // returns Array(2) * * sc.parallelize(Seq(2, 3, 4, 5, 6)).takeOrdered(2) * // returns Array(2, 3) * }}} **/该算子返回RDD中最小的k个元素,其中排序规则用户可以自定义ord。 (2)top算子 top(num: Int)(implicit ord: Ordering[T]): Array[T]top算子是与takeOrdered算子的相反的操作,该算子返回RDD中的最大的k个元素 查看top源码可以知道,top方法本身是调用了takeOrdered: def top(num: Int)(implicit ord: Ordering[T]): Array[T] = withScope { takeOrdered(num)(ord.reverse) } (3)take算子 take(num: Int): Array[T]take算子获取RDD中的前num个元素。 /** * Take the first num elements of the RDD. It works by first scanning one partition, and use the * results from that partition to estimate the number of additional partitions needed to satisfy * the limit. */---------------------------------------------------------------------------个人实践中遇到的问题---------------------------------------- 之所以写这篇博客,是因为自己在使用top和take的过程中遇到了一点问题: val reduceRdd: RDD[(String, Double)] = mapRdd.reduceByKey(_+_) val sortRdd: RDD[(String, Double)] = reduceRdd.sortBy(_._2,false) val result: Array[(String, Double)] = sortRdd.take(10)在上述代码中,我是想获得排序后的前10个元素(即Value最大的前10个元素),使用take即可获得答案;我一开始使用的是top(10),但返回的结果是按照Key排序取出的前10个,应该是默认按照key排序。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |