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?