开发者社区> 问答> 正文

Spark SQL - createDataFrame错误的struct schema

尝试使用Spark SQL创建DataFrame时,通过传递一个行列表,如下所示:

some_data = [{'some-column': [{'timestamp': 1353534535353, 'strVal': 'some-string'}]},

         {'some-column': [{'timestamp': 1353534535354, 'strVal': 'another-string'}]}]

spark.createDataFrame([Row(**d) for d in some_data]).printSchema()
生成的DataFrame架构是:

root
|-- some-column: array (nullable = true)
| |-- element: map (containsNull = true)
| | |-- key: string
| | |-- value: long (valueContainsNull = true)
这个模式是错误的,因为strVal列是string类型的(实际上收集此DataFrame将导致nulls此列)。

我期望模式是Array合适的Structs- 通过对值的类型的一些Python反射推断。为什么不是这样?除了在这种情况下明确提供架构之外,我还能做些什么吗?

展开
收起
社区小助手 2018-12-12 11:33:12 3687 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    要使用结构,您应该使用嵌套Rows(namedtuples通常是首选,但需要有效的名称标识符):

    from pyspark.sql import Row

    Outer = Row("some-column")
    Inner = Row("timestamp", "strVal")

    spark.createDataFrame([

    Outer([Inner(1353534535353, 'some-string')]),
    Outer([Inner(1353534535354, 'another-string')])

    ]).printSchema()
    root
    |-- some-column: array (nullable = true)
    | |-- element: struct (containsNull = true)
    | | |-- timestamp: long (nullable = true)
    | | |-- strVal: string (nullable = true)
    根据您目前的结构,可以使用中间JSON实现方案结果:

    import json

    spark.read.json(sc.parallelize(some_data).map(json.dumps)).printSchema()
    root
    |-- some-column: array (nullable = true)
    | |-- element: struct (containsNull = true)
    | | |-- strVal: string (nullable = true)
    | | |-- timestamp: long (nullable = true)
    或显式模式:

    from pyspark.sql.types import *

    schema = StructType([StructField(

    "some-column", ArrayType(StructType([
        StructField("timestamp", LongType()), 
        StructField("strVal", StringType())])

    ))])

    spark.createDataFrame(some_data, schema)
    虽然最后一种方法可能不完美。

    2019-07-17 23:20:04
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Hybrid Cloud and Apache Spark 立即下载
Scalable Deep Learning on Spark 立即下载
Comparison of Spark SQL with Hive 立即下载