首页 > 解决方案 > pyspark 数据框列:Hive 列

问题描述

我有一个 Hive 表如下:

hive> describe stock_quote;
OK
tickerid                string                                      
tradeday                string                                      
tradetime               string                                      
openprice               string                                      
highprice               string                                      
lowprice                string                                      
closeprice              string                                      
volume                  string

以下 Spark 代码读取 csv 文件并尝试将记录插入 Hive 表:

sc = spark.sparkContext
lines = sc.textFile('file:///<File Location>')
rows = lines.map(lambda line : line.split(','))
rows_map = rows.map(lambda row : Row(TickerId = row[0], TradeDay = row[1], TradeTime = row[2], OpenPrice = row[3], HighPrice = row[4], LowPrice = row[5], ClosePrice = row[6], Volume = row[7]))
rows_df = spark.createDataFrame(rows_map)
rows_df.write.mode('append').insertInto('default.stock_quote')

我面临的问题是,当我在数据帧上调用 show() 函数时,它会按字母顺序打印列,如下所示

|ClosePrice|HighPrice|LowPrice|OpenPrice|TickerId|TradeDay|TradeTime|Volume|

, 在表中,它在 TickerId(Hive 表中的第 1 列) 列中插入 ClosePrice(DF 中的第 1 列) 的值,在 TradeDay 列中插入 HighPrice 的值等等。

试图在数据帧上调用 select() 函数,但没有帮助。试图将列名列表如下:

rows_df = spark.createDataFrame(rows_map, ["TickerId", "TradeDay", "TradeTime", "OpenPrice", "HighPrice", "LowPrice", "ClosePrice", "Volume"])

上面更改了列名的顺序,但值保持在相同的位置,这更加不正确。

任何帮助将不胜感激。

标签: apache-sparkdataframehive

解决方案


您也可以使用saveAsTable而不是insertInto

文档

与 不同insertIntosaveAsTable将使用列名来查找正确的列位置


推荐阅读