ReduceByKey of Spark RDD operation

1. The role of reduceByKey

    reduceByKey merges all K, V pairs in the RDD and V with the same K value, and this merging is only performed according to the function passed in by the user. The following is an example of wordcount.

import java.util.Arrays;
import java.util.List;

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

import scala.Tuple2;

public class WordCount {

	public static void main(String[] args) {
		SparkConf conf = new SparkConf().setAppName("spark WordCount!").setMaster("local[*]");
		JavaSparkContext javaSparkContext = new JavaSparkContext(conf);
		List<Tuple2<String, Integer>> list = Arrays.asList(new Tuple2<String, Integer>("hello", 1),
				new Tuple2<String, Integer>("word", 1), new Tuple2<String, Integer>("hello", 1),
				new Tuple2<String, Integer>("simple", 1));
		JavaPairRDD<String, Integer> listRDD = javaSparkContext.parallelizePairs(list);
		
		/**
		 * spark的shuffle是hash-based的,也就是reduceByKey算子的两个入参一个是来源于hashmap,一个来源于从map端拉取的数据,对于wordcount例子而言,进行如下运行
		 * hashMap.get(Key)+ Value,计算结果重新put回hashmap,循环往复,就迭代出了最后结果
		 */
		JavaPairRDD<String, Integer> wordCountPair = listRDD.reduceByKey(new Function2<Integer, Integer, Integer>() {
			@Override
			public Integer call(Integer v1, Integer v2) throws Exception {
				return v1 + v2;
			}
		});
		wordCountPair.foreach(new VoidFunction<Tuple2<String, Integer>>() {
			@Override
			public void call(Tuple2<String, Integer> tuple) throws Exception {
				System.out.println(tuple._1 + ":" + tuple._2);
			}
		});
	}

}

    Calculation results:

    

2. The principle of reduceByKey is as follows

     

 

 

 

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324187184&siteId=291194637