Apache spark 如何从Spark中的多个值计算平均值
我有一个映射器,它发出键/值对复合键和由逗号分隔的复合值 e、 g 键:a,b,c,d值:1,2,3,4,5 键:a1、b1、c1、d1值:5,4,3,2,1 键:a、b、c、d值:5,4,3,2,1 我可以使用reduceByKey轻松地对这些值求和 e、 gApache spark 如何从Spark中的多个值计算平均值,apache-spark,spark-streaming,Apache Spark,Spark Streaming,我有一个映射器,它发出键/值对复合键和由逗号分隔的复合值 e、 g 键:a,b,c,d值:1,2,3,4,5 键:a1、b1、c1、d1值:5,4,3,2,1 键:a、b、c、d值:5,4,3,2,1 我可以使用reduceByKey轻松地对这些值求和 e、 g 但问题是,我如何才能找到其中一个值的平均值。假设我想求第一个、第二个、第三个和第四个的和,但我想求第五个的平均值。我该怎么做?通过一个简单的键/值对,我可以使用mapValues函数,但不确定如何使用我的示例。请提供建议。我已使用f
但问题是,我如何才能找到其中一个值的平均值。假设我想求第一个、第二个、第三个和第四个的和,但我想求第五个的平均值。我该怎么做?通过一个简单的键/值对,我可以使用mapValues函数,但不确定如何使用我的示例。请提供建议。我已使用foldByKey函数解决了此问题。您能否分享您如何使用foldByKey解决此问题的代码?
reduceByKey(new Function2<String, String, String>() {
@Override
public String call(String value1, String value2) {
String oldValue[] = value1.toString().split(",");
String newValue[] = value2.toString().split(",");
int iFirst = Integer.parseInt(oldValue[0]) + Integer.parseInt(newValue[0]);
int iSecond = Integer.parseInt(oldValue[1]) + Integer.parseInt(newValue[1]);
int iThird = Integer.parseInt(oldValue[2]) + Integer.parseInt(newValue[2]);
int iFourth = Integer.parseInt(oldValue[3]) + Integer.parseInt(newValue[3]);
int iFifth = Integer.parseInt(oldValue[4]) + Integer.parseInt(newValue[4]);
return iFirst + "," + iSecond + ","
+ iThird+ "," + iFourth+ "," + iFifth;
}
});