2017-06-06 4 views
1

私はScalaの2.11スパーク2.0.1を使用して、この質問は、下記thisスパーク - 空のMapのnamed_struct

に関連しているが、セットアップで:

val ss = new StructType().add("x", IntegerType).add("y", MapType(DoubleType, IntegerType)) 

val s = new StructType() 
    .add("a", IntegerType) 
    .add("b", ss) 

val d = Seq(Row(1, Row(1,Map(1.0->1, 2.0->2))), 
    Row(2, Row(2,Map(2.0->2, 3.0->3))), 
    Row(3, null), 
    Row(4, Row(4, Map()))) 

val rd = sc.parallelize(d) 
val df = spark.createDataFrame(rd, s) 

df.select($"a", $"b").show(false) 

// +---+---------------------------+ 
// |a |b       | 
// +---+---------------------------+ 
// |1 |[1,Map(1.0 -> 1, 2.0 -> 2)]| 
// |2 |[2,Map(2.0 -> 2, 3.0 -> 3)]| 
// |3 |null      | 
// |4 |[4,Map()]     | 
// +---+---------------------------+ 
// 

私が持っている場合は、以下の文が機能します

df.groupBy($"a").pivot("a"). 
    agg(expr("first(coalesce(b, named_struct('x', cast(null as Int), 'y', Map(0.0D, 0))))")) 
    .show(false) 

// +---+---------------------------+---------------------------+--------------------+---------+ 
// |a |1       |2       |3     |4  | 
// +---+---------------------------+---------------------------+--------------------+---------+ 
// |1 |[1,Map(1.0 -> 1, 2.0 -> 2)]|null      |null    |null  | 
// |3 |null      |null      |[null,Map(0.0 -> 0)]|null  | 
// |4 |null      |null      |null    |[4,Map()]| 
// |2 |null      |[2,Map(2.0 -> 2, 3.0 -> 3)]|null    |null  | 
// +---+---------------------------+---------------------------+--------------------+---------+ 

しかし、どのように空の0を作成するには、​​3210にデフォルト(行2 COL 3細胞は、デフォルト値を有する)を提供します(a=4のようなもの)はnamed_structまたはそれ以外を使用していますか?

答えて

1

あなたはケースクラスとUDFでこれを達成することができます答えを

case class MyStruct(x:Option[Int], y:Map[Double,Int]) 

import org.apache.spark.sql.functions.{udf, first,coalesce} 

val emptyStruct = udf(() => MyStruct(None,Map.empty[Double,Int])) 

df.groupBy($"a").pivot("a") 
    .agg(first(coalesce($"b",emptyStruct()))) 
    .show(false) 
+0

感謝を! Sparkには同じことをするためのこれらのさまざまな方法がありますが、小さな調整(例:IntではなくMap) – mrbrahman

関連する問題