获取 Spark RDD 中每个键的最大值 [英] Get the max value for each key in a Spark RDD

查看:34
本文介绍了获取 Spark RDD 中每个键的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回与 spark RDD 中每个唯一键关联的最大行(值)的最佳方法是什么?

What is the best way to return the max row (value) associated with each unique key in a spark RDD?

我正在使用 python 并且我尝试过 Math max,通过键和聚合进行映射和减少.有没有一种有效的方法来做到这一点?可能是 UDF?

I'm using python and I've tried Math max, mapping and reducing by keys and aggregates. Is there an efficient way to do this? Possibly an UDF?

我有 RDD 格式:

[(v, 3),
 (v, 1),
 (v, 1),
 (w, 7),
 (w, 1),
 (x, 3),
 (y, 1),
 (y, 1),
 (y, 2),
 (y, 3)]

我需要返回:

[(v, 3),
 (w, 7),
 (x, 3),
 (y, 3)]

关系可以返回第一个值或随机值.

Ties can return the first value or random.

推荐答案

实际上你有一个 PairRDD.最好的方法之一是使用 reduceByKey:

Actually you have a PairRDD. One of the best ways to do it is with reduceByKey:

(斯卡拉)

val grouped = rdd.reduceByKey(math.max(_, _))

(Python)

grouped = rdd.reduceByKey(max)

(Java 7)

JavaPairRDD<String, Integer> grouped = new JavaPairRDD(rdd).reduceByKey(
    new Function2<Integer, Integer, Integer>() {
        public Integer call(Integer v1, Integer v2) {
            return Math.max(v1, v2);
    }
});

(Java 8)

JavaPairRDD<String, Integer> grouped = new JavaPairRDD(rdd).reduceByKey(
    (v1, v2) -> Math.max(v1, v2)
);

reduceByKey 的 API 文档:

API doc for reduceByKey:

这篇关于获取 Spark RDD 中每个键的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