首页 > 解决方案 > 如何在pyspark /中的结构内爆炸结构中的内部数组

问题描述

我是新来的火花。我试过在一个array内部爆炸struct。JSON 循环有点复杂,如下所示。

{
"id": 1,
"firstfield": "abc",
"secondfield": "zxc",
"firststruct": {
    "secondstruct": {
        "firstarray": [{
            "firstarrayfirstfield": "asd",
            "firstarraysecondfield": "dasd",
            "secondarray": [{
                "score": " 7 "
            }]
        }]
    }
}

}

我正在尝试访问score字段下的secondarray字段,以便能够计算一些指标并得出每个指标的平均分数id

标签: pythonpysparkaws-glue

解决方案


如果您使用的是 Glue,那么您应该将 DynamicFrame 转换为 Spark 的 DataFrame,然后使用explode函数:

from pyspark.sql.functions import col, explode

scoresDf = dynamicFrame.toDF
  .withColumn("firstExplode", explode(col("firststruct.secondstruct.firstarray")))
  .withColumn("secondExplode", explode(col("firstExplode.secondarray")))
  .select("secondExplode.score") 

scoresDyf = DynamicFrame.fromDF(scoresDf, glueContext, "scoresDyf")

推荐阅读