Apache Beam 基于 Schema 的多 PCollection 等值连接:CoGroup 变换完整实战指南

原创2026-10-06 16:22:262,341 阅读
文章标签:大数据批处理流处理数据工程后端

Apache Beam 基于 Schema 的多 PCollection 等值连接:CoGroup 变换完整实战指南

Apache Beam 的 CoGroup 是 org.apache.beam.sdk.schemas.transforms 包中面向带 Schema 的 PCollection 的等值连接(equijoin)变换。与传统的 CoGroupByKey 相比,它免去了手动构造 KV<K, V> 的繁琐步骤,只需声明要连接的字段名,即可在任意数量的输入 PCollection 上完成连接,并直接输出结构化的 Row 结果。通过组合 crossProductJoin() 与 withOptionalParticipation(),你可以在 Beam 中原生地表达 SQL 的 inner join、left outer join、right outer join 与 full outer join 四种语义。

本指南以 learning/tour-of-beam/learning-content/schema-based-transforms/co-group/description.md 为骨架,结合 CoGroup.java 的源码实现与其 单元测试,逐层讲解用法、输出结构、源码原理与常见坑。读完你将能够:在 Java SDK 中用 CoGroup 完成多表连接、跨字段连接与四种外连接语义,并理解其底层如何复用 CoGroupByKey 与递归展开笛卡尔积。

CoGroup 是什么:与 CoGroupByKey 的差异与输出结构

CoGroup 是执行跨多个带 Schema 的 PCollection 的等值连接的变换(见 CoGroup.java 类注释)。它与 CoGroupByKey(位于 sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/join/CoGroupByKey.java)功能相似,但面向的是已经声明了 Schema 的 PCollection,因此使用者只需简单指定要连接的 Schema 字段,而不必先做 MapElements/WithKeys 之类的键抽取。

CoGroup 的输出类型是 Row,其结构为:

  • 一个 key 行字段:包含所有连接键字段;
  • 每个输入对应一个 ITERABLE 字段:包含在该 key 上成功连接的所有行。

默认情况下不展开笛卡尔积(cross product),但可以通过 crossProductJoin() 选择展开。默认 key 字段名为 "key"(可用 withKeyField 覆盖),且索引为 0;PCollectionTuple 中的 tag 则决定了输出 Row 中各值字段的名称。

举例来说,对三个 PCollection 在 "user" 与 "country" 两个字段上连接:

PCollection<Row> joined =
    PCollectionTuple.of("input1", input1, "input2", input2, "input3", input3)
        .apply(CoGroup.join(By.fieldNames("user", "country")));

此时输出 schema 中的 key 字段包含字符串字段 user 与 country,前提是 input1/input2/input3 的 Schema 都必须存在同名同类型的 user 与 country 字段;Row 的其余部分则是名为 "input1"、"input2"、"input3" 的三个 Iterable<Row> 字段(源码注释)。

从源码结构看(Result.getUnexandedOutputSchema),未展开模式的输出 schema 由 key 行字段加每个输入的 Iterable 字段构成;而在展开模式下(getExpandedOutputSchema),输出是一行中并列的多个 ROW 字段,且标记了可选参与的输入字段会被声明为 nullable。

为了便于理解,未展开的输出可以类比为如下 POJO(源自 源码注释):

@DefaultSchema(JavaFieldSchema.class)
public class JoinedValue {
  public JoinedKey key;
  // 以下列表包含三个输入中与给定 key 匹配的全部行
  public Iterable<Input1Type> input1;
  public Iterable<Input2Type> input2;
  public Iterable<Input3Type> input3;
}

PCollection<JoinedValue> values = joined.apply(Convert.to(JoinedValue.class));

快速上手:按相同字段连接多个 PCollection

CoGroup.join(By clause) 是最简单的入口:所有输入使用同一组连接字段与选项(join(By clause) 源码)。只要每个输入 PCollection 都含有这些字段,即可一次连接任意多个集合:

