hive中运行python脚本

hive中可以加载python脚本,然后在hive中运行。

好处:可以解决模型离线上线问题和一些基于行的运算。

python脚本

import sys

#本代码实现47中变换中的求均值
#运行前先处理掉空值
'''
表结构:
uid,c1,c2,c3
123,11,22,33
...
...

'''
if __name__ == '__main__':

    for line in sys.stdin: #hive一行一行读取,必须使用标准输入流输入
        features = line.strip().split('\t')  # 在hive表中字段间的分割符是\t
        if len(features) != 7:   #判断每行的长度是否正确,理论上这句if不要也没问题
            print(sys.stderr, "error:error1!")
            break
        avg = (int(features[1])+int(features[1])+int(features[1])) / 3 # hive传入的数据全部为string类型,所以要先转成int后计算
        print(str(features[0])+'\t'+str(avg))  # 输出到hive表中,输出的格式必须为string类型,'\t'为分隔符

hive中代码:

add ARCHIVE hdfs:///tmp/anaconda3_nlp.zip;   -- 指定python及相关包的路径,该路径为集群hdfs上的路径
add file hdfs:///tmp/02_LSTM/tmp.py;    -- 将上面的python脚本上传到hdfs上(比如你自己的文件下)

drop table if exists manyorder_model_lstm_columntorow;
create table manyorder_model_lstm_columntorow as
select
transform(
            uid
              ,c1
              ,c2
              ,c3
  )
using 'anaconda3_nlp.zip/anaconda3/bin/python  tmp.py'  -- 指定python的路径
as (uid,avg)

from  tableX
;

猜你喜欢

转载自blog.csdn.net/weixin_42247685/article/details/81285965