查询具有复杂类型的Spark SQL DataFrame

dvi*_*vir 54 sql scala dataframe apache-spark apache-spark-sql

如何查询具有复杂类型(如地图/数组)的RDD?例如,当我写这个测试代码时:

case class Test(name: String, map: Map[String, String])
val map = Map("hello" -> "world", "hey" -> "there")
val map2 = Map("hello" -> "people", "hey" -> "you")
val rdd = sc.parallelize(Array(Test("first", map), Test("second", map2)))
Run Code Online (Sandbox Code Playgroud)

我虽然语法如下:

sqlContext.sql("SELECT * FROM rdd WHERE map.hello = world")
Run Code Online (Sandbox Code Playgroud)

要么

sqlContext.sql("SELECT * FROM rdd WHERE map[hello] = world")
Run Code Online (Sandbox Code Playgroud)

但我明白了

无法访问MapType类型中的嵌套字段(StringType,StringType,true)

org.apache.spark.sql.catalyst.errors.package $ TreeNodeException:未解析的属性

分别.

zer*_*323 155

它取决于列的类型.让我们从一些虚拟数据开始:

import org.apache.spark.sql.functions.{udf, lit}
import scala.util.Try

case class SubRecord(x: Int)
case class ArrayElement(foo: String, bar: Int, vals: Array[Double])
case class Record(
  an_array: Array[Int], a_map: Map[String, String], 
  a_struct: SubRecord, an_array_of_structs: Array[ArrayElement])


val df = sc.parallelize(Seq(
  Record(Array(1, 2, 3), Map("foo" -> "bar"), SubRecord(1),
         Array(
           ArrayElement("foo", 1, Array(1.0, 2.0, 2.0)),
           ArrayElement("bar", 2, Array(3.0, 4.0, 5.0)))),
  Record(Array(4, 5, 6), Map("foz" -> "baz"), SubRecord(2),
         Array(ArrayElement("foz", 3, Array(5.0, 6.0)), 
               ArrayElement("baz", 4, Array(7.0, 8.0))))
)).toDF
Run Code Online (Sandbox Code Playgroud)
df.registerTempTable("df")
df.printSchema

