如何将带有nullable = false的模式应用于json读取

Nur*_*mji 6 apache-spark

我正在尝试使用json文件为数据帧编写一些测试用例(而生产将是镶木地板).我正在使用基于spark测试的框架,并且当由于模式不匹配而断言数据帧彼此相等时我遇到了麻烦,其中json模式总是具有nullable = true.

我希望能够将具有nullable = 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)

  }
}
Run Code Online (Sandbox Code Playgroud)

并有一个小的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 at(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

Ami*_*mar 7

有一种解决方法,不是直接从文件中读取 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)

  }
Run Code Online (Sandbox Code Playgroud)

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

root
 |-- a: integer (nullable = false)
 |-- b: integer (nullable = true)
Run Code Online (Sandbox Code Playgroud)

有 JIRA https://issues.apache.org/jira/browse/SPARK-10848 with apache Spark for this issue,他们说这不是问题,并说:

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

如果您收到错误消息,您可以再次打开 JIRA。我在 spark 2.1.0 中测试过,仍然看到同样的问题