如何在Java Spark RDD上执行标准偏差和平均操作?

时间:2016-05-29 12:15:07

标签: java apache-spark rdd bigdata

我有一个看起来像这样的JavaRDD。

[
[A,8]
[B,3]
[C,5]
[A,2]
[B,8]
...
...
]

我想要我的结果 意味着

[
[A,5]
[B,5.5]
[C,5]
]

如何仅使用Java RDD执行此操作。 P.S:我想避免使用groupBy操作,所以我没有使用DataFrames。

2 个答案:

答案 0 :(得分:2)

你走了:

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.util.StatCounter;
import scala.Tuple2;
import scala.Tuple3;

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

public class AggregateByKeyStatCounter {

  public static void main(String[] args) {

    SparkConf conf = new SparkConf().setAppName("AggregateByKeyStatCounter").setMaster("local");
    JavaSparkContext sc = new JavaSparkContext(conf);

    List<Tuple2<String, Integer>> myList = Arrays.asList(new Tuple2<>("A", 8), new Tuple2<>("B", 3), new Tuple2<>("C", 5),
            new Tuple2<>("A", 2), new Tuple2<>("B", 8));

    JavaRDD<Tuple2<String, Integer>> data = sc.parallelize(myList);
    JavaPairRDD<String, Integer> pairs = JavaPairRDD.fromJavaRDD(data);

    /* I'm actually using aggregateByKey to perform StatCounter 
       aggregation, so actually you can even have more statistics available */
    JavaRDD<Tuple3<String, Double, Double>> output = pairs
                         .aggregateByKey(
                          new StatCounter(), 
                          StatCounter::merge, 
                          StatCounter::merge)
                         .map(x -> new Tuple3<String, Double, Double>(x._1(), x._2().stdev(), x._2().mean()));

    output.collect().forEach(System.out::println);
  }

}

答案 1 :(得分:0)

您可以使用reduceByKey并计算每个键的总和和计数,然后按每个键划分它们。

val means: RDD[(String, Double)] = rdd
 .map(x => (x._1, (x._2, 1))) // add 1 for each element for the count
 .reduceByKey((a,b) => (a._1+b._1, a._2+b._2)) // create a tuple (count, sum) for each key
 .map{ case (k, v) => (k, v._1 / v._2) } // calculate mean for each key