【问题标题】:How to get the total number of elements in a PCollection<String, String>如何获取 PCollection<String, String> 中的元素总数
【发布时间】:2019-04-21 22:31:54
【问题描述】:

我想在 apache 梁中获取 PCollection&lt;String, String&gt; 中的元素总数。我想存储此计数以供进一步使用。如何编写相同的java代码?

【问题讨论】:

标签: java google-cloud-platform apache-beam


【解决方案1】:

在 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 ...长度。

【讨论】:

  • 嘿,谢谢您的信息,实际上我尝试过,但没有成功。下面是我试过的代码。 PCollectioncomposedProducts;公共静态 PCollection pi; pi = compositionProducts.apply(Count.globally());
  • 假设composedProducts 有元素。如果我希望使用 pi PCollection 获得计数。相同的代码是什么?我想在一个整数变量中得到这个计数..怎么做?
  • 嘿,一个简单的问题,所以如果我需要在 public void run(String[] args) 方法中访问 MyMap 类中的长度(变量)。我该怎么做?
  • 我相信高级别的答案是“你不能”。这是我的想法。在 Apache Beam 代码中,您实际上正在做的是构建一个活动图,当您调用管道运行方法时,这些活动将“随后”执行。将这些语句视为在遇到时执行是不正确的……而是将 p.run() 视为将整个图(包括类的 Java 代码)“发送”到远程服务器,随后将在该服务器执行.
  • 好的..所以我想我无法从其他方法中获得这个计数....因为使用虚拟 vm 来执行图形。如果我们不能得到这个计数,你能告诉我吗?这个 count.globally() 会在什么情况下实际使用?
猜你喜欢
  • 2023-02-03
  • 1970-01-01
  • 2021-12-14
  • 2013-05-27
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多