如何在Java中将Spark DataFrame转换为POJO的RDD

时间:2017-03-17 16:48:51

标签: java apache-spark dataframe rdd

我对Spark很新。我想将DataFrame转换为POJO的RDD。像:

JavaRDD<POJOClass> data = df.toJavaRDD();

其中df是一个DataFrame。

df.show()给出:

+---------+---------+---------+---------+                                       
|    A    |    B    |    C    |    D    |
+---------+---------+---------+---------+
|603300042|     1025|        2|127000948|
|603303766|     1112|        2|127000364|
|603302691|     1184|        2|127000853|
|603303766|     1112|        2|127000364|
|603302691|     1184|        2|127000853|
|603303766|     1112|        2|127000364|
|603303787|     1041|        2|137000323|
|603306351|     1041|        2|137000468|
|603304009|     1307|        2|137000788|
|603303830|     1041|        2|137000012|
|603301119|     1002|        2|137000369|
|603301507|     1188|        2|137001568|
|603302168|     1041|        2|137000468|
+---------+---------+---------+---------+

我的POJO课程如下:

public static class POJOClass {
        public Long A;
        public Integer B;
        public Integer C;
        public Long D;
}

我知道

JavaRDD<Row> data = df.toJavaRDD();

运作良好。但是我有什么办法可以解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

您可以使用如下的地图功能。

import org.apache.spark.api.java.function.Function;

JavaRDD<POJOClass> data = df.toJavaRDD().map(new Function<Row, POJOClass>() {
        @Override
        public POJOClass call(Row row) {
        POJOClass pojo = new POJOClass();
        pojo.setA(row.getLong(0));
        pojo.setB(row.getInt(1));
        pojo.setC(row.getInt(2));
        pojo.setD(row.getLong(3));
        return pojo;
    }
});

答案 1 :(得分:0)

您可以使用数据集

public static class POJOClass implements serializable{
        public Long A;
        public Integer B;
        public Integer C;
        public Long D;
}

     Dataset<POJOClass> pojos = context.read().json("/data.json").as(Encoders.bean(POJOClass.class)); 

答案 2 :(得分:0)

试试这个(未经测试):

def new_state
  grid = @grid.collect(&:dup)
  Board.new(grid)
end