将数据保存为文本文件,从spark到hdfs

时间:2016-07-28 05:03:29

标签: apache-spark pyspark apache-spark-sql apache-hive

我使用pySparksqlContext使用以下查询处理数据:

(sqlContext.sql("select LastUpdate,Count(1) as Count" from temp_t)
           .rdd.coalesce(1).saveAsTextFile("/apps/hive/warehouse/Count"))

它以以下格式存储:

Row(LastUpdate=u'2016-03-14 12:27:55.01', Count=1)
Row(LastUpdate=u'2016-02-18 11:56:54.613', Count=1)
Row(LastUpdate=u'2016-04-13 13:53:32.697', Count=1)
Row(LastUpdate=u'2016-02-22 17:43:37.257', Count=5)

但我想将数据存储在Hive表中

LastUpdate                           Count

2016-03-14 12:27:55.01                   1
.                                        .
.                                        .

以下是我在Hive中创建表的方法:

CREATE TABLE Data_Count(LastUpdate string, Count int )
ROW FORMAT DELIMITED fields terminated by '|';

我尝试了很多选项,但没有成功。请帮帮我。

2 个答案:

答案 0 :(得分:1)

为什么不将数据加载到Hive本身,而不进行保存文件然后将其加载到配置单元的过程。

from datetime import datetime, date, time, timedelta
hiveCtx = HiveContext(sc)

#Create sample data
currTime = datetime.now()
currRow = Row(LastUpdate=currTime)
delta = timedelta(days=1)
futureTime = currTime + delta
futureRow = Row(LastUpdate=futureTime)
lst = [currRow, currRow, futureRow, futureRow, futureRow]

#parallelize the list and convert to dataframe
myRdd = sc.parallelize(lst)
df = myRdd.toDF()
df.registerTempTable("temp_t")
aggRDD = hiveCtx.sql("select LastUpdate,Count(1) as Count from temp_t group by LastUpdate")
aggRDD.saveAsTable("Data_Count")

答案 1 :(得分:0)

您创建了一个表,现在需要用您生成的数据填充它。

这可以从Spark HiveContext运行,我相信

LOAD DATA INPATH '/apps/hive/warehouse/Count' INTO TABLE Data_Count

或者,您可能希望在数据上构建表

CREATE EXTERNAL TABLE IF NOT Exists Data_Count(
    LastUpdate DATE, 
    Count INT
   ) 
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '|'
STORED AS TEXTFILE
LOCATION '/apps/hive/warehouse/Count';