踩坑事件:不能对基于文本的临时表使用sql insert语句

先来描述一下问题:

  如果你是从基于文本的数据源来创建DataFrame的,当你将DataFrame注册为临时表后,如果对这个临时表进行insert into 操作,会抛出异常的。

问题答案参见:http://apache-spark-user-list.1001560.n3.nabble.com/How-to-direct-insert-vaules-into-SparkSQL-tables-td11851.html

no, spark sql can not insert or update textfile yet, can only insert into parquet files 

but, 

people.union(new_people).registerAsTable("people") 

could be an idea.

 

 

后来再对基于parquet的DataFrame进行insert into 操作时也出问题,后来发现从这里找到了答案:

http://stackoverflow.com/questions/33923348/insert-into-with-sparksql-hivecontext

 

原因就是语法不对。

原来的语法:insert into people(age,name) values (10,'francis')

修改后的语法:insert into table people select t.* from (select 10,'francis') t

 

复制代码
        // 首先还是创建SparkConf
        SparkConf conf = new SparkConf()
                .setMaster("local")
                .setAppName("HiveDataSource");
        // 创建JavaSparkContext
        JavaSparkContext sc = new JavaSparkContext(conf);
       SQLContext sqlContext=new SQLContext(sc);
 
     DataFrame peopleDF=sqlContext.read().parquet("hdfs://spark2:9000/francis/spark-core/people2.parquet");
     
     peopleDF.show();
  
     peopleDF.registerTempTable("people");
     
      qlContext.sql("insert into table people select t.* from (select 25,'francis') t"); 
     //sqlContext.sql("insert into table people (age,name) values (25,'francis')");  错误
     
     
     peopleDF.show();
复制代码

 

 

I've had the same problem (Spark 1.5.1), and tried different versions.

Given

sqlContext.sql("create table my_table(id int, score int)")

The only versions that worked looked like this:

sqlContext.sql("insert into table my_table select t.* from (select 1, 10) t")
sqlContext.sql("insert into       my_table select t.* from (select 2, 20) t")

 

posted @   王宝生  阅读(1015)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
点击右上角即可分享
微信分享提示