apachespark在Scala中嵌套迭代以生成statsrdd

apachespark在Scala中嵌套迭代以生成statsrdd,scala,apache-spark,mapreduce,apache-spark-sql,rdd,Scala,Apache Spark,Mapreduce,Apache Spark Sql,Rdd,我有一个由rowkey=client\u id,campaints=Json数组{campaign\u id:campaign\u name}生成的RDD val clientsRDD = resultRDD.map(ClientRow.parseClientRow) // change RDD of ClientRow objects to a DataFrame val clientsDF = clientsRDD.toDF() // Return the schema of this

我有一个由rowkey=client\u id,campaints=Json数组{campaign\u id:campaign\u name}生成的RDD

val clientsRDD = resultRDD.map(ClientRow.parseClientRow)
// change  RDD of ClientRow  objects to a DataFrame
val clientsDF = clientsRDD.toDF()
// Return the schema of this DataFrame
clientsDF.printSchema()
// print each line DataFrame
clientsDF.collect().foreach(println)
输出:

root
 |-- rowkey: string (nullable = true)
 |-- campaigns: string (nullable = true)

[1,[{"1000":"campaign1"},{"1001":"campaign2"}]]
[2,[{"1002":"campaign3"}]]
我还有一个RDD,里面有来自HBase的所有客户机和活动数据记录

记录

rowkey                 type         body
client_id-campaign_id, record_type, record_text 
我的目标是为每个客户(考虑其所有活动)和每个活动生成统计数据,例如,统计所有客户id记录,按类型分组,统计每个活动记录,按类型分组

client1
records:100, login:20, actions:80

client1 campaign1  
records:70, login:16, actions:50

client1 campaign2
records:30, login:4, actions:30
最后我想写统计数据

使用Scala在Spark中执行此操作的最佳方法是什么?
我是否必须迭代clientsRDD(map?),并为每一行生成不同的RDDs映射记录srdd?

首先,您需要为活动字段定义架构: 这意味着 您可以使用

val schema = StructType(Seq(StructField("rowkey", StringType, true),
StructField("campaigns", StructType(
  StructField("id", StringType, true) ::
    StructField("name", StringType, true) :: Nil
))
))

然后,您可以在“活动”字段中使用
explode
方法使行变平

val df = sqlContext.createDataFrame(clientsRDD, schema)
df.select(col("rowkey"), explode(col("campaigns")).as("campaign")).filter(col("campaign.id") === 1)

首先,您需要为活动字段定义架构: 这意味着 您可以使用

val schema = StructType(Seq(StructField("rowkey", StringType, true),
StructField("campaigns", StructType(
  StructField("id", StringType, true) ::
    StructField("name", StringType, true) :: Nil
))
))

然后,您可以在“活动”字段中使用
explode
方法使行变平

val df = sqlContext.createDataFrame(clientsRDD, schema)
df.select(col("rowkey"), explode(col("campaigns")).as("campaign")).filter(col("campaign.id") === 1)