我想在apache梁中获得PCollection<String, String>
中元素的总数。我想存储此计数以供进一步使用。如何编写相同的java代码?
在Apache Beam中有一个名为Count的转换(JavaDoc就是这里的链接)。这有一个名为globally
的方法,它返回一个包含输入PCollection中元素数量的PCollection。您将使用此方法来获取元素的数量。
这是我用来测试的逻辑片段:
private class MyMap extends SimpleFunction < Long, Long > {
public Long apply(Long in ) {
System.out.println("Length is: " + in );
return in;
}
}
public void run(String[] args) {
PipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().create();
Pipeline p = Pipeline.create(options);
// Create a PCollection from static objects
ArrayList < String > strs = new ArrayList < > ();
strs.add("Neil");
strs.add("John");
strs.add("Bob");
PCollection < String > pc1 = p.apply(Create.of(strs));
PCollection < Long > count = pc1.apply(Count.globally());
count.apply(MapElements.via(new MyMap()));
System.out.println("About to run!");
p.run().waitUntilFinish();
System.out.println("Run complete!");
} // run
运行时,此代码创建一个包含三个字符串的PCollection。然后我应用Count.globally()
变换,最后一个Map来记录新的PCollection,其中包含一个元素......长度。