Spark临时表tempView的注册/使用/注销/注意事项(推荐)

2022-10-22,,,,

createtempview运作原理

先说一个众人皆知的知识:
spark中的算子包含transformation算子和action算子,transformation是根据原有rdd创建一个新的rdd,而action则把rdd操作后的结果返回给driver。spark对transformation的抽象可以大大提高性能,这是因为在spark中,所有transformation操作都是lazy模式,即spark不会立即计算结果,而只是简单地记住所有对数据集的转换操作逻辑。这些转换只有遇到action操作的时候才会开始计算。这样的设计使得spark更加高效。

低效做法

sql("select a,b from table where xxx").createtempview("view1")
sql("select a from view1 where xxx").show()
sql("select b from view1 where xxx").show()

使用createtempview后,查询这个视图每次都很耗时了,正是因为createtempview操作是lazy模式,在没有action算子触发之前,它并没有什么实质性的运作,仅仅记录了一个创建视图的逻辑
spark每次遇到action算子show()方法的时候,才开始真正计算,上面代码中两次用到视图view1,那么意味着创建视图的方法会执行两次,因此非常的耗时,所以需要对view1进行缓存处理

缓存临时表方式:

方式1 创建

// 创建它的sparksession对象终止前有效
df.createorreplacetempview("tempviewname")  
// spark应用程序终止前有效
df.createorreplaceglobaltempview("tempviewname") 

注销

spark.catalog.droptempview("tempviewname")
spark.catalog.dropglobaltempview("tempviewname")

方式2

创建

session.table("tempviewname").cache()

注销

session.table("tempviewname").unpersist()

方式3

创建

commondf.cahe() 或 commondf.persist(storagelevel.memory_and_disk)
commondf.createorreplacetempview("tempviewname")

注销

commondf.unpersist()

临时表生命周期

源码

createorreplacetempview

  /**
   * 使用给定名称创建本地临时视图。此临时视图的生命周期与用于创建此数据集的 sparksession 相关联。
   *
   * @group basic
   * @since 2.0.0
   */
  def createorreplacetempview(viewname: string): unit = withplan {
    createtempviewcommand(viewname, replace = true, global = false)
  }

也就是说,当一下代码中spark stop(),之后 创建的临时视图表才失效

createglobaltempview

/**
   * 使用给定名称创建一个全局临时视图。此临时视图的生命周期与此 spark 应用程序相关联。全局临时视图是跨会话的。它的生命周期是 spark 应用程序的生命周期,即当应用程序终止时它会被自动删除。它与系统保留的数据库 global_temp 相关联,我们必须使用限定名称来引用全局临时视图,例如从 global_temp.view1 中选择。
   *
   * @throws analysisexception if the view name is invalid or already exists
   *
   * @group basic
   * @since 2.1.0
   */
  @throws[analysisexception]
  def createglobaltempview(viewname: string): unit = withplan {
    createtempviewcommand(viewname, replace = false, global = true)
  }

到此这篇关于spark临时表tempview的注册/使用/注销/注意事项的文章就介绍到这了,更多相关spark临时表tempview内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Spark临时表tempView的注册/使用/注销/注意事项(推荐).doc》

下载本文的Word格式文档,以方便收藏与打印。