【问题标题】:spark-scala Efficient way to count at each group levelspark-scala 在每个组级别进行计数的有效方法
【发布时间】:2015-08-07 05:15:00
【问题描述】:

我有关注 rdd

(000740C7AD5274,8884165739991289,0)
(000740C7AD5274,5247914560952402,1)
(000740C7AD5274,6366183814312296,0)
(000740C7AD5274,8416039242203850,1)
(000740C7AD5274,8767784019249585,0)
(000740C7AD5274,8875366436847528,0)
(000740C7AD5274,6878583261589229,0)
(000740C7AD5274,7480419089929113,1)
(000740C7AD5274,7480419089929113,0)
(000740C7AD5274,8848143710281107,0)
(000740C7AD5274,7617664942496492,1)
(000740C7AD5274,4905980213247549,0)
(000740C7AD5274,6806506896473929,1)

这是代表 userId、productId、BuyorNot 信息。我想从这些数据中生成一组统计数据,例如。每个用户购买的商品数量和每个产品的用户数量。

我是这样开始的:

val userProduct = userProductRDD.groupBy(x => (x._1, x._2)).flatMap(k => (k._1, if (k._2._3) != 0) 1 else 0))

但这并没有给(userId, distinct_bought_count) 一些指导将有助于前进。

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    简单地说:

    val userProducts: RDD[(String, Long)] = 
      userProductRDD.filter(_._3 == 1)                 // buys only
                    .map { case (u, p, _, _) => (u, p) } // drop buys and price
                    .distinct                          // keep distinct (user, product)
                    .map { case (u, _) => (u, 1L) }    // word count problem
                    .reduceByKey(_ + _)
    
    // similarly
    val productUsers: RDD[(Long, Long)] =
      userProductRDD.filter(_._3 == 1)
                    .map { case (u, p, _, _) => (p, u) }
                    .distinct
                    .map { case (p, _) => (p, 1L) }
                    .reduceByKey(_ + _)
    

    【讨论】:

    • 我错过的小事,如果我在第三个值之后有更多元素,例如000740C7AD5274,8884165739991289,0,price,我需要更改什么?
    • 因为我收到以下错误:` found : (T1, T2, T3, T4) required: (String, String, Int, String, String)`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2018-07-09
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    相关资源
    最近更新 更多