2016-09-14 158 views
2

我有創建數據框架的代碼,如果在我的輸入數據中沒有數組,那麼這可以正常工作。如何使用spark在數據框架中創建模式陣列

我試過使用JSON數據,沒有數組,它運行成功。 我的代碼是

val vals = sc.parallelize(
    """{"id":"1","name":"alex"}""" :: 
    Nil 
) 

val schema = (new StructType) 
     .add("id", StringType) 
     .add("name", StringType) 


    sqlContext.read.schema(schema).json(vals).select($"*").printSchema() 

我的問題是,如果我有輸入數據與數組像下面那麼如何創建模式?

 val vals = sc.parallelize(
    """{"id":"1","name":"alex","score":[{"keyword":"read","point":10}]}""" :: 
    Nil 
) 


val schema = (new StructType) 
     .add("id", StringType) 
     .add("name", StringType) 

謝謝。

+1

有在網絡上這麼多的文章。你有什麼嘗試? – Samar

回答

3

奧克,我可以在我的代碼中有解決方案。

在數據框中創建數組中的模式會產生這樣的代碼。

val vals = sc.parallelize(
    """{"id":"1","name":"alex","score":[{"keyword":"read","point":10}]}""" :: 
    Nil 
) 

val schema = StructType(
     Array(
     StructField("id", StringType), 
     StructField("name", StringType), 
     StructField("score", ArrayType(StructType(Array(
      StructField("keyword", StringType), 
      StructField("point", IntegerType) 
     )))) 
    ) 
    ) 

,則在打印模式

sqlContext.read.schema(schema).json(vals).select($"*").printSchema() 

感謝解決

相關問題