在spark-shell(scala)中,我们导入, org.apache.spark.sql.hive.thriftserver._ 以编程方式为特定的hive上下文启动Hive Thrift服务器 HiveThriftServer2.startWithContext(hiveContext)公开该特定会话的已注册临时表。
我们如何使用python做同样的事情? python上有一个包/ api用于导入HiveThriftServer吗?任何其他想法/建议表示赞赏。
我们已经使用pyspark来创建数据框
谢谢
Ravi Narayanan
答案 0 :(得分:3)
您可以使用py4j java gateway导入它。以下代码适用于spark 2.0.2,可以通过beeline查询在python脚本中注册的临时表。
from py4j.java_gateway import java_import
java_import(sc._gateway.jvm,"")
spark = SparkSession \
.builder \
.appName(app_name) \
.master(master)\
.enableHiveSupport()\
.config('spark.sql.hive.thriftServer.singleSession', True)\
.getOrCreate()
sc=spark.sparkContext
sc.setLogLevel('INFO')
#Start the Thrift Server using the jvm and passing the same spark session corresponding to pyspark session in the jvm side.
sc._gateway.jvm.org.apache.spark.sql.hive.thriftserver.HiveThriftServer2.startWithContext(spark._jwrapped)
spark.sql('CREATE TABLE myTable')
data_file="path to csv file with data"
dataframe = spark.read.option("header","true").csv(data_file).cache()
dataframe.createOrReplaceTempView("myTempView")
然后去直线检查它是否已开始:
in terminal> $SPARK_HOME/bin/beeline
beeline> !connect jdbc:hive2://localhost:10000
beeline> show tables;
它应该显示在python中创建的表和临时表/视图,包括" myTable"和#34; myTempView"以上。为了看到临时视图,有必要使用相同的spark会话
(见ans:Avoid starting HiveThriftServer2 with created context programmatically。
注意:即使Thrift服务器从终端启动并连接到同一个Metastore,也可以访问配置单元表,但是临时视图不能被访问,因为它们在spark会话中而不是写入Metastore )