2

在cassandra中,我有一个列表列类型。我是新来的火花和斯卡拉,并不知道从哪里开始。 在火花我想得到每个值的数量,是否有可能这样做。 下面是数据帧spark中列表值的计数 - 数据帧

+--------------------+------------+ 
|     id|  data| 
+--------------------+------------+ 
|53e5c3b0-8c83-11e...|  [b, c]| 
|508c1160-8c83-11e...|  [a, b]| 
|4d16c0c0-8c83-11e...| [a, b, c]| 
|5774dde0-8c83-11e...|[a, b, c, d]| 
+--------------------+------------+ 

我想输出

+--------------------+------------+ 
| value   |  count | 
+--------------------+------------+ 
|a     |  3  | 
|b     |  4  | 
|c     |  3  | 
|d     |  1  | 
+--------------------+------------+ 

火花版本:1.4

回答

4

在这里你去:

scala> val rdd = sc.parallelize(
    Seq(
    ("53e5c3b0-8c83-11e", Array("b", "c")), 
    ("53e5c3b0-8c83-11e1", Array("a", "b")), 
    ("53e5c3b0-8c83-11e2", Array("a", "b", "c")), 
    ("53e5c3b0-8c83-11e3", Array("a", "b", "c", "d")))) 
// rdd: org.apache.spark.rdd.RDD[(String, Array[String])] = ParallelCollectionRDD[22] at parallelize at <console>:27 

scala> rdd.flatMap(_._2).map((_, 1)).reduceByKey(_ + _) 
// res11: org.apache.spark.rdd.RDD[(String, Int)] = ShuffledRDD[21] at reduceByKey at <console>:30 

scala> rdd.flatMap(_._2).map((_,1)).reduceByKey(_ + _).collect 
// res16: Array[(String, Int)] = Array((a,3), (b,4), (c,3), (d,1)) 

这也是实际上的数据帧API很简单:

scala> val df = rdd.toDF("id", "data") 
// res12: org.apache.spark.sql.DataFrame = ["id": string, "data": array<string>] 

scala> df.select(explode($"data").as("value")).groupBy("value").count.show 
// +-----+-----+ 
// |value|count| 
// +-----+-----+ 
// | d| 1| 
// | c| 3| 
// | b| 4| 
// | a| 3| 
// +-----+-----+ 
2

你需要这样的事情(从Apache Spark Examples):

val textFile = sc.textFile("hdfs://...") 
val counts = textFile 
      .flatMap(line => line.split(" ")) 
      .map(word => (word, 1)) 
      .reduceByKey(_ + _) 

猜测你已经有了配对,.reduceByKey(_ + _)会返回你需要。

您也可以尝试在火花外壳是这样的:

sc.parallelize(Array[Integer](1,1,1,2,2),3).map(x=>(x,1)).reduceByKey(_+_).foreach(println) 
+0

你可以请检查编辑 –

相关问题