PCollection<Row> input1 = ...; // 含 user、country 字段
PCollection<Row> input2 = ...;
PCollection<Row> input3 = ...;

PCollection<Row> joined =
    PCollectionTuple.of("input1", input1, "input2", input2, "input3", input3)
        .apply(CoGroup.join(By.fieldNames("user", "country")));

关于 By(连接参数描述符),源码提供了三种构造方式(CoGroup.java L241-L258):

静态工厂 说明
By.fieldNames(String...) 按字段名连接,最常用
By.fieldIds(Integer...) 按字段 ID(索引)连接
By.fieldAccessDescriptor(FieldAccessDescriptor) 直接传入字段访问描述符,底层实现均收敛于此

在底层,JoinInformation.from 会对每个 tag 解析其字段访问描述符(源码):key schema 按用户指定的字段顺序生成,并利用 SchemaUtils.mergeWideningNullable 将各输入的 key schema 合并(必要时放宽为 nullable),从而保证即使各输入字段类型存在可空性差异也能对齐。随后 extractKey 用一个 RowSelector 从每一行中抽取连接键,产出 KV<Row, Row>(extractKey 实现),为后续交给 CoGroupByKey 做好准备。

按不同字段连接:为每个输入单独指定连接字段

当两个输入要连接的字段名不同时,只要字段类型匹配即可连接。此时必须为每一个输入 PCollection 都显式指定连接字段,使用的是 CoGroup.join(String tag, By clause)(源码 L328-L330)以及 Impl.join(String tag, By clause) 的链式调用(源码 L726-L731)。

考虑 SQL 语句 SELECT * FROM input1Tag JOIN input2Tag ON input1Tag.referringUser = input2Tag.user,对应写法为:

PCollection<Row> joined =
    PCollectionTuple.of("input1Tag", input1, "input2Tag", input2)
        .apply(CoGroup
            .join("input1Tag", By.fieldNames("referringUser"))
            .join("input2Tag", By.fieldNames("user")));

注意:一旦使用 per-tag 方式指定字段,所有输入都必须给出自己的连接参数;同时不能混用全局 join(By) 与 per-tag join(tag, By),否则会抛出 IllegalStateException("Cannot set both a global and per-tag fields.")(源码 L727-L729)。此外,Impl.expand 的第一步 verify 会严格校验输入 tuple 的 tag 集合与 join 参数中 tag 集合完全一致(verify 实现 L451-L466),不匹配即抛 IllegalArgumentException——这正是测试 testUnmatchedTags 与 testUnderspecifiedCoGroup 所覆盖的约束。

用 crossProductJoin 实现四种 SQL 连接语义

默认的未展开输出不做笛卡尔积展开;而 SQL 连接本质上是笛卡尔积连接(cross-product join)——所有满足连接条件的行会被组合成独立行输出,任意 SQL inner join 都是两张表笛卡尔积的子集(源码注释 L128-L131)。Impl.crossProductJoin()(源码 L734)返回 ExpandCrossProduct 变换,将连接结果展开为与 SQL 一致的行。

外层连接语义由 By.withOptionalParticipation()(源码 L260-L268)控制:默认所有输入必须完全参与连接(inner 语义)——只要有一个输入没有某 key 的值,该 key 就不产生结果;而标记为可选参与的输入,在缺失该 key 时以 null 填充,只要至少一个输入有值即可产生结果。下面逐一对照 SQL 写法。

Inner Join(内连接)

SQL:SELECT * FROM input1 INNER JOIN input2 ON input1.user = input2.user

PCollection<Row> joined =
    PCollectionTuple.of("input1", input1, "input2", input2)
        .apply(CoGroup.join(By.fieldNames("user")).crossProductJoin());

