如何检查PySpark中是否存在临时视图?

如何检查PySpark中是否存在临时视图?,pyspark,Pyspark,我了解如何在PySpark中检查表是否存在: >>> spark.catalog.setCurrentDatabase("staging") >>> 'test_table' in sqlContext.tableNames() True 但是,关于观点呢? 如果它是这样创建的: df = sqlContext.sql("SELECT * FROM staging.test_table") df.createOrReplaceTempView("test_v

我了解如何在PySpark中检查表是否存在:

>>> spark.catalog.setCurrentDatabase("staging")
>>> 'test_table' in sqlContext.tableNames()
True
但是,关于观点呢? 如果它是这样创建的:

df = sqlContext.sql("SELECT * FROM staging.test_table")
df.createOrReplaceTempView("test_view")
df.persist(p.persistLevel)

如何检查代码后面是否存在“测试视图”?

您可以使用sqlContext.tableNames和sqlContext.tables

>>> sqlContext.registerDataFrameAsTable(df, "table1")
>>> "table1" in sqlContext.tableNames()
True
>>> "table1" in sqlContext.tableNames("default")
True
“默认”是定义视图的上下文

>>> spark.catalog.setCurrentDatabase("staging")
>>> 'test_view' in sqlContext.tableNames()
False
>>> spark.catalog.setCurrentDatabase("default")
>>> 'test_view' in sqlContext.tableNames()
True
这需要一点时间(>3秒)

更快的方法是尝试/抓住

try:
  _=spark.read.table('test_view')
  print('Exists!')
catch:
  print('Does not exist.')

对于那些使用全局临时视图的人来说,速度非常慢,超过3秒:
sql\u context.tableNames(“global\u temp”)