我正在尝试使用apache-beam创建一个流管道,它读取google pub / sub中的句子并将这些单词写入Bigquery表。
我正在使用0.6.0
apache-beam版本。
根据这些例子,我做了这个:
public class StreamingWordExtract {
/**
* A DoFn that tokenizes lines of text into individual words.
*/
static class ExtractWords extends DoFn<String, String> {
@ProcessElement
public void processElement(ProcessContext c) {
String[] words = ((String) c.element()).split("[^a-zA-Z']+");
for (String word : words) {
if (!word.isEmpty()) {
c.output(word);
}
}
}
}
/**
* A DoFn that uppercases a word.
*/
static class Uppercase extends DoFn<String, String> {
@ProcessElement
public void processElement(ProcessContext c) {
c.output(c.element().toUpperCase());
}
}
/**
* A DoFn that uppercases a word.
*/
static class StringToRowConverter extends DoFn<String, TableRow> {
@ProcessElement
public void processElement(ProcessContext c) {
c.output(new TableRow().set("string_field", c.element()));
}
static TableSchema getSchema() {
return new TableSchema().setFields(new ArrayList<TableFieldSchema>() {
// Compose the list of TableFieldSchema from tableSchema.
{
add(new TableFieldSchema().setName("string_field").setType("STRING"));
}
});
}
}
private interface StreamingWordExtractOptions extends ExampleBigQueryTableOptions, ExamplePubsubTopicOptions {
@Description("Input file to inject to Pub/Sub topic")
@Default.String("gs://dataflow-samples/shakespeare/kinglear.txt")
String getInputFile();
void setInputFile(String value);
}
public static void main(String[] args) {
StreamingWordExtractOptions options = PipelineOptionsFactory.fromArgs(args)
.withValidation()
.as(StreamingWordExtractOptions.class);
options.setBigQuerySchema(StringToRowConverter.getSchema());
Pipeline p = Pipeline.create(options);
String tableSpec = new StringBuilder()
.append(options.getProject()).append(":")
.append(options.getBigQueryDataset()).append(".")
.append(options.getBigQueryTable())
.toString();
p.apply(PubsubIO.read().topic(options.getPubsubTopic()))
.apply(ParDo.of(new ExtractWords()))
.apply(ParDo.of(new StringToRowConverter()))
.apply(BigQueryIO.Write.to(tableSpec)
.withSchema(StringToRowConverter.getSchema())
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));
PipelineResult result = p.run();
}
我附近有错误:
apply(ParDo.of(new ExtractWords()))
因为之前的apply
没有返回String
而是Object
我认为问题是从PubsubIO.read().topic(options.getPubsubTopic())
返回的类型。类型为PTransform<PBegin, PCollection<T>>
,而不是PTransform<PBegin, PCollection<String>>
使用apache-beam从google pub / sub读取的正确方法是什么?
答案 0 :(得分:6)
你最近在Beam中遇到了一个向后兼容的变化 - 对不起!
从Apache Beam版本0.5.0开始,需要使用PubsubIO.Read
和PubsubIO.Write
来实例化PubsubIO.<T>read()
和PubsubIO.<T>write()
,而不是使用{{1}等静态工厂方法}}
PubsubIO.Read.topic(String)
需要通过.withCoder(Coder)
为输出类型指定编码器。 Read
需要为输入类型指定编码器或通过.withAttributes(SimpleFunction<T, PubsubMessage>)
指定格式函数。