如何在 Apache Beam 中为我的 PCollection 使用 AutoValue 数据类型?

How do I use an AutoValue data type for my PCollection in Apache Beam?

我想在我的 PCollection 中使用我的 AutoValue 数据 classes 作为对象类型,但是我在使用自动编码器时遇到了问题:

@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 class 的架构?还是可以自动推断出不同的编码器?

Beam 有一个实用程序可以自动推断不同数据的模式 classes,包括 Java Beans、具有 Getters 和 Setters 的 Beans、Avro 记录、协议缓冲区和 AutoValue class es.

您只需添加带有适当 SchemaProvider (see the SchemaProvider javadoc and discover subclasses there) 的 DefaultSchema 注释。

此注释适用于 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);
  }
}

最后,如果您不能自己修改 class(可能是因为您不拥有源代码 包含AutoValue class)的代码,您可以手动注册如下:

pipeline.getSchemaRegistry().registerSchemaProvider(
    MyPersonClass.class, new AutoValueSchema());

接受的答案非常好。

我的 2 美分,在 AutoValueSchema 中存在一个约束,ReflectionUtils#isGtter,它期望 AutoValue 的字段遵循 get* 约定。 如果您遵循将 getter 命名为 field() 而不是 getField() 的约定,AutoValueSchema 不会将它们注册为实际的 getter 方法,因此不会作为 属性 用于模式创建。 (最后一点对我来说有点模糊,因为我不确定通过 getter 识别 属性 的完整流程,必须更详细地阅读源代码)。

因此,截至目前,您必须将所有 AutoValue getter 命名为 get*() 才能使其与 Beam 的 AutoValueSchema 正确配合使用。

有关详细信息,请参阅:https://github.com/apache/beam/pull/7334 and https://github.com/apache/beam/pull/7334#issuecomment-453560743