您可以使用 py4j java gateway 导入它。以下代码适用于 spark 2.0.2 并且可以通过直线查询在 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”和“myTempView”。必须有相同的火花会话才能看到临时视图
(请参阅答案:避免以编程方式使用创建的上下文启动 HiveThriftServer2。
注意:即使 Thrift 服务器从终端启动并连接到同一个元存储,也可以访问配置单元表,但是无法访问临时视图,因为它们在 spark 会话中和未写入元存储)