How to convert DataFrame to Dataset in Apache Spar

2020-05-20 08:23发布

问题:

I can convert DataFrame to Dataset in Scala very easy:

case class Person(name:String, age:Long)
val df = ctx.read.json("/tmp/persons.json")
val ds = df.as[Person]
ds.printSchema

but in Java version I don't know how to convert Dataframe to Dataset? Any Idea?

my effort is:

DataFrame df = ctx.read().json(logFile);
Encoder<Person> encoder = new Encoder<>();
Dataset<Person> ds = new Dataset<Person>(ctx,df.logicalPlan(),encoder);
ds.printSchema();

but the compiler say:

Error:(23, 27) java: org.apache.spark.sql.Encoder is abstract; cannot be instantiated

Edited(Solution):

solution based on @Leet-Falcon answers:

DataFrame df = ctx.read().json(logFile);
Encoder<Person> encoder = Encoders.bean(Person.class);
Dataset<Person> ds = new Dataset<Person>(ctx, df.logicalPlan(), encoder);

回答1:

Official Spark docs suggest in Dataset API the following:

Java Encoders are specified by calling static methods on Encoders.

List<String> data = Arrays.asList("abc", "abc", "xyz");
Dataset<String> ds = context.createDataset(data, Encoders.STRING());

Encoders can be composed into tuples:

Encoder<Tuple2<Integer, String>> encoder2 = Encoders.tuple(Encoders.INT(), Encoders.STRING());
List<Tuple2<Integer, String>> data2 = Arrays.asList(new scala.Tuple2(1, "a");
Dataset<Tuple2<Integer, String>> ds2 = context.createDataset(data2, encoder2);

Or constructed from Java Beans by Encoders#bean:

Encoders.bean(MyClass.class);


回答2:

If you want to convert a generic DF to a Dataset in Java, you can use RowEncoder class like below

DataFrame df = sql.read().json(sc.parallelize(ImmutableList.of(
            "{\"id\": 0, \"phoneNumber\": 109, \"zip\": \"94102\"}"
    )));

    Dataset<Row> dataset = df.as(RowEncoder$.MODULE$.apply(df.schema()));