Apache Beam 基于 Schema 的 CoGroup 等值连接:多 PCollection 关联的完整实战指南
Apache Beam 基于 Schema 的 CoGroup 等值连接:多 PCollection 关联的完整实战指南
本篇技术指南聚焦 Apache Beam 中面向 Schema PCollection 的多路等值连接变换 CoGroup。它让你无需手工构造 KV 键值对,直接按字段名把两个乃至多个带 Schema 的 PCollection 关联起来,并可以像 SQL 一样表达内连接、左/右/全外连接语义。读完本文,你将掌握 CoGroup 的核心 API(By.fieldNames、withOptionalParticipation、crossProductJoin、withKeyField 等)、输出 Row 的结构、底层基于 CoGroupByKey 的实现原理,以及如何在 Tour of Beam 的 Playground 中完成实战练习。
CoGroup 是什么:为 Schema PCollection 而生的等值连接
CoGroup 与经典的 CoGroupByKey 在语义上相似,但它的输入是带 Schema 的 PCollection,因此用户只需直接指定参与连接的字段名,而不必先把每条元素转换成 KV<key, value> 形式。这是它区别于传统 Join 的根本点:连接键由 Schema 字段声明,而非由用户手工编码。
CoGroup 的完整定义位于 sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/CoGroup.java,其 Javadoc 明确说明了输出形态:
- 输出类型是
Row; - 该 Row 包含一个 key 字段(ROW 类型),存放所有输入共享的连接键;
- 每个输入 PCollection 对应一个 ITERABLE 字段,存放按该 key 关联上的所有行;
- 默认情况下不展开笛卡尔积,但可以通过
crossProductJoin()可选地展开; - 默认 key 字段名为
"key"(可用withKeyField覆盖),且位于索引 0; PCollectionTuple中的 tag 名称决定了输出 Row 中各值字段的名称。
基础示例:三路连接
下面的代码将三个 PCollection 按 "user" 和 "country" 两个字段同时关联:
PCollection<Row> input = PCollectionTuple
.of("input1", input1, "input2", input2, "input3", input3)
.apply(CoGroup.join(By.fieldNames("user", "country")));
此时 key 的 Schema 会包含 "user" 和 "country" 两个字符串字段,且要求 input1/input2/input3 的 Schema 中都存在同名的这两个字段。输出 Row 中除 key 外,还有分别名为 "input1"、"input2"、"input3" 的三个 Iterable<Row> 字段,各自装载在该 key 上关联到的全部输入行。
从源码结构看,这条命令链等价于:先为每个输入执行一次 extractKey(用 RowSelector 按 FieldAccessDescriptor 抽取连接键,产出 KV<Row, Row>),再把它们汇入 KeyedPCollectionTuple 并统一走 CoGroupByKey,最后用 ConvertCoGbkResult DoFn 把 CoGbkResult 转成上述 Row 形态(见 CoGroup.java 中的 JoinInformation.from 与 Impl.expand)。用 Javadoc 的 POJO 类比,未展开的输出可视为:
@DefaultSchema(JavaFieldSchema.class)
public class JoinedValue {
public JoinedKey key;
public Iterable<Input1Type> input1; // 该 key 下 input1 的全部关联行
public Iterable<Input2Type> input2;
public Iterable<Input3Type> input3;
}
按不同字段连接(JOIN DIFFERENT FIELDS)
实际数据中,两个输入的连接字段往往名称不同(如一个叫 referringUser,一个叫 user)。CoGroup 支持这种场景——只要字段类型匹配即可。此时必须为每个输入 PCollection 显式指定各自的连接字段。
例如,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")));
这里先通过 CoGroup.join(tag, By...) 为第一个 tag 指定字段,再用链式 .join(tag, By...) 为第二个 tag 指定字段。单元测试 testCoGroupByDifferentFields 在 CoGroupTest.java 中验证了这类场景:三个输入的连接字段分别名为 user、user2、user3,字段类型均为 String,即可正常关联。
需要注意两个使用约束(来自 CoGroup.java 的 verify 与 Impl.join):
- 一旦使用按 tag 指定字段的方式,每个输入 tag 都必须配置连接字段,且指定的 tag 集合必须与
PCollectionTuple的 tag 完全一致,否则抛出IllegalArgumentException; - 全局 join 与按 tag join 不能混用——若先调用了
CoGroup.join(By.fieldNames(...))再调用join(tag, By...),会抛出IllegalStateException("Cannot set both a global and per-tag fields.")。
在 key Schema 的合并上,源码会保留用户指定的字段顺序,并以第一个输入 PCollection 中的字段名为准;当不同输入的 key 字段类型不一致时,通过 SchemaUtils.mergeWideningNullable 做可空化加宽合并,保证 key 结构统一(见 JoinInformation.from)。
支持四种 SQL 连接语义
默认(不带 crossProductJoin())时,CoGroup 输出每个 key 下一组未展开的 Iterable,标准的 SQL 连接需要通过展开各 Iterable 的笛卡尔积来得到逐行组合。CoGroup 用 crossProductJoin() 直接提供这一能力,并配合 By.withOptionalParticipation() 实现外连接语义。
withOptionalParticipation() 的含义:默认所有输入都必须“完整参与”连接(内连接语义)——只要某个输入在某个 key 上没有值,该 key 就不会产出任何结果;而一旦标记为可选参与,只要至少一个输入在该 key 上有值,就会产出结果,缺失输入的对应位置以 null 填充。Javadoc 强调这一设置只影响 expandCrossProduct 的结果(即 crossProductJoin() 的展开过程)。
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());
两个输入均未标记可选参与,只有两边都有对应 key 的行才会组合输出。展开后的输出 Schema 中,每个输入对应一个 ROW 字段(名为该输入的 tag);随后可以用 Select.flattenedSchema() 把各输入的所有子字段扁平化到一个顶层 Row 中,再配合 Select 选取感兴趣字段(因为 key 字段在 input1 与 input2 中是重复的),详见 CoGroup.java 的 Javadoc。
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());
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());
两个输入都可选参与:只要任一输入存在该 key,就会输出组合,缺失方以 null 填充。
Javadoc 特别提醒:虽然上面的示例用两个输入模拟 SQL 的左/右外连接,但 CoGroup 支持任意数量的输入,withOptionalParticipation 可以施加在任意子集上。同时需要警惕:笛卡尔积连接虽然更简单易写,但可能引发严重的性能问题(行数会按各输入命中数相乘增长),生产环境要评估数据规模。
从源码看,展开逻辑在 Result.outputExpandedRows → crossProduct → crossProductHelper 中实现:对每个 tag 的 Iterable 逐层递归组合,在底层一次性输出累计完成的 Row(见 CoGroup.java)。空 Iterable 且带 withOptionalParticipation 的输入会被替换为「单个 null 元素」参与展开(extractIterables 中的 NULL_LIST)。此外,展开时若检测到「所有主输入均为可选参与且同时存在 side input」,会抛出校验异常——因为此时所有输入都可能缺失,无法确定展开基准(verifyExpandedArgs)。
完整 API 速览
CoGroup 的对外 API 全部位于 CoGroup.java:
| API | 说明 |
|---|---|
CoGroup.join(By clause) |
全局 join:所有输入共用同一组连接字段与选项 |
CoGroup.join(String tag, By clause) |
按 tag join:为该输入单独指定连接字段/选项,可链式调用 |
By.fieldNames(String...) |
按字段名指定连接键 |
By.fieldIds(Integer...) |
按字段 ID(Schema 中的字段顺序索引)指定连接键 |
By.fieldAccessDescriptor(FieldAccessDescriptor) |
用 FieldAccessDescriptor 精确描述要访问的字段(可含嵌套字段) |
By.withOptionalParticipation() |
该输入可选参与,实现外连接语义(缺失以 null 补齐) |
By.withSideInput() |
将该输入作为 side input 参与 join(内部经 View.asMultimap 构建 PCollectionView,见 JoinInformation.from) |
Impl.withKeyField(String) |
自定义输出 key 字段名(默认 "key",索引 0) |
Impl.crossProductJoin() |
展开为逐行笛卡尔积连接,返回 ExpandCrossProduct(其上也支持链式 join(tag, By...)) |
Playground 实战:多表游戏统计
本小节内容对应 co-group/description.md 中的练习,完整可运行代码见 co-group/java-example/Task.java。这是一个 ADVANCED 复杂度的 Java 示例(见 unit-info.yaml)。
示例业务背景:从 gs://apache-beam-samples/game/small/gaming_data.csv 读取游戏数据,解析出 User(userId、userName)与 Game(userId、score、gameId、date)两类记录,再通过 CoGroup 按 userId 关联,观察特定游戏中的用户统计信息。
示例中先为 POJO 声明 Schema(源码中使用 Schema.builder() 手工构建,并用 setSchema 绑定 POJO 与 Row 的双向转换函数):
Schema userSchema = Schema.builder()
.addStringField("userId")
.addStringField("userName")
.build();
Schema gameSchema = Schema.builder()
.addStringField("userId")
.addInt32Field("score")
.addStringField("gameId")
.addStringField("date")
.build();
PCollection<Row> coGroupPCollection =
PCollectionTuple.of("user", userRows).and("game", gameRows)
.apply(CoGroup.join(CoGroup.By.fieldNames("userId")));
注意这里使用了 PCollectionTuple.of("user", ...).and("game", ...) 追加更多输入;输出 tag 名 "user"、"game" 即为结果 Row 中 Iterable 字段的名字。随后为输出 Row 声明完整 Schema 并设置 RowCoder,再用 ParDo 逐行打印:
Schema totalSchema = Schema.builder()
.addRowField("key", Schema.builder().addStringField("userId").build())
.addArrayField("game", Schema.FieldType.row(gameSchema))
.addArrayField("user", Schema.FieldType.row(userSchema))
.build();
coGroupPCollection
.setRowSchema(totalSchema)
.setCoder(RowCoder.of(totalSchema))
.apply("User flatten row", ParDo.of(new LogOutput<>("Flattened")));
练习任务:组合你自己的类
Playground 练习的核心任务有两个:
其一,添加自己的 POJO 类。 例如新增 UserDetails,加入 firstName 与 lastName 字段,并与既有的 User、Game 一起参与连接:
public static class UserDetails {
public String userId;
public String userFirstName;
public String userLastName;
}
其二,连接超过两张表。 CoGroup 天然支持多输入,只要用 and(...) 继续追加即可:
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")));
注意此处追加的 POJO 输入同样需要具备可被 CoGroup 识别的 Schema(在示例中通过 @DefaultSchema(JavaFieldSchema.class) 与 @SchemaCreate 注解声明,或显式 setSchema),否则连接无法解析字段。
从测试看行为保证
CoGroupTest.java(887 行)覆盖了 CoGroup 的主要行为契约,可作为阅读与验证的入口:
testCoGroupByFieldNames:三路按("user", "country")双字段连接,用PAssert断言每个 key 下的 Iterable 内容(按行集合比较,不关心顺序);testCoGroupByDifferentFields:三路输入使用user/user2/user3不同字段名连接,验证按 tag 指定字段的路径;- 测试中还覆盖了
withSideInput、withOptionalParticipation(左/右/全外连接语义)以及混合 tag 指定等场景。
建议在本地以 ./gradlew :sdks:java:core:test --tests "org.apache.beam.sdk.schemas.transforms.CoGroupTest" 方式运行该测试类(以当前仓库 Gradle 配置为准),即可快速验证上述语义。若要系统学习 Schema 系列的其他变换,可继续阅读 schema-based-transforms 目录 下的 select、filter、convert、group、join 等单元,它们与 CoGroup 同属「基于 Schema 的变换」学习路径。