2016-07-30 60 views
1

有是受以下代碼生成可能的錯誤:火花上數據幀初始化2.0可能的錯誤

_struct = [ 
    types.StructField('string_field', types.StringType(), True), 
    types.StructField('long_field', types.LongType(), True), 
    types.StructField('double_field', types.DoubleType(), True) 
] 
_rdd = sc.parallelize([Row(string_field='1', long_field=1, double_field=1.1)]) 
_schema = types.StructType(_struct) 
_df = sqlContext.createDataFrame(_rdd, schema=_schema) 
_df.take(1) 

預期的輸出是一個與RDD 1行應該被創建。

但與當前的行爲我收到以下錯誤:

DoubleType can not accept object '1' in type <type 'str'> 

PS:我使用的火花2.0彙編斯卡拉2.10

編輯

得益於回答者的建議,我現在可以正確理解這一點。爲了簡化,請確保結構已排序。以下代碼解釋了這一點:

# This doesn't work: 
_struct = [ 
    SparkTypes.StructField('string_field', SparkTypes.StringType(), True), 
    SparkTypes.StructField('long_field', SparkTypes.LongType(), True), 
    SparkTypes.StructField('double_field', SparkTypes.DoubleType(), True) 
] 
_rdd = sc.parallelize([Row(string_field='1', long_field=1, double_field=1.1)]) 

# But this will work, since schema is sorted: 
_struct = sorted([ 
    SparkTypes.StructField('string_field', SparkTypes.StringType(), True), 
    SparkTypes.StructField('long_field', SparkTypes.LongType(), True), 
    SparkTypes.StructField('double_field', SparkTypes.DoubleType(), True) 
], key=lambda x: x.name) 
params = {'string_field':'1', 'long_field':1, 'double_field':1.1} 
_rdd = sc.parallelize([Row(**params)]) 


_schema = SparkTypes.StructType(_struct) 

_df = sqlContext.createDataFrame(_rdd, schema=_schema) 
_df.take(1) 

_schema = SparkTypes.StructType(_struct) 

_df = sqlContext.createDataFrame(_rdd, schema=_schema) 
_df.take(1) 
+2

你是指scala 2.10嗎? – eliasah

回答

4

這看起來像1.x和2.x之間的行爲改變,但我懷疑它是一個錯誤。特別是當您使用kwargs(命名參數)the fields are sorted by names創建對象時。讓我們說明了一個簡單的例子:

Row(string_field='1', long_field=1, double_field=1.1) 
## Row(double_field=1.1, long_field=1, string_field='1' 

正如你可以看到訂單的領域發生變化,在該模式中不再體現。

2.0.0之前Spark驗證類型only if data argument for createDataFrame is a local data structure。所以,下面的代碼:

sqlContext.createDataFrame(
    data=[Row(string_field='1', long_field=1, double_field=1.1)], 
    schema=_schema 
) 

將在1.6失敗以及

星火2.0.0介紹verification for RDDs,並提供本地和分佈式輸入之間一致的行爲。