【问题标题】:Serialize object that contains a Dataset序列化包含数据集的对象
【发布时间】:2019-01-26 12:32:39
【问题描述】:

我正在使用带有 Java 的 Spark 2.3.1 我有一个封装数据集的对象。我希望能够序列化和反序列化这个对象。

我的代码如下:

public class MyClass implements Serializable {

    private static final long serialVersionUID = -189012460301698744L;

    public Dataset<Row> dataset;

    public MyClass(final Dataset<Row> dataset) {
        this.dataset = dataset;
    }

    /**
     * Save the current instance of MyClass into a file as a serialized object.
     */
    public void save(final String filepath, final String filename) throws Exception{
        File file = new File(filepath);
        file.mkdirs();

        file = new File(filepath+"/"+filename);
        try (final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            oos.writeObject(this);
        } 
    }

    /**
     * Create a new MyClass from a serialized MyClass object
     */
    public static MyClass load(final String filepath) throws Exception{
        final File file = new File(filepath);
        final MyClass myclass;
        try (final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
              myclass = ((MyClass) ois.readObject());
        }

        System.out.println("test 1 : "+ myclass);
        System.out.println("test 2 : "+ myclass.dataset);
        myclass.dataset.printSchema();

        return myclass;
    }      
    // Some other functions   
}

但序列化似乎没有正确完成。 load() 函数给我以下显示:

test 1 : MyClass@520e6089
test 2 : Invalid tree; null:
null

并在 printSchema() 上抛出 java.lang.NullPointerException

正确序列化我的对象缺少什么?

【问题讨论】:

    标签: java apache-spark serialization


    【解决方案1】:

    Spark Datasets 仅在用于创建这些的会话范围内有意义。因此序列化Dataset 完全没有意义。

    • 如果您想序列化数据,只需将Dataset 写入持久存储即可。
    • 如果您想“序列化”管道,只需继续使用采用某种输入形式并返回所需Dataset 的代码(方法)。不要尝试序列化 Dataset 本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      相关资源
      最近更新 更多