在 Spark 中对记录中的整数求和

Summing integers across records in Spark

我在 Cloudera QuickStart VM 中使用 Spark 控制台。在下面的示例输出中,您将看到使用代码获得的两列数据:

channel_views.filter(lambda x: "XYZ" == x[1]).take(10)

目标是折叠此数据集,使其仅显示 "XYZ" 的唯一一行以及与 "XYZ" 有关的所有数字的相应总和。我们如何获得它?

示例输出:

[(1038, u'XYZ'),
(415, u'XYZ'),
(100, u'XYZ'),
(597, u'XYZ'),
(786, u'XYZ'),
(163, u'XYZ'),
(884, u'XYZ'),
(345, u'XYZ'),
(534, u'XYZ'),
(947, u'XYZ')]

您需要减少输出,可能最简单的是将 (map) 转换为键值对,然后 reduceByKey,例如:

>>> from operator import add
>>> rdd = sc.parallelize([(1038, u'XYZ'), ...])
>>> (rdd.filter(lambda x: "XYZ" == x[1])
...  .map(lambda x: (x[1], x[0]))
...  .reduceByKey(add).collect())
[('XYZ', 5809)]

或者您可以在 reduce 中定义更复杂的函数:

>>> (rdd.filter(lambda x: "XYZ" == x[1])
...  .reduce(lambda x, y: (x[0]+y[0], x[1]))
(5809, 'XYZ')