2017-11-22 7 views
2

jsonファイルを使用してデータフレームを作成する際に、いくつかのテストケースを作成しようとしています。私はspark-testing-baseフレームワークを使用していますが、jsonスキーマが常にnullable = trueのスキーマの不一致が原因でデータフレームが互いに等しいと主張すると、jsonの読み込みにnullable = falseのスキーマを適用するには

nullable = falseのスキーマをjsonの読み込みに適用できるようにしたいと考えています。

私は小さなテストケース書いた:これは

StructType(のアサーション失敗を返し {"a": 1, "b": 2} {"a": 1}

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ファイルを持っていますStructField(a、IntegerType、true)、 StructField(b、IntegerType、true))は一致しません StructType(StructField(a、IntegerType 、偽)、 StructField(B、IntegerType、真))ScalaTestFailureLocation: TestJSON $$ anonfun(TestJSON.scalaで$ 1:予想される15) :StructType(StructField()、偽、IntegerType、 StructField(B、IntegerType 、真))実際の
:)、真StructType(StructField(、IntegerType、 StructField真(B、IntegerType、))

私は、スキーマに正しい方法を適用していますか? 私はspark 2.2、scala 2.11.8を使用しています

答えて

1

ファイルから直接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) 

彼らは問題ではありませんと言ったことを言って、この問題のためのApacheスパークとJIRA https://issues.apache.org/jira/browse/SPARK-10848は、あります:

これは、Spark 2.0の最新のファイル形式リファクタリングで解決する必要があります。それでも問題が発生した場合は、再度開いてください。ありがとう!

エラーが発生した場合は、再度JIRAを開くことができます。 spark 2.1.0でテストしましたが、同じ問題が表示されます

+0

この問題にコメントしたことがありますか、私もコメントしてこのページを指す必要がありますか? –

+0

はいできますか。 JIRAを再オープンするオプションはありません。オプションがある場合は、再度開くことができます。 –

0

workAround abovesは正しいスキーマがあることを保証しますが、null値はデフォルト値に設定されています。私のケースでは、Intがjson Stringに存在しない場合、0に設定されます。

関連する問題