要解决“Apache Spark Scala - 使用指定的模式从CSV文件中加载数据不会遵守空值约束”的问题,您可以使用option("nullValue", "")
来指定空值约束。
以下是使用指定模式从CSV文件加载数据时应用空值约束的示例代码:
import org.apache.spark.sql.SparkSession
object CSVDataLoadExample {
def main(args: Array[String]): Unit = {
val spark = SparkSession.builder()
.appName("CSVDataLoadExample")
.master("local")
.getOrCreate()
val filePath = "path/to/csvfile.csv"
val schema = "col1 INT, col2 STRING, col3 DOUBLE" // 指定列的数据类型和名称
val df = spark.read
.option("header", "true")
.option("nullValue", "") // 指定空值约束
.schema(schema) // 指定模式
.csv(filePath)
df.show()
}
}
在上面的示例中,我们使用option("nullValue", "")
指定空值约束。这将告诉Spark将空字符串("")视为空值,并且遵守空值约束。
请确保将filePath
更改为实际的CSV文件路径,并根据您的数据的实际模式更新scheme
。
这样,您应该能够从CSV文件加载数据并遵守空值约束。