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';

 

解析 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;
复制代码

 

3、使用 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])
复制代码

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

hive>add file /home/hadoop/weekday_mapper.py;
hive> insert into table lastjsontable select transform(movie,rate,unixtime,userid)
using 'python weekday_mapper.py' as(movie,rate,weekday,userid) from rate;

 

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

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

 

最后查询看数据是否正确

select distinct(weekday) from lastjsontable;