从 Scala 中其他 2 个数据集中的特定列创建新数据集

Create new dataset from specific columns from 2 other datasets in scala

我有以下 2 个不同架构的数据集。

case class schema1(a: Double, b: Double) -> dataset1
case class schema2(c: Double, d: Double, e: Double, f: Double) -> dataset2

我想创建另一个具有以下架构的数据集:

case class schema3(c: Double,  b: Double) -> dataset3

即 schema3 数据集包含模式 2 数据集的第一列 c 和模式 1 数据集的第二列 b。

如何利用数据集 2 和 1 中 c 列和 b 列的数据,基于 schema3 创建第三个数据集。

或者更简单地说,我必须通过从第一个数据集中获取一列和从第二个数据集中获取另一列并将其映射到上面定义的第三个模式来创建第三个数据集。

请帮忙。

使用 monotonically_increasing_idrow_numer 在两个数据集中添加唯一的 id 值并使用 id 列连同两个数据集中的必需列连接两个数据集,最后从结果数据集中删除 id .

请检查以下代码。

scala> case class schema1(a: Double, b: Double)
defined class schema1

scala> case class schema2(c: Double, d: Double, e: Double, f: Double)
defined class schema2

scala> import org.apache.spark.sql.expressions._
import org.apache.spark.sql.expressions._

scala> val sa = Seq(schema1(11,12),schema1(22,23)).toDF.withColumn("id",monotonically_increasing_id).withColumn("id",row_number().over(Window.orderBy("id")))
sa: org.apache.spark.sql.DataFrame = [a: double, b: double ... 1 more field]

scala> val sb = Seq(schema2(22,23,24,25),schema2(32,33,34,35),schema2(132,133,134,135)).toDF.withColumn("id",monotonically_increasing_id).withColumn("id",row_number().over(Window.orderBy("id")))
sb: org.apache.spark.sql.DataFrame = [c: double, d: double ... 3 more fields]

scala> sa.show(false)
+----+----+---+
|a   |b   |id |
+----+----+---+
|11.0|12.0|0  |
|22.0|23.0|1  |
+----+----+---+


scala> sb.show(false)
+-----+-----+-----+-----+---+
|c    |d    |e    |f    |id |
+-----+-----+-----+-----+---+
|22.0 |23.0 |24.0 |25.0 |0  |
|32.0 |33.0 |34.0 |35.0 |1  |
|132.0|133.0|134.0|135.0|2  |
+-----+-----+-----+-----+---+

scala> sb.select("c","id").join(sa.select("b","id"),Seq("id"),"full").drop("id").show(false)
+-----+----+
|c    |b   |
+-----+----+
|22.0 |12.0|
|32.0 |23.0|
|132.0|null|
+-----+----+