簡體   English   中英

是否可以在spark中插入臨時表?

[英]Is it possible to insert into temporary table in spark?

我使用 Databricks 和 Apache Spark 2.4 測試了以下查詢:

%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:不允許插入到基於 RDD 的表中。;; 'InsertIntoTable 項目 [1 AS no#824, aaa AS str#825], false, false +- LocalRelation [col1#831, col2#832]

我的問題是

  1. 在spark中插入臨時表是不可能的嗎?
  2. 如何在 spark sql 中創建臨時數據?

謝謝你。

我們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|
#+---+---+

我不認為建議做UNION的答案是有效的(至少在最近的 Databricks 運行時,8.2 spark 運行時 3.1.1),在執行時檢測到遞歸視圖。 上面的代碼示例給出:

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

這看起來很合邏輯。 為什么不使用一些中間臨時視圖或將視圖編寫為托管 Delta 表,這樣它將處理INSERT操作。

是的,您可以插入到臨時視圖中,但它必須基於文件中的 df 構建。 然后新行將作為單獨的文件保存在存儲中。

例如

df.read.parquet(path).createOrReplaceTempView('temp')

spark.sql("INSERT INTO temp VALUES (....)")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM