How to count elements per window

2019-08-12 13:48发布

I'm trying to solve what seems to be easy problem -- count how many elements there are in a PCollection per window. I need it to pass to .withSharding() function on write, to create as many shards as there are going to be files to write.

I tried to do:

FileIO.writeDynamic<Long, E>()
    .withDestinationCoder(AvroCoder.of(Long::class.java))
    .by { e -> e.key }
    .via(Contextful.fn(MySerFunction()))
    .withNaming({ key -> MyFileNaming() })
    .withSharding(ShardingFn())
    .to("gs://some-output")

class ShardingFn : PTransform<PCollection<E>>, PCollectionView<Int>>() {
    override fun expand(input: PCollection<E>): PCollectionView<Int> {

        val keys: PCollection<Long> = input.apply(Keys.create())

        // This only works with GlobalWindowing, how to count per window?
        val count: PCollection<Long> = keys.apply(Count.globally())

        val int: PCollection<Int> = count.apply(MapElements.via(Long2Int))
        return int.apply(View.asSingleton())
    }

However, this works only as long as I have global windowing (aka "batch mode"), otherwise Count.globally() will throw an exception.

Maybe I'm doing it wrong for writing, but if I ever want to count elements per window for some other reason, how to do that?

2条回答
叼着烟拽天下
2楼-- · 2019-08-12 14:40

Using Combine.globally(Count.<T>combineFn()).withoutDefaults() instead of Count.globally() should work in your case. This can also be found in the Javadoc: https://beam.apache.org/documentation/sdks/javadoc/2.5.0/org/apache/beam/sdk/transforms/Count.html#globally--

查看更多
forever°为你锁心
3楼-- · 2019-08-12 14:43

To count the data per window you have to use the timestamps (add one if there are none in the data) and then count them. I recommend to review this example as it explains in details how to do so.

查看更多
登录 后发表回答