146、Spark核心编程进阶之coalesce以及公司部门整合案例

coalesce算子,功能是将RDD的partition缩减,减少 ,将一定量的数据,压缩到更少的partition中去

建议的使用场景,配合filter算子使用,使用filter算子过滤掉很多数据以后,比如30%的数据,出现了很多partition中的数据不均匀的情况,此时建议使用coalesce算子,压缩rdd的partition数量,从而让各个partition中的数据都更加的紧凑

公司原先有6个部门,但是呢,不巧,碰到了公司裁员,裁员以后呢,有的部门中的人员就没了,不同的部分人员不均匀,此时呢,做一个部门整合的操作,将不同的部门的员工进行压缩

public class Coalesce {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf()
                .setAppName("Coalesce")
                .setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(conf);
        List<String> staffList = Arrays.asList("张三", "李四", "王二", "麻子",
                "赵六", "王五", "李大个", "王大妞", "小明", "小倩");
        JavaRDD<String> staffRDD = sc.parallelize(staffList, 6);

        JavaRDD<String> staffRDD2 = staffRDD.mapPartitionsWithIndex(

                new Function2<Integer, Iterator<String>, Iterator<String>>() {

                    @Override
                    public Iterator<String> call(Integer index, Iterator<String> iterator)
                            throws Exception {
                        List<String> list = new ArrayList<String>();

                        while (iterator.hasNext()) {
                            String staff = iterator.next();
                            list.add("部门[" + (index + 1) + "], " + staff);
                        }

                        return list.iterator();
                    }

                }, true);

        for (String staffInfo : staffRDD2.collect()) {
            System.out.println(staffInfo);
        }

        JavaRDD<String> staffRDD3 = staffRDD2.coalesce(3);
        
        JavaRDD<String> staffRDD4 = staffRDD3.mapPartitionsWithIndex(

                new Function2<Integer, Iterator<String>, Iterator<String>>() {
                    @Override
                    public Iterator<String> call(Integer index, Iterator<String> iterator)
                            throws Exception {
                        List<String> list = new ArrayList<String>();

                        while (iterator.hasNext()) {
                            String staff = iterator.next();
                            list.add("部门[" + (index + 1) + "], " + staff);
                        }

                        return list.iterator();
                    }

                }, true);

        for (String staffInfo : staffRDD4.collect()) {
            System.out.println(staffInfo);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值