hivesql将不同的表作为结构数组连接起来

ix0qys7i  于 2021-05-24  发布在  Spark
关注(0)|答案(1)|浏览(406)

让我们有一张table header :

id |  col1 | col2
1  |  "a" | "b"
2  |  "c" | "d"

和table body :

header_id | body_id | body_col
1         | 6       | "abc"
1         | 7       | "def"
2         | 8       | "ghi"
2         | 9       | "jkl"

我想将body作为结构数组插入到header中,在json中,结果如下:

{
  id: 1,
  col1: "a",
  col2: "b",
  body: [{body_id: 6, body_col: "abc"}, {body_id: 7, body_col: "def"}]
},
{
  id: 2,
  col1: "c",
  col2: "d",
  body: [{body_id: 8, body_col: "ghi"}, {body_id: 9, body_col: "jkl"}]
}

我如何做到这一点?阿法伊克 collect_set 或者 collect_list 不起作用,因为它们只将整列收集到一个数组中。

bhmjp9jg

bhmjp9jg1#

您必须从连接两个Dataframe开始。那么 collect_list 实际上是达到你想要的目的的方法。你只需要绑起来 body_id 以及 body_col 一起在一个 struct 第一。
代码如下所示:

val result = header
    .join(body.withColumnRenamed("header_id", "id"), Seq("id"))
    .groupBy("id", "col1", "col2")
    .agg(collect_list(struct('body_id, 'body_col)) as "body")
result.show(false)
+---+----+----+--------------------+
|id |col1|col2|body                |
+---+----+----+--------------------+
|2  |c   |d   |[[8, ghi], [9, jkl]]|
|1  |a   |b   |[[6, abc], [7, def]]|
+---+----+----+--------------------+

我们还可以打印结果的模式,这正是json的构建方式:

root
 |-- id: string (nullable = true)
 |-- col1: string (nullable = true)
 |-- col2: string (nullable = true)
 |-- body: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- body_id: string (nullable = true)
 |    |    |-- body_col: string (nullable = true)

相关问题