zoukankan      html  css  js  c++  java
  • java实现spark常用算子之coalesce



    import org.apache.spark.SparkConf;
    import org.apache.spark.api.java.JavaRDD;
    import org.apache.spark.api.java.JavaSparkContext;
    import org.apache.spark.api.java.function.Function2;
    import org.apache.spark.api.java.function.VoidFunction;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;

    /**
    * coalesce 算子: 将N个分区 合并为 N-M个分区
    * 分区合并(减少),在filter后使用效果更佳,可以有效避免数据倾斜问题
    *
    */
    public class CoalesceOperator {
    public static void main(String[] args){
    SparkConf conf = new SparkConf().setMaster("local").setAppName("coalesce");
    JavaSparkContext sc = new JavaSparkContext(conf);
    List<String> names = Arrays.asList("w1","w2","w3","w4","w5");

    JavaRDD<String> nameRdd = sc.parallelize(names,4);

    JavaRDD<String> namefristRdd = nameRdd.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<>();
    while (iterator.hasNext()){
    list.add("1["+index+"]:"+iterator.next());
    }
    return list.iterator();
    }
    },true);

    // 将 4 个partition减少为2个partition
    JavaRDD<String> tempRdd = namefristRdd.coalesce(2);

    JavaRDD<String> result = tempRdd.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<>();
    while (iterator.hasNext()){
    list.add("2["+index+"]:"+iterator.next());
    }
    return list.iterator();
    }
    },false);

    result.foreach(new VoidFunction<String>() {
    @Override
    public void call(String s) throws Exception {
    System.err.println(s);
    }
    });


    }
    }

    微信扫描下图二维码加入博主知识星球,获取更多大数据、人工智能、算法等免费学习资料哦!

    
    
  • 相关阅读:
    TcpClient连接帮助类
    winform中添加管理员权限控制
    textbox中输入email做格式控制
    绑定和非绑定方法
    类的封装、property、多态和多态性
    继承类之点点滴滴
    爬虫日记-正则表达式
    爬虫日记-单元总结
    爬虫日记-最好大学排名实例
    爬虫日记-第一单元总结
  • 原文地址:https://www.cnblogs.com/guokai870510826/p/11598581.html
Copyright © 2011-2022 走看看