// root
// |-- an_array: array (nullable = true)
// |    |-- element: integer (containsNull = false)
// |-- a_map: map (nullable = true)
// |    |-- key: string
// |    |-- value: string (valueContainsNull = true)
// |-- a_struct: struct (nullable = true)
// |    |-- x: integer (nullable = false)
// |-- an_array_of_structs: array (nullable = true)
// |    |-- element: struct (containsNull = true)
// |    |    |-- foo: string (nullable = true)
// |    |    |-- bar: integer (nullable = false)
// |    |    |-- vals: array (nullable = true)
// |    |    |    |-- element: double (containsNull = false)
Run Code Online (Sandbox Code Playgroud)
  • array(ArrayType)列:

    • Column.getItem 方法

      df.select($"an_array".getItem(1)).show
      
      // +-----------+
      // |an_array[1]|
      // +-----------+
      // |          2|
      // |          5|
      // +-----------+
      
      Run Code Online (Sandbox Code Playgroud)
    • Hive括号语法:

      sqlContext.sql("SELECT an_array[1] FROM df").show
      
      // +---+
      // |_c0|
      // +---+
      // |  2|
      // |  5|
      // +---+
      
      Run Code Online (Sandbox Code Playgroud)
    • 一个UDF

      val get_ith = udf((xs: Seq[Int], i: Int) => Try(xs(i)).toOption)
      
      df.select(get_ith($"an_array", lit(1))).show
      
      // +---------------+
      // |UDF(an_array,1)|
      // +---------------+
      // |              2|
      // |              5|
      // +---------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • 除了上面列出的方法之外,Spark还支持越来越多的复杂类型的内置函数列表.值得注意的例子包括高阶函数,如transform(仅限SQL,2.4 +):

      df.selectExpr("transform(an_array, x -> x + 1) an_array_inc").show
      // +------------+
      // |an_array_inc|
      // +------------+
      // |   [2, 3, 4]|
      // |   [5, 6, 7]|
      // +------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • filter (仅限SQL,2.4 +)

      df.selectExpr("filter(an_array, x -> x % 2 == 0) an_array_even").show
      // +-------------+
      // |an_array_even|
      // +-------------+
      // |          [2]|
      // |       [4, 6]|
      // +-------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • aggregate (仅限SQL,2.4 +):

      df.selectExpr("aggregate(an_array, 0, (acc, x) -> acc + x, acc -> acc) an_array_sum").show
      // +------------+
      // |an_array_sum|
      // +------------+
      // |           6|
      // |          15|
      // +------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • 数组处理函数(array_*)如array_distinct(2.4+):

      import org.apache.spark.sql.functions.array_distinct
      
      df.select(array_distinct($"an_array_of_structs.vals"(0))).show
      // +-------------------------------------------+
      // |array_distinct(an_array_of_structs.vals[0])|
      // +-------------------------------------------+
      // |                                 [1.0, 2.0]|
      // |                                 [5.0, 6.0]|
      // +-------------------------------------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • array_max(array_min,2.4 +):

      import org.apache.spark.sql.functions.array_max
      
      df.select(array_max($"an_array")).show
      // +-------------------+
      // |array_max(an_array)|
      // +-------------------+
      // |                  3|
      // |                  6|
      // +-------------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • flatten (2.4 +)

      import org.apache.spark.sql.functions.flatten
      
      df.select(flatten($"an_array_of_structs.vals")).show
      // +---------------------------------+
      // |flatten(an_array_of_structs.vals)|
      // +---------------------------------+
      // |             [1.0, 2.0, 2.0, 3...|
      // |             [5.0, 6.0, 7.0, 8.0]|
      // +---------------------------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • arrays_zip (2.4及以上):

      import org.apache.spark.sql.functions.arrays_zip
      
      df.select(arrays_zip($"an_array_of_structs.vals"(0), $"an_array_of_structs.vals"(1))).show(false)
      // +--------------------------------------------------------------------+
      // |arrays_zip(an_array_of_structs.vals[0], an_array_of_structs.vals[1])|
      // +--------------------------------------------------------------------+
      // |[[1.0, 3.0], [2.0, 4.0], [2.0, 5.0]]                                |
      // |[[5.0, 7.0], [6.0, 8.0]]                                            |
      // +--------------------------------------------------------------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • array_union (2.4及以上):

      import org.apache.spark.sql.functions.array_union
      
      df.select(array_union($"an_array_of_structs.vals"(0), $"an_array_of_structs.vals"(1))).show
      // +---------------------------------------------------------------------+
      // |array_union(an_array_of_structs.vals[0], an_array_of_structs.vals[1])|
      // +---------------------------------------------------------------------+
      // |                                                 [1.0, 2.0, 3.0, 4...|
      // |                                                 [5.0, 6.0, 7.0, 8.0]|
      // +---------------------------------------------------------------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • slice (2.4及以上):

      import org.apache.spark.sql.functions.slice
      
      df.select(slice($"an_array", 2, 2)).show
      // +---------------------+
      // |slice(an_array, 2, 2)|
      // +---------------------+
      // |               [2, 3]|
      // |               [5, 6]|
      // +---------------------+
      
      Run Code Online (Sandbox Code Playgroud)
  • map(MapType)列

    • 使用Column.getField方法:

      df.select($"a_map".getField("foo")).show
      
      // +----------+
      // |a_map[foo]|
      // +----------+
      // |       bar|
      // |      null|
      // +----------+
      
      Run Code Online (Sandbox Code Playgroud)
    • 使用Hive括号语法:

      sqlContext.sql("SELECT a_map['foz'] FROM df").show
      
      // +----+
      // | _c0|
      // +----+
      // |null|
      // | baz|
      // +----+
      
      Run Code Online (Sandbox Code Playgroud)
    • 使用点语法的完整路径:

      df.select($"a_map.foo").show
      
      // +----+
      // | foo|
      // +----+
      // | bar|
      // |null|
      // +----+
      
      Run Code Online (Sandbox Code Playgroud)
    • 使用UDF

      val get_field = udf((kvs: Map[String, String], k: String) => kvs.get(k))
      
      df.select(get_field($"a_map", lit("foo"))).show
      
      // +--------------+
      // |UDF(a_map,foo)|
      // +--------------+
      // |           bar|
      // |          null|
      // +--------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • 越来越多的map_*功能,如map_keys(2.3+)

      import org.apache.spark.sql.functions.map_keys
      
      df.select(map_keys($"a_map")).show
      // +---------------+
      // |map_keys(a_map)|
      // +---------------+
      // |          [foo]|
      // |          [foz]|
      // +---------------+
      
      Run Code Online (Sandbox Code Playgroud)
    • map_values(2.3+)

      import org.apache.spark.sql.functions.map_values
      
      df.select(map_values($"a_map")).show
      // +-----------------+
      // |map_values(a_map)|
      // +-----------------+
      // |            [bar]|
      // |            [baz]|
      // +-----------------+
      
      Run Code Online (Sandbox Code Playgroud)

    请查看SPARK-23899的详细清单.

  • StructType使用带有点语法的完整路径的struct()列:

  • structs可以使用点语法,名称和标准Column方法访问数组内的字段:

    df.select($"an_array_of_structs.foo").show
    
    // +----------+
    // |       foo|
    // +----------+
    // |[foo, bar]|
    // |[foz, baz]|
    // +----------+
    
    sqlContext.sql("SELECT an_array_of_structs[0].foo FROM df").show
    
    // +---+
    // |_c0|
    // +---+
    // |foo|
    // |foz|
    // +---+
    
    df.select($"an_array_of_structs.vals".getItem(1).getItem(1)).show
    
    // +------------------------------+
    // |an_array_of_structs.vals[1][1]|
    // +------------------------------+
    // |                           4.0|
    // |                           8.0|
    // +------------------------------+
    
    Run Code Online (Sandbox Code Playgroud)
  • 可以使用UDF访问用户定义的类型(UDT)字段.有关详细信息,请参阅UDT的SparkSQL引用属性.

备注:

  • 根据Spark版本,这些方法中的一些只能使用HiveContext.UDF应该独立于标准SQLContext和版本的版本工作HiveContext.
  • 一般而言,嵌套值是二等公民.并非嵌套字段支持所有典型操作.根据上下文,可以更好地展平架构和/或爆炸集合

    df.select(explode($"an_array_of_structs")).show
    
    // +--------------------+
    // |                 col|
    // +--------------------+
    // |[foo,1,WrappedArr...|
    // |[bar,2,WrappedArr...|
    // |[foz,3,WrappedArr...|
    // |[baz,4,WrappedArr...|
    // +--------------------+
    
    Run Code Online (Sandbox Code Playgroud)
  • 点语法可以与通配符(*)组合以选择(可能是多个)字段,而无需显式指定名称:

    df.select($"a_struct.*").show
    // +---+
    // |  x|
    // +---+
    // |  1|
    // |  2|
    // +---+
    
    Run Code Online (Sandbox Code Playgroud)
  • 可以使用get_json_objectfrom_json函数查询JSON列.请参见如何使用Spark DataFrames查询JSON数据列?详情.