(原文档示例代码此处有括号不完整的问题,上面是修复后的完整可运行形式。)输出 schema 中为 input1 与 input2 各含一个嵌套 ROW 字段,可继续用 Convert.to(...) 转成 POJO:

@DefaultSchema(JavaFieldSchema.class)
public class JoinedValue {
  public Input1Type input1;
  public Input2Type input2;
}

随后还可以配合 Select.flattenedSchema() 将所有子字段拍平为单个顶层 Row,并结合 Select 挑选目标字段(key 字段在 input1、input2 中相同,通常会被去重选择)(源码注释 L143-L157)。

Left Outer Join(左外连接)

SQL:SELECT * FROM input1 LEFT OUTER JOIN input2 ON input1.user = input2.user

PCollection<Row> joined =
    PCollectionTuple.of("input1", input1, "input2", input2)
        .apply(CoGroup.join("input1", By.fieldNames("user").withOptionalParticipation())
                      .join("input2", By.fieldNames("user"))
                      .crossProductJoin());

input1 标记为可选参与,意味着即使 input2 中缺少某用户,input1 的行仍会保留,input2 侧以 null 填充。

Right Outer Join(右外连接)

SQL:SELECT * FROM input1 RIGHT OUTER JOIN input2 ON input1.user = input2.user

PCollection<Row> joined =
    PCollectionTuple.of("input1", input1, "input2", input2)
        .apply(CoGroup.join("input1", By.fieldNames("user"))
                      .join("input2", By.fieldNames("user").withOptionalParticipation())
                      .crossProductJoin());

与左外连接对称:input2 可选参与。

Full Outer Join(全外连接)

SQL:SELECT * FROM input1 FULL OUTER JOIN input2 ON input1.user = input2.user

PCollection<Row> joined =
    PCollectionTuple.of("input1", input1, "input2", input2)
        .apply(CoGroup.join("input1", By.fieldNames("user").withOptionalParticipation())
                      .join("input2", By.fieldNames("user").withOptionalParticipation())
                      .crossProductJoin());

两个输入都标记为可选参与。需要强调的是:上述示例虽然用两个输入模拟 SQL 的左/右连接,但 CoGroup 支持任意数量的输入,且可选参与可以施加在任意子集上(源码注释 L200-L202)。

展开模式的源码实现

展开模式的输出 schema(getExpandedOutputSchema L568-L581)为每个输入各建一个 ROW 字段,可选参与的字段声明为 nullable。当某个输入在 key 上无匹配行且该输入可选参与时,extractIterables 会将其替换为包含单个 null 的迭代器(源码 L589-L603,对应类级静态常量 NULL_LIST)。随后 crossProduct 以递归方式逐层展开各输入的 iterable,在到达最底层时输出累积的完整行(crossProduct/crossProductHelper L605-L638)。

另外注意 verifyExpandedArgs 的一条限制:当所有主输入都是可选参与且存在 side input 时,展开连接会直接报错——因为此时连主输入都可能为空,side input 无从合并,测试 testIllegalOuterJoinWithSideInput 正是验证这一约束。

自定义与性能:withKeyField、withSideInput 与笛卡尔积风险

  • withKeyField(String):默认连接键字段名为 "key" 且位于索引 0,可用 Impl.withKeyField(...) 覆盖(源码 L717-L719)。在未展开输出 schema 中,key 字段通过 addRowField(keyFieldName, keySchema) 构建(L535-L542)。
  • By.withSideInput():将某个输入标记为 side input(源码 L270-L272)。在 JoinInformation.from 中,side input 输入不会进入 KeyedPCollectionTuple,而是通过 View.asMultimap() 构建 PCollectionView<Map<Row, Iterable<Row>>>,在 Result.from 中按 key 查询(源码 L412-L417、L518-L531)。
  • 性能警示:类注释明确提醒,笛卡尔积连接虽然更简单易写,但可能引发性能问题(源码注释 L204)。当某个 key 下匹配行较多时,展开后的行数是各输入匹配数的乘积,可能急剧膨胀,请根据业务数据量谨慎选择展开模式。

