有需求,各种批处理完数据,因部分分析人员不具备spark的能力,
比较熟悉sql环境操作
需要每个批处理的统计数据文件都能用sql查询,
现阶段zeppelin下hive/presto两种都是类sql供分析人员使用
下面是zeppelin中pyspark下的简便离子,真实环境,需要hadoop+hive+spark环境
并在spark提交时开启hive支持
注意:千万不要想当然认为数据类型,在另外的地方写创建表和添加分区,比如默认计算都是bigint,如果在hive中用int创建不报错,但是使用查询会报错
最好是写入数据后,同时根据数据类型创建表
bin/pyspark --conf spark.sql.catalogImplementation=hive --conf spark.sql.catalogImplementation=hive
然后交互环境中操作:
from pyspark.sql import HiveContext
from pyspark.sql import functions as F
df=sc.parallelize([(1,2,3),(4,5,6)]).toDF(["A","B","C"]).groupBy(["A","B"]).agg(F.count("C").alias("C_cnt"))
table_name="to_delete_test"
save_hdfs_path="/tmp/"+table_name
df.write.format("parquet").mode("overwrite").save(save_hdfs_path)
hct=HiveContext(sc)
hct.sql("drop table if exists "+table_name)
create_sql='''create external table if not exists '''+table_name+"("
for k,t in df.dtypes:
field_str=k+" "+t+","
create_sql+=field_str
create_sql=create_sql[:-1]
create_sql+=''') stored as parquet location "'''+save_hdfs_path+'''"'''
print "create_sql:\n",create_sql
hct.sql(create_sql)