我想在 PCollection 中使用 AutoValue 数据类作为对象类型,但在使用自动编码器时遇到问题:
@AutoValue
public abstract class MyPersonClass {
public abstract String getName();
public abstract Integer getAge();
public abstract Float getHeight();
public static MyPersonClass create(String name, Integer age, Float height) {
return new AutoValue_MyPersonClass(name, age, height);
}
}
每当我使用这个时,我都会从 Beam 尝试选择编码器时收到错误。我不想为其定义自己的编码器。
如何使用编码器来推断 AutoValue 类的架构?或者可以自动推断出不同的编码器吗?
最佳答案
Beam 有一个实用程序可以自动推断不同数据类的架构,包括 Java Bean、具有 Getters 和 Setters 的 Bean、Avro Records、Protocol buffers 和 AutoValue 类。
您只需添加带有适当 SchemaProvider
的 DefaultSchema
注释 ( see the SchemaProvider javadoc and discover subclasses there )。
此注释适用于 AutoValue 构建器,因此如果您使用 AutoValue.Builder 模式,则无需执行其他操作!
如果您使用 create
函数(如本例所示),则可以添加 SchemaCreate
注释,如下所示:
import org.apache.beam.sdk.schemas.AutoValueSchema;
import org.apache.beam.sdk.schemas.annotations.DefaultSchema;
import org.apache.beam.sdk.schemas.annotations.SchemaCreate;
@DefaultSchema(AutoValueSchema.class)
@AutoValue
public abstract class MyPersonClass {
public abstract String getName();
public abstract Integer getAge();
public abstract Float getHeight();
@SchemaCreate
public static MyPersonClass create(String name, Integer age, Float height) {
return new AutoValue_MyPersonClass(name, age, height);
}
}
最后,如果您无法自己修改该类(可能是因为您不拥有源代码) 包含 AutoValue 类的代码),您可以手动注册它,如下所示:
pipeline.getSchemaRegistry().registerSchemaProvider(
MyPersonClass.class, new AutoValueSchema());
关于java - 如何在 Apache Beam 中为我的 PCollection 使用 AutoValue 数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62546191/