【发布时间】:2019-01-21 19:14:16
【问题描述】:
我是一个新的火花,我正在尝试使用以下火花函数执行分组和计数:
Dataset<Row> result = dataset
.groupBy("column1", "column2")
.count();
但我读到here 说使用 group by 不是一个好主意,因为它没有组合器,这反过来会影响 spark 作业的运行时效率。 相反,应该使用 reduceByKey 函数进行聚合操作。
所以我尝试使用reduceByKey 函数,但它不适用于dataset。相反,数据集使用reduce(ReduceFunction<Row> func)。
由于找不到使用reduce函数执行分组和计数的示例,我尝试将其转换为JavaRDD并使用reduceByKey:
//map each row to 1 and then group them by key
JavaPairRDD<String[], Integer> mapOnes;
try {
mapOnes = dailySummary.javaRDD().mapToPair(
new PairFunction<Row, String[], Integer>() {
@Override
public Tuple2<String[], Integer> call(Row t) throws Exception {
return new Tuple2<String[], Integer>(new String[]{t.getAs("column1"), t.getAs("column2")}, 1);
}
});
}catch(Exception e) {
log.error("exception in mapping ones: "+e);
throw new Exception();
}
JavaPairRDD<String[], Integer> rowCount;
try {
rowCount = mapOnes.reduceByKey(
new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer v1, Integer v2) throws Exception {
return v1+v2;
}
});
}catch(Exception e) {
log.error("exception in reduce by key: "+e);
throw new Exception();
}
但这也给了org.apache.spark.SparkException: Task not serializablemapToPair函数的异常。
谁能建议一种更好的方法来使用数据集的reduce 和map 函数进行分组和执行计数。
感谢任何帮助。
【问题讨论】:
-
如果我能给你一个小费,请使用 SCALA。 Java 不在它所在的位置,除了可能是 KAFKA。
-
“但我在这里读到,使用 group by 不是一个好主意,因为它没有组合器” - DataFrame / Dataset groupBy behaviour/optimization
标签: java apache-spark mapreduce dataset