我們知道在Spark中可以通過start-thriftServer.sh 來啟動ThriftServer,之后並可以通過beeline或者JDBC來連接並執行Spark SQL。在一般的Spark應用中,通常並不希望另外起一個服務進程,自然就要問:可以在Spark dirver program里啟一個嵌入式的ThriftServer嗎?
答案是Yes。要啟動ThriftServer,首先需要HiveContext,並且需要在Spark中已經configure好了Hive。通過啟動HiveContext,可以利用 DataFrame 的saveAsTable方法將dataframe save 成 Hive table,達到持久化效果。下面是代碼示例:
import org.apache.spark.sql.hive.HiveContext import org.apache.spark.sql.hive.thriftserver._ // start the Thrift Server with existing sqlContext casting to HiveContext HiveThriftServer2.startWithContext(sqlContext.asInstanceOf[HiveContext]) // wisdom_lu_country has two columns: id and desc case class lu_country(id:Short,desc:String) // load the file as RDD, split each line to id and desc, and convert it to DataFrame val countryDF = sc.textFile("/FB_100/wisdom_lu_country.csv").map(_.split('^')).map(p=>lu_country(p(0).toShort,p(1))).toDF() // save as Hive table countryDF.write.saveAsTable("wisdom_lu_country")
上述代碼在spark-shell中執行成功。