Playground 练习:合并多张表与自定义用户类

在 tour-of-beam 的 schema-based-transforms 模块中,co-group 单元被标记为 ADVANCED 难度(见 unit-info.yaml)。Playground 窗口中内置了使用 CoGroup 的示例:读取 gs://apache-beam-samples/game/small/gaming_data.csv 游戏数据,将用户信息与游戏战绩按 userId 连接,观察不同游戏中的用户统计。

练习任务的第一步是组合多个类,并新增自己的 UserDetails 类,携带 firstName 与 lastName 字段:

public static class UserDetails {
    public String userId;
    public String userFirstName;
    public String userLastName;
}

第二步是连接多于两张表:把用户信息、游戏信息与新加的详情表一起放入 PCollectionTuple,统一按 userId 连接:

PCollection<UserDetails> details =
    pipeline.apply(Create.of(new UserDetails("userId", "first", "last")));

PCollection<Row> coGroupPCollection =
    PCollectionTuple.of("user", userInfo).and("game", gameInfo).and("details", details)
        .apply(CoGroup.join(CoGroup.By.fieldNames("userId")));

完整的可运行参考实现位于 co-group/java-example/Task.java,其核心流程是:

  1. 用 @DefaultSchema(JavaFieldSchema.class) 定义 User(userId、userName)与 Game(userId、score、gameId、date)POJO,并通过 @SchemaCreate 标注构造器;
  2. 分别用 Schema.builder() 构建 userSchema、gameSchema,以及包含 key 行字段与 game/user 数组字段的 totalSchema;
  3. 通过 setSchema(...) 把 POJO 集合绑定 Schema 并转换为 Row;
  4. PCollectionTuple.of("user", userRows).and("game", gameRows).apply(CoGroup.join(CoGroup.By.fieldNames("userId"))) 完成连接;
  5. 最后 setRowSchema(totalSchema) 并注册 RowCoder,用 ParDo 打印展开后的行。

对应输出结构即:key(内含 userId)+ game 数组 + user 数组——这正是未展开模式下 key 字段 + 每个 tag 一个 ITERABLE 字段的直观体现。

测试佐证:行为边界一览

CoGroupTest.java 是验证上述语义的权威参考,关键用例包括:

  • testCoGroupByFieldNames(L108):同名字段多输入连接的基础行为;
  • testCoGroupByDifferentFields(L254):不同字段名连接;
  • testInnerJoin(L525)、testFullOuterJoin(L594)、testPartialOuterJoin(L683):三种连接语义与展开输出;
  • testIllegalOuterJoinWithSideInput(L440):全可选主输入 + side input 的非法组合;
  • testUnderspecifiedCoGroup(L473)、testUnmatchedTags(L791):join 参数与输入 tag 不匹配/缺失字段时的校验;
  • testMismatchingKeys(L501):key 类型不匹配等场景。

这些测试与 description.md 的示例一一对应,可作为你自测代码行为的对照基准。

小结

CoGroup 是 Apache Beam Java SDK 中面向 Schema 体系的连接利器:CoGroup.join(By.fieldNames(...)) 负责多输入同字段等值连接,join(tag, By) 链支持跨字段连接,crossProductJoin() + withOptionalParticipation() 组合可精确复现 SQL 的 inner/left/right/full outer join 四种语义,withKeyField 与 withSideInput 进一步提供了输出定制与 side-input 优化手段。其底层实现(extractKey → CoGroupByKey → ConvertCoGbkResult/递归 crossProduct)清晰展示了 Beam 如何把「Schema 字段声明」翻译为经典的 GroupByKey 连接过程。在实际使用时,请务必结合数据规模评估笛卡尔积展开的膨胀风险,并用 CoGroupTest.java 中的边界用例校准你的预期。

登录后查看全文
beam