首页 > 解决方案 > 使用结构和数组类型定义模式

问题描述

我有一个 Spark 数据框,它具有这样的模式(我阅读并推断):

record_id           string
record_type         string
record_timestamp    string
checked             boolean
comments            bigint
categories          array<string>
geo                 struct<coordinates:array<double>,type:string>

展望未来,我想预先定义模式,而不是推断它。我知道如何定义数组和结构以外的所有内容。例如,如果它只是前五个,它看起来像:

schema = StructType([\
    StructField(record_id, StringType(), True), \
    StructField(record_type, StringType(), True), \
    StructField(record_timestamp, TimestampType(), True), \
    StructField(checked, BooleanType(), True), \
    StructField(comments, LongType(), True) \
    ])

我不知道如何定义数组和结构。

标签: apache-sparkpyspark

解决方案


这是一个例子:

from pyspark.sql.types import StructType, StructField, IntegerType, StringType, ArrayType, FloatType

zipsSchema3 = StructType([ \
  StructField("city", StringType(), True), \
  StructField("loc", \
    ArrayType(FloatType(), True), True), \
  StructField("pop", IntegerType(), True) \
])

将模式应用于 JSON 意味着使用 .schema 方法。这将导致仅返回架构中指定的列,并可能更改列类型。

loc表示原始类型的数组:例如"loc" : [ -72.576142, 42.176443 ]

这是一个更复杂的示例,其中包含多个字段的数组:

fullTweetSchema = StructType([
  StructField("id", LongType(), True),
  StructField("user", StructType([
    StructField("id", LongType(), True),
    StructField("screen_name", StringType(), True),
    StructField("location", StringType(), True),
    StructField("friends_count", IntegerType(), True),
    StructField("followers_count", IntegerType(), True),
    StructField("description", StringType(), True)
  ]), True),
  StructField("entities", StructType([
    StructField("hashtags", ArrayType(
      StructType([
        StructField("text", StringType(), True)
      ]),
    ), True),
    StructField("urls", ArrayType(
      StructType([
        StructField("url", StringType(), True),
        StructField("expanded_url", StringType(), True),
        StructField("display_url", StringType(), True)
      ]),
    ), True)
  ]), True),
  StructField("lang", StringType(), True),
  StructField("text", StringType(), True),
  StructField("created_at", StringType(), True)
])

推荐阅读