Hive的TRANSFORM

    xiaoxiao2025-05-02  13

    转载自https://www.cnblogs.com/qingyunzong/p/8746159.html

    Hive 的 TRANSFORM 关键字提供了在 SQL 中调用自写脚本的功能。适合实现 Hive 中没有的 功能又不想写 UDF 的情况

    具体以一个实例讲解。

    Json 数据: {"movie":"1193","rate":"5","timeStamp":"978300760","uid":"1"}

    需求:把 timestamp 的值转换成日期编号

    1、先加载 rating.json 文件到 hive 的一个原始表 rate_json

    create table rate_json(line string) row format delimited; load data local inpath '/home/hadoop/rating.json' into table rate_json;

    2、创建 rate 这张表用来存储解析 json 出来的字段:

    create table rate(movie int, rate int, unixtime int, userid int) row format delimited fields terminated by '\t';

    3、解析 json,得到结果之后存入 rate 表:

    insert into table rate select get_json_object(line,'$.movie') as moive, get_json_object(line,'$.rate') as rate, get_json_object(line,'$.timeStamp') as unixtime, get_json_object(line,'$.uid') as userid from rate_json;

    4、

    使用 transform+python 的方式去转换 unixtime 为 weekday,先编辑一个 python 脚本文件:

    ########python######代码 ## vi weekday_mapper.py #!/bin/python import sys import datetime for line in sys.stdin: line = line.strip() movie,rate,unixtime,userid = line.split('\t') weekday = datetime.datetime.fromtimestamp(float(unixtime)).isoweekday() print '\t'.join([movie, rate, str(weekday),userid])

    5、保存文件 然后,将文件加入 hive 的 classpath:

    add file /home/hadoop/weekday_mapper.py;

    6、创建最后的用来存储调用 python 脚本解析出来的数据的表:lastjsontable:

    create table lastjsontable(movie int, rate int, weekday int, userid int) row format delimited fields terminated by '\t';

    7、使用脚本插入数据:

    insert into table lastjsontable select transform(movie,rate,unixtime,userid) using 'python weekday_mapper.py' as(movie,rate,weekday,userid) from rate;

    8、查询数据:

    select distinct(weekday) from lastjsontable;

     

    最新回复(0)