我正在从 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/