![](/img/trans.png)
[英]How to convert PCollection<TableRow> to PCollection<Row> in Apache Beam?
[英]How to create PCollection<Row> from PCollection<String> for performing beam SQL Trasforms
我正在嘗試實現一個數據管道,它連接來自 Kafka 主題的多個無界源。 我能夠連接到主題並將數據作為PCollection<String>
,我需要將其轉換為PCollection<Row>
。 我將逗號分隔的字符串拆分為一個數組,並使用模式將其轉換為 Row。 但是,如何實現/構建模式並將值動態綁定到它?
即使我為架構構建創建了一個單獨的類,有沒有辦法將字符串數組直接綁定到架構?
下面是我當前的工作代碼,它是靜態的,每次構建管道時都需要重寫,並且它也會根據字段的數量進行延長。
final Schema sch1 =
Schema.builder().addStringField("name").addInt32Field("age").build();
PCollection<KafkaRecord<Long, String>> kafkaDataIn1 = pipeline
.apply(
KafkaIO.<Long, String>read()
.withBootstrapServers("localhost:9092")
.withTopic("testin1")
.withKeyDeserializer(LongDeserializer.class)
.withValueDeserializer(StringDeserializer.class)
.updateConsumerProperties(
ImmutableMap.of("group.id", (Object)"test1")));
PCollection<Row> Input1 = kafkaDataIn1.apply(
ParDo.of(new DoFn<KafkaRecord<Long, String>, Row>() {
@ProcessElement
public void processElement(
ProcessContext processContext,
final OutputReceiver<Row> emitter) {
KafkaRecord<Long, String> record = processContext.element();
final String input = record.getKV().getValue();
final String[] parts = input.split(",");
emitter.output(
Row.withSchema(sch1)
.addValues(
parts[0],
Integer.parseInt(parts[1])).build());
}}))
.apply("window",
Window.<Row>into(FixedWindows.of(Duration.standardSeconds(50)))
.triggering(AfterWatermark.pastEndOfWindow())
.withAllowedLateness(Duration.ZERO)
.accumulatingFiredPanes());
Input1.setRowSchema(sch1);
我的期望是以動態/可重用的方式實現與上述代碼相同的事情。
模式設置在 pcollection 上,因此它不是動態的,如果您想懶惰地構建它,那么您需要使用支持它的格式/編碼器。 Java 序列化或 json 就是例子。
據說要從 sql 功能中受益,您還可以使用帶有查詢字段和其他字段的靜態模式,這樣靜態部分可以執行 sql 並且不會丟失額外的數據。
羅曼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.