【问题标题】:Is it possible to insert into temporary table in spark?是否可以在火花中插入临时表?
【发布时间】:2020-07-10 09:03:35
【问题描述】:

我使用带有 Apache Spark 2.4 的 Databricks 测试了以下查询:

%sql

<step1>
create temporary view temp_view_t
as select 1 as no, 'aaa' as str;

<step2>
insert into temp_view_t values (2,'bbb');

然后我收到此错误消息。

SQL 语句错误:AnalysisException: Inserting into an RDD-based table is not allowed.;; 'InsertIntoTable 项目 [1 AS no#824, aaa AS str#825], false, false +- 本地关系 [col1#831, col2#832]

我的问题是

  1. spark中不能插入临时表吗?
  2. 如何在 spark sql 中创建临时数据?

谢谢。

【问题讨论】:

    标签: apache-spark temporary


    【解决方案1】:

    我认为建议执行 UNION 的答案不起作用(至少在最近的 Databricks 运行时,8.2 spark 运行时 3.1.1),在执行时检测到递归视图。上面的代码示例给出:

    AnalysisException: Recursive view `temp_view_t` detected (cycle: `temp_view_t` -> `temp_view_t`)
    

    这似乎很合乎逻辑。 为什么不使用一些中间临时视图或将视图编写为托管 Delta 表,这样它将处理 INSERT 操作。

    【讨论】:

      【解决方案2】:

      是的,您可以插入临时视图,但它必须基于 df build from file。然后新行将作为单独的文件保存在存储中。

      例如

      df.read.parquet(path).createOrReplaceTempView('temp')
      
      spark.sql("INSERT INTO temp VALUES (....)")
      

      【讨论】:

      • 请在您的回答中给出正确的解释和 cmets,以便它与问题的 OP 相关。
      【解决方案3】:

      我们can't 将数据插入到临时表中,但我们可以使用 union all(或)union(以删除重复项)来模拟插入。

      Example:

      #create temp view
      spark.sql("""create or replace temporary view temp_view_t as select 1 as no, 'aaa' as str""")
      
      spark.sql("select * from temp_view_t").show()
      #+---+---+
      #| no|str|
      #+---+---+
      #|  1|aaa|
      #+---+---+
      
      #union all with the new data
      spark.sql("""create or replace temporary view temp_view_t as select * from temp_view_t union all select 2 as no, 'bbb' as str""")
      
      spark.sql("select * from temp_view_t").show()                                                                     
      #+---+---+
      #| no|str|
      #+---+---+
      #|  1|aaa|
      #|  2|bbb|
      #+---+---+
      
      #to eliminate duplicates we can use union also. 
      spark.sql("""create or replace temporary view temp_view_t as select * from temp_view_t union select 1 as no, 'aaa' as str""")
      
      spark.sql("select * from temp_view_t").show()
      #+---+---+
      #| no|str|
      #+---+---+
      #|  1|aaa|
      #|  2|bbb|
      #+---+---+
      

      【讨论】:

        猜你喜欢
        • 2016-07-31
        • 2012-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-04
        • 1970-01-01
        • 1970-01-01
        • 2022-08-23
        相关资源
        最近更新 更多