首页 > 解决方案 > Spark 结构化流/Spark SQL 中的条件爆炸

问题描述

我正在尝试在 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-sparkapache-spark-sqlspark-structured-streaming

解决方案


用于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]

推荐阅读