PySpark sqlContext JSON查询数组的所有值

问题描述 投票:0回答:1

我目前有一个json文件,我试图用sqlContext.sql()查询,看起来像这样:

{
  "sample": {
    "persons": [
      {
        "id": "123",
      },
      {
        "id": "456",
      }
    ]
  }
}

如果我只想要输入的第一个值:

sqlContext.sql("SELECT sample.persons[0] FROM test")

但是我想要“人”的所有价值,而不必写一个循环。循环只消耗太多的处理能力,并且考虑到这些文件的大小,这将是不切实际的。

我以为我能够在[]括号中放置一个范围,但我找不到任何语法来做到这一点。

python sql json apache-spark pyspark
1个回答
3
投票

如果您的架构如下所示:

root
 |-- sample: struct (nullable = true)
 |    |-- persons: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- id: string (nullable = true)

并且想要从structs阵列访问单个persons所有你需要做的就是爆炸它:

from pyspark.sql.functions import explode

df.select(explode("sample.persons").alias("person")).select("person.id")

另见:Querying Spark SQL DataFrame with complex types

© www.soinside.com 2019 - 2024. All rights reserved.