apache-spark - 从spark sql插入hive表

标签 apache-spark hive apache-spark-sql

我正在从 json 文件中读取一些数据,并将其转换为用于将数据发送到 hive 的字符串。

数据在 Hive 中正常到达,但它分布到了错误的列,我做了一个小例子

在 hive 中:

Table name = TestTable, Column1 = test1, Column2 = test2`

我的代码:

data = hiveContext.sql("select \"hej\" as test1, \"med\" as test2")
data.write.mode("append").saveAsTable("TestTable")

data = hiveContext.sql("select \"hej\" as test2, \"med\" as test1")
data.write.mode("append").saveAsTable("TestTable")

这会导致 "hej" 两次出现在 test1 中,"med" 出现在 test2 中> 两次,而不是每次都出现一次。

它似乎总是按照编写的顺序显示,而不是进入我用 'as' 关键字提到的列。

有人有什么想法吗?

最佳答案

It always just seems to show up in the order written...

你是对的。 Spark 的工作方式与任何 SQL 数据库一样。输入数据集中的列名称没有任何区别。
由于您没有显式地将输出列映射到输入列,Spark 必须假设映射是按位置完成的。

请思考以下测试用例...

hiveContext.sql("create temporary table TestTable (RunId string, Test1 string, Test2 string)")
hiveContext.sql("insert into table TestTable select 'A', 'x1', 'y1'")
hiveContext.sql("insert into table TestTable (RunId, Test1, Test2) select 'B', 'x2' as Blurb, 'y2' as Test1")
hiveContext.sql("insert into table TestTable (RunId, Test2, Test1) select 'C', 'x3' as Blurb, 'y3' as Test1")
data = hiveContext.sql("select 'xxx' as Test1, 'yyy' as Test2"))
data.registerTempTable("Dummy")
hiveContext.sql("insert into table TestTable(Test1, RunId, Test2) select Test1, 'D', Test2 from Dummy")
hiveContext.sql("insert into table TestTable select Test1, 'E', Test2 from Dummy")
hiveContext.sql("select * from TestTable").show(20)

免责声明 - 我实际上并未测试这些命令,其中可能存在一些拼写错误和语法问题(特别是因为您没有提及您的 Hive 和 Spark 版本),但您应该明白这一点。

关于apache-spark - 从spark sql插入hive表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41202377/

相关文章:

hadoop - 在表中看不到Hadoop Hive数据/在hdfs位置显示

sql - 按值范围分组并删除 Hql/Sql 中的重复行

java - Apache Spark MySQL JavaRDD.foreachPartition - 为什么我收到 ClassNotFoundException

python - 比较两个数据帧 Pyspark

apache-spark-sql - 从 Spark 数据框中选择最新记录

apache-spark - 在没有标题的 Spark Dataframe 中读取 Hive 表

hadoop - Hive 分区不适用于动态变量

java - Spark : Merging 2 columns of a DataSet into a single column

scala - 使用单个开发/测试机器同时拥有 Spark 进程分区

apache-spark - 检查点SqlContext nullpointerException问题