Apache spark 如何将null=false的模式应用于json读取

Apache spark 如何将null=false的模式应用于json读取,apache-spark,Apache Spark,我正在尝试使用json文件为数据帧编写一些测试用例(而产品将是拼花地板)。我使用的是spark testing base framework,在断言数据帧彼此相等时遇到了一个障碍,因为模式不匹配,而json模式总是具有nullable=true 我希望能够将null=false的模式应用于json读取 我编写了一个小测试用例: import com.holdenkarau.spark.testing.DataFrameSuiteBase import org.apache.spark.sql.t

我正在尝试使用json文件为数据帧编写一些测试用例(而产品将是拼花地板)。我使用的是spark testing base framework,在断言数据帧彼此相等时遇到了一个障碍,因为模式不匹配,而json模式总是具有nullable=true

我希望能够将null=false的模式应用于json读取

我编写了一个小测试用例:

import com.holdenkarau.spark.testing.DataFrameSuiteBase
import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
import org.scalatest.FunSuite

class TestJSON extends FunSuite with DataFrameSuiteBase {

  val expectedSchema = StructType(
    List(StructField("a", IntegerType, nullable = false),
         StructField("b", IntegerType, nullable = true))
  )
  test("testJSON") {
    val readJson =
      spark.read.schema(expectedSchema).json("src/test/resources/test.json")

    assert(readJson.schema == expectedSchema)

  }
}
并有一个小test.json文件:

{“a”:1,“b”:2}
{“a”:1}

这将返回一个失败的断言

StructType(StructField(a,IntegerType,true), StructField(b,IntegerType,true))不等于 StructType(StructField(a,IntegerType,false), StructField(b,IntegerType,true))ScalaTestFailureLocation: TestJSON$$anonfun$1(TestJSON.scala:15)应为 :StructType(StructField(a,IntegerType,false), StructField(b,IntegerType,true))实际值
:StructType(StructField(a,IntegerType,true), StructField(b,IntegerType,true))

我是否以正确的方式应用模式?
我使用的是spark 2.2,scala 2.11.8,有一个解决方法,它不是直接从文件中读取json,而是使用RDD读取它,然后应用模式。代码如下:

val expectedSchema = StructType(
    List(StructField("a", IntegerType, nullable = false),
         StructField("b", IntegerType, nullable = true))
  )


  test("testJSON") {
    val jsonRdd =spark.sparkContext.textFile("src/test/resources/test.json")
    //val readJson =sparksession.read.schema(expectedSchema).json("src/test/resources/test.json")
    val readJson = spark.read.schema(expectedSchema).json(jsonRdd)
    readJson.printSchema()
    assert(readJson.schema == expectedSchema)

  }
测试用例通过,打印模式结果为:

root
 |-- a: integer (nullable = false)
 |-- b: integer (nullable = true)
ApacheSpark的JIRA负责这个问题,他们说这不是问题,并说:

这应该在Spark 2.0中最新的文件格式重构中解决。如果仍然遇到问题,请重新打开它。谢谢

如果出现错误,可以再次打开JIRA。
我在spark 2.1.0中进行了测试,但仍然看到相同的问题

上述解决方案确保存在正确的模式,但将空值设置为默认值。在我的例子中,当json字符串中不存在Int时,它被设置为0。

我看到你也对这个问题发表了评论,我是否也应该发表评论并指向这个页面?是的,请你可以。我看不到重新开放JIRA的选择。如果您有此选项,可以重新打开它。