【问题标题】:Explode Array-Nested Array Spark SQL展开数组嵌套数组 Spark SQL
【发布时间】:2021-06-10 20:19:06
【问题描述】:

我有一个包含多个嵌套数组的 JSON 结构,如下所示:

{
    "id": 10,
    "packages": [
        {
            "packageId": 1010,
            "clusters": [
                {
                    "fieldClusterId": 101010,
                    "fieldDefinitions": [
                        {
                            "fieldId": 101011112999,
                            "fieldName": "EntityId"
                        }
                    ]
                }
            ]
        }
    ]
}

我正在使用 spark sql 将数组展平为如下所示:

id packageId fieldClusterId fieldId fieldName
10 1010 101010 101011112999 EntityId

查询最终是一个相当丑陋的 spark-sql cte,包含多个步骤:

%sql
with cte as(
  select 
    id
    explode(packages) as packages_exploded
  from temp),
cte2 as (
  select
    id,
    packages_exploded.packageId,
    explode(packages_exploded.clusters) as col
  from cte),
cte3 as (
  select 
    id,
    packageId,
    col.fieldClusterId
    explode(col.fieldDefinitions) as col
  from cte2)
select 
    productId,
    productName,
    fieldClusterId,
    fieldClusterName,
    col.*
from cte3

有没有更好的语法来完成这种多层次的爆炸?

【问题讨论】:

  • 是否只需要使用SQL来解决?
  • 是的,该过程是元数据驱动的,需要 spark-sql 查询

标签: apache-spark pyspark apache-spark-sql


【解决方案1】:

这是我要实现的方式:

SELECT id,
       packageId,
       fieldClusterId,
       inline(fieldDefinitions)
FROM
  (SELECT id,
          packageId,
          inline(clusters)
   FROM
     (SELECT id,
             inline(packages)
      FROM TABLE_NAME))

【讨论】:

  • 我希望语法比多阶段 cte 或连续子查询更简洁。您认为没有这些复杂性可以做到吗?
  • 这是不可能的,因为您正在从嵌套对象中分解数组。如果packages、clusters 和fieldDefinitions 是扁平结构中的数组列,您可以使用inline(arrays_zip(packages, clusters, fieldDefinitions)),但事实并非如此。
猜你喜欢
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 2018-10-07
相关资源
最近更新 更多