【问题标题】:Conditional Explode in Spark Structured Streaming / Spark SQLSpark 结构化流/Spark SQL 中的条件爆炸
【发布时间】:2018-06-13 00:04:06
【问题描述】:

我正在尝试在 Spark Structured Streaming 中进行条件爆炸。

例如,我的流数据帧如下所示(完全在此处制作数据)。我想在contingent = 1 时将员工数组分解为单独的数组行。 contingent = 0时,需要让数组保持原样。

|----------------|---------------------|------------------|
|     Dept ID    |     Employees       |    Contingent    |
|----------------|---------------------|------------------|
|          1     | ["John", "Jane"]    |       1          |
|----------------|---------------------|------------------|
|          4     | ["Amy", "James"]    |       0          |
|----------------|---------------------|------------------|
|          2     | ["David"]           |       1          |
|----------------|---------------------|------------------|

所以,我的输出应该是这样的(我不需要显示contingent 列:

|----------------|---------------------|
|     Dept ID    |     Employees       |
|----------------|---------------------|
|          1     | ["John"]            |
|----------------|---------------------|
|          1     | ["Jane"]            |
|----------------|---------------------|
|          4     | ["Amy", "James"]    |
|----------------|---------------------|
|          2     | ["David"]           |
|----------------|---------------------|

我目前面临几个挑战:

  1. 有条件地分解数组
  2. 将数组分解为数组(在这种情况下不是字符串)

在 Hive 中,有一个 UDTF(用户定义的表函数)的概念可以让我这样做。想知道有没有什么可以与之媲美的?

【问题讨论】:

    标签: apache-spark apache-spark-sql spark-structured-streaming


    【解决方案1】:

    使用flatMap 展开并指定您想要的任何条件。

    case class Department (Dept_ID: String, Employees: Array[String], Contingent: Int)
    case class DepartmentExp (Dept_ID: String, Employees: Array[String])
    
    val ds = df.as[Department]
    
    ds.flatMap(dept => {
      if (dept.Contingent == 1) {
        dept.Employees.map(emp => DepartmentExp(dept.Dept_ID, Array(emp)))
      } else {
        Array(DepartmentExp(dept.Dept_ID, dept.Employees))
      }
    }).as[DepartmentExp]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-27
      • 2021-02-16
      • 2018-06-27
      • 2017-01-09
      • 2021-06-04
      • 2019-07-24
      • 2017-08-25
      • 1970-01-01
      相关资源
      最近更新 更多