apache-spark - 使用结构和数组类型定义模式
问题描述
我有一个 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) \
])
我不知道如何定义数组和结构。
解决方案
这是一个例子:
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)
])
推荐阅读
- php - PHP:如果域是测试环境,则更改代码
- node.js - 在节点应用程序中安装 npm 包时无法安装“弱”?
- r - 闪亮的连续反应数据表
- java - 在处理之前让 SpringBoot API 返回 200
- ios - LaunchScreen.storyboard 在 iPhone X 上没有占据全部高度
- javascript - 将小部件对象状态存储到 ipython 内核对象实例而不是对象类
- flutter - 小部件变量为空颤动
- sql - SELECT TOP(x 行数)单个用户观看的视频
- php - 解码json嵌套PHP(laravel)
- javascript - 给 A 与 B 相同的值而不使它们相互连接