有效地计算flink中的属性数量

时间:2018-07-24 08:27:32

标签: scala apache-flink

我正在尝试获取flink的DataSet拥有的属性数量,第一次尝试很简单:

dataset.input
    .map(_.vector.size)
    .reduce((_, b) => b)
    .collect
    .head

然后,看一下Solver的实现,我发现它是这样做的:

// TODO: Faster way to do this?
dataset.map(_.vector.size)
    .reduce((a, b) => b)

但是 TODO 评论说明了一切。

因此,我想到了这个实现:

dataset.first(1)
    .map(_.vector.size)
    .reduce((_, b) => b)
    .collect

是否有更有效的实施方式?

1 个答案:

答案 0 :(得分:2)

最快的是

dataset
  // only forward first vector of each partition
  .mapPartition(in => if (in.hasNext) Seq(in.next) else Seq())
  // move all remaining vectors to a single partition, compute size of the first and forward it
  .mapPartition(in => if (in.hasNext) Seq(in.next.vector.size) else Seq()).setParallelism(1)
  .collect

使用reducegroupReduce的效率较低,因为可能会将数据移动到一台机器上而不先减少数据,并导致每个输入记录的函数调用。 mapPartition每个分区被调用一次,并且仅转发输入迭代器的第一个元素。