作为困扰我一周的一个问题,经过各种尝试,最终确定为读取文件并写入的方式颇为高效,在此记录。
# -*- coding: utf-8 -*-
import os
from pyspark import SparkContext, HiveContext, Row, StorageLevel
from pyspark.mllib.stat import Statistics
import tempRain
#加这一部分是为了解决转码问题,就不需要手动encode、decode
reload(sys)
sys.setdefaultencoding('utf-8')
output_tmp_dir="hdfs://hdfs地址"
def loadinto(exampleList,flag):
line1 = sc.parallelize(exampleList)
line1.repartition(1).textsaveAsTextFile(output_tmp_dir+flag)
sqlContext.sql("load data inpath '"+output_tmp_dir+flag+"' into table "+currentSchema+".table1")
#调用example:
dayList=[]
insert="案例1\001案例2\001"
dayList.append(insert)
flag="123"
loadinto(dayList,flag)
思路是先通过RDD的textsaveAsTextFile保存为hdfs文件,再通过hive的load语句加载进入目标table。
目标表建表语句,要保证是表存储格式是textfile格式
create table table1
(
a string,
b string
)
row format delimited
fields terminated by '\001'
stored as textfile
\001是数据间隔符
目前只找到此种文件导入方式,textfile格式表也存在缺点,即文件不压缩,占用空间较大,应该还存在更理想实现方案,
有待验证