Spark DataFrame 架构可为空字段

2024-02-11

我在 Scala 和 Python 中编写了以下代码,但是返回的 DataFrame 似乎没有应用我正在应用的架构中的非空字段。italianVotes.csv是一个 csv 文件,以“~”作为分隔符和四个字段。我正在使用火花2.1.0.

意大利投票.csv

2657~135~2~2013-11-22 00:00:00.0
2658~142~2~2013-11-22 00:00:00.0
2659~142~1~2013-11-22 00:00:00.0
2660~140~2~2013-11-22 00:00:00.0
2661~140~1~2013-11-22 00:00:00.0
2662~1354~2~2013-11-22 00:00:00.0
2663~1356~2~2013-11-22 00:00:00.0
2664~1353~2~2013-11-22 00:00:00.0
2665~1351~2~2013-11-22 00:00:00.0
2667~1357~2~2013-11-22 00:00:00.0

Scala

import org.apache.spark.sql.types._
val schema =  StructType(
StructField("id", IntegerType, false) ::
StructField("postId", IntegerType, false) ::
StructField("voteType", IntegerType, true) ::
StructField("time", TimestampType, true) :: Nil)

val fileName = "italianVotes.csv"

val italianDF = spark.read.schema(schema).option("sep", "~").csv(fileName)

italianDF.printSchema()

// output
root
 |-- id: integer (nullable = true)
 |-- postId: integer (nullable = true)
 |-- voteType: integer (nullable = true)
 |-- time: timestamp (nullable = true)

Python

from pyspark.sql.types import *

schema = StructType([
    StructField("id", IntegerType(), False),
    StructField("postId", IntegerType(), False),
    StructField("voteType", IntegerType(), True),
    StructField("time", TimestampType(), True),
])

file_name = "italianVotes.csv"

italian_df = spark.read.csv(file_name, schema = schema, sep = "~")

# print schema
italian_df.printSchema()
root
 |-- id: integer (nullable = true)
 |-- postId: integer (nullable = true)
 |-- voteType: integer (nullable = true)
 |-- time: timestamp (nullable = true)

我的主要问题是,当我在架构中将前两个字段设置为不可为空时,为什么它们可以为空?


一般情况下火花Datasets要么继承nullable来自其父级的属性,或根据外部数据类型进行推断。

你可以争论这是否是一个好方法,但最终它是明智的。如果数据源的语义不支持可为空性约束,那么模式的应用程序也不支持。归根结底,假设事情可以解决总是更好null,如果相反的假设被证明是不正确的,那么运行时就会失败。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spark DataFrame 架构可为空字段 的相关文章

随机推荐