2016-07-27 46 views
2

我使用spark 1.6,我的目標是創建外部配置單元表,就像我在hive腳本中所做的一樣。爲此,我首先閱讀分區的avro文件並獲取此文件的架構。現在我停在這裏,我不知道如何將這個模式應用到我的創建表中。我使用scala。需要幫助的人。使用spark創建配置單元外部表格

回答

3

最後,我用老式的方式做我自己。隨着下面的代碼幫助:

val rawSchema = sqlContext.read.avro("Path").schema 
val schemaString = rawSchema.fields.map(field => field.name.replaceAll("""^_""", "").concat(" ").concat(field.dataType.typeName match { 
     case "integer" => "int" 
     case smt => smt 
     })).mkString(",\n") 

     val ddl = 
     s""" 
     |Create external table $tablename ($schemaString) \n 
     |partitioned by (y int, m int, d int, hh int, mm int) \n 
     |Stored As Avro \n 
     |-- inputformat 'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat' \n 
     | -- outputformat 'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat' \n 
     | Location 'hdfs://$path' 
     """.stripMargin 

照顧沒有列名可以與_開始,蜂巢無法解析integer。我想說,這種方式不靈活,但工作。如果任何人得到更好的主意,PLZ評論。

1

我沒有看到一種方法來自動推斷外部表的模式。所以我創建了字符串類型的例子。您可以爲您的數據類型添加大小寫。但我不確定你有多少列。我很抱歉,因爲這可能不是一個乾淨的方法。

import org.apache.spark.{SparkConf, SparkContext} 
import org.apache.spark.sql.{Row, SaveMode}; 
import org.apache.spark.sql.types.{StructType,StructField,StringType}; 

val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc) 
val results = hiveContext.read.format("com.databricks.spark.avro").load("people.avro") 


val schema = results.schema.map(x => x.name.concat(" ").concat(x.dataType.toString() match { case "StringType" => "STRING"})).mkString(",") 

val hive_sql = "CREATE EXTERNAL TABLE people_and_age (" + schema + ")     ROW FORMAT DELIMITED     FIELDS TERMINATED BY ','    LOCATION '/user/ravi/people_age'" 

hiveContext.sql(hive_sql) 
results.saveAsTable("people_age",SaveMode.Overwrite) 
hiveContext.sql("select * from people_age").show() 
+0

hx爲您提供幫助。但是這樣桌子就不會是分區的桌子了。任何想法? –

-1

試試下面的代碼。

val htctx= new HiveContext(sc) 
htctx.sql(create extetnal table tablename schema partitioned by attribute row format serde serde.jar field terminated by value location path) 
+0

你能說更多關於哪一個是可變的,Thx –

相關問題