Spark:scala rdd中的group concat等价物

时间:2015-12-08 07:47:36

标签: scala apache-spark group-concat rdd spark-dataframe

我有以下DataFrame:

    |-----id-------|----value------|-----desc------|
    |     1        |     v1        |      d1       |
    |     1        |     v2        |      d2       |
    |     2        |     v21       |      d21      |
    |     2        |     v22       |      d22      |
    |--------------|---------------|---------------|

我想将其转换为:

    |-----id-------|----value------|-----desc------|
    |     1        |     v1;v2     |      d1;d2    |
    |     2        |     v21;v22   |      d21;d22  |
    |--------------|---------------|---------------|
  • 是否可以通过数据框操作?
  • 在这种情况下rdd转换怎么样?

我认为rdd.reduce是关键,但我不知道如何使其适应这种情况。

4 个答案:

答案 0 :(得分:8)

您可以使用spark sql转换数据

realm.write {
    let storageArea = …
    let sortedProducts = Array(storageArea.products.sorted("name"))
    storageArea.products.removeAll()
    storageArea.products.appendContentsOf(sortedProducts)
}

答案 1 :(得分:1)

假设您有类似

的内容
import scala.util.Random

val sqlc: SQLContext = ???

case class Record(id: Long, value: String, desc: String)

val testData = for {
    (i, j) <- List.fill(30)(Random.nextInt(5), Random.nextInt(5))
  } yield Record(i, s"v$i$j", s"d$i$j")

val df = sqlc.createDataFrame(testData)

您可以轻松地将数据加入:

import sqlc.implicits._

def aggConcat(col: String) = df
      .map(row => (row.getAs[Long]("id"), row.getAs[String](col)))
      .aggregateByKey(Vector[String]())(_ :+ _, _ ++ _)

val result = aggConcat("value").zip(aggConcat("desc")).map{
      case ((id, value), (_, desc)) => (id, value, desc)
    }.toDF("id", "values", "descs") 

如果您想要连接字符串而不是数组,可以稍后运行

import org.apache.spark.sql.functions._

val resultConcat =  result
      .withColumn("values", concat_ws(";", $"values"))
      .withColumn("descs" , concat_ws(";", $"descs" ))

答案 2 :(得分:1)

如果使用DataFrames,请使用UDAF

import org.apache.spark.sql.Row
import org.apache.spark.sql.expressions.{MutableAggregationBuffer, UserDefinedAggregateFunction}
import org.apache.spark.sql.types.{DataType, StringType, StructField, StructType}

class ConcatStringsUDAF(InputColumnName: String, sep:String = ",") extends UserDefinedAggregateFunction {
  def inputSchema: StructType = StructType(StructField(InputColumnName, StringType) :: Nil)
  def bufferSchema: StructType = StructType(StructField("concatString", StringType) :: Nil)
  def dataType: DataType = StringType
  def deterministic: Boolean = true
  def initialize(buffer: MutableAggregationBuffer): Unit = buffer(0) = ""

  private def concatStrings(str1: String, str2: String): String = {
   (str1, str2) match {
      case (s1: String, s2: String) => Seq(s1, s2).filter(_ != "").mkString(sep)
      case (null, s: String) => s
      case (s: String, null) => s
      case _ => ""
    }
  }
  def update(buffer: MutableAggregationBuffer, input: Row): Unit = {
    val acc1 = buffer.getAs[String](0)
    val acc2 = input.getAs[String](0)
    buffer(0) = concatStrings(acc1, acc2)
  }

  def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = {
    val acc1 = buffer1.getAs[String](0)
    val acc2 = buffer2.getAs[String](0)
    buffer1(0) = concatStrings(acc1, acc2)
  }

  def evaluate(buffer: Row): Any = buffer.getAs[String](0)
}

然后用这种方式

val stringConcatener = new ConcatStringsUDAF("Category_ID", ",")
data.groupBy("aaid", "os_country").agg(stringConcatener(data("X")).as("Xs"))

从Spark 1.6开始,看一下Datasets和Aggregator。

答案 3 :(得分:0)

经过一些研究后,我想出了这样的事情:

    val data = sc.parallelize(
    List(
        ("1", "v1", "d1"),
        ("1", "v2", "d2"),
        ("2", "v21", "d21"),
        ("2", "v22", "d22")))
        .map{ case(id, value, desc)=>((id), (value, desc))}
        .reduceByKey((x,y)=>(x._1+";"+y._1, x._2+";"+x._2))
        .map{ case(id,(value, desc))=>(id, value, desc)}.toDF("id", "value","desc")
        .show()

让我:

    +---+-------+-------+
    | id|  value|   desc|
    +---+-------+-------+
    |  1|  v1;v2|  d1;d1|
    |  2|v21;v22|d21;d21|
    +---+-------+-------+