我可以很容易地将DataFrame转换为
Scala数据集:
case class Person(name:String,age:Long) val df = ctx.read.json("/tmp/persons.json") val ds = df.as[Person] ds.printSchema
但是在Java版本中,我不知道如何将Dataframe转换为Dataset?任何想法?
我的努力是:
DataFrame df = ctx.read().json(logFile); Encoder<Person> encoder = new Encoder<>(); Dataset<Person> ds = new Dataset<Person>(ctx,df.logicalPlan(),encoder); ds.printSchema();
但是编译器说:
Error:(23,27) java: org.apache.spark.sql.Encoder is abstract; cannot be instantiated
编辑(解决方案):
基于@ Leet-Falcon的解决方案:
DataFrame df = ctx.read().json(logFile); Encoder<Person> encoder = Encoders.bean(Person.class); Dataset<Person> ds = new Dataset<Person>(ctx,encoder);
解决方法
官方Spark文档建议在
Dataset API以下:
Java Encoders are specified by calling static methods on 07001.
List<String> data = Arrays.asList("abc","abc","xyz"); Dataset<String> ds = context.createDataset(data,Encoders.STRING());
编码器可以组成元组:
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);
或从Java Bean构建到Encoders#bean:
Encoders.bean(MyClass.class);