如何使用 Apache Beam Python SDK 使用 ParDo 过滤 PCollection 的元素

How do I Filter elements of a PCollection with a ParDo with Apache Beam Python SDK

我有一个 PCollection,我想使用 ParDo 从中过滤掉一些元素。

有什么地方可以找到这方面的例子吗?

在 Apache Beam Python SDK 中,有一个 Filter 转换接收 lambda,并过滤掉所有 return False 的元素。这是一个例子:

filtered_collection = (beam.Create([1, 2, 3, 4, 5])
                       beam.Filter(lambda x: x % 2 == 0))

在这种情况下,filtered_collection 将是包含 24.

PCollection

如果您想将其编码为传递给 ParDo 转换的 DoFn,您可以这样做:

class FilteringDoFn(beam.DoFn):
  def process(self, element):
    if element % 2 == 0:
      yield element
    else:
      return  # Return nothing

你可以像这样应用它:

filtered_collection = (beam.Create([1, 2, 3, 4, 5])
                       beam.ParDo(FilteringDoFn()))

其中,与之前一样,filtered_collection 是包含 24.

PCollection