(1)命令行方式
Hive配置属性存储于 hiveconf 命名空间中,该命名空间中的属性是可读写的。在查询语句中插入 ‘${hiveconf:变量名}‘,就可以通过 hive -hiveconf来替换变量。例如,查询语句和执行方式如下:
[root]$cat test.sql #查看该文件
SELECT * FROM ${hiveconf:tablename}
limit ${hiveconf:var_rows};
[root]$hive -hiveconf tablename=‘t1‘ -hiveconf var_rows=10 -f test.sql
或者
#!/bin/bash
tablename="student"
limitcount="8"
hive -S -e "use test; select * from ${tablename} limit ${limitcount};"
需要注意的是:
(2)hql脚本方式
-- 设置变量
SET startdate=20181201;
SET enddate=20181231;
SET event_name=(‘网商节_主会场‘, ‘网商节_微信分享‘,‘网商节_主会场‘,‘网商节_分会场‘);
-- 查询语句
select
event_name
, count(1) pv
, count(distinct ga_id) uv
from edw_log.user_trace_log_di
where dt between ${hiveconf:startdate} and ${hiveconf:enddate}
and event_name in ${hiveconf:event_name}
and data_source_id = ‘3‘
group by event_name
;
Hive命令行变量,存储于 hivevar 命名空间中,该命名空间中的变量是可读写的。使用方式和hive配置属性类似,只是在查询语句中插入的是‘${hivecar:变量名}‘,其中命名空间"hivecar:"可以省略。例如:
[root]$cat test.sql
SELECT * FROM ${hivevar:tablename} #等同于${tablename}
limit ${hiveconf:var_rows};
[root]$hive -hivevar tablename=‘t1‘ -hiveconf var_rows=10 -f test.sql
因为命令行变量的命名空间是唯一可以省略的,因此:
[root]$hive -hivevar tablename=‘t1‘ -hiveconf var_rows=10 -f test.sql [root]$hive -define tablename=‘t1‘ -hiveconf var_rows=10 -f test.sql [root]$hive -d tablename=‘t1‘ -hiveconf var_rows=10 -f test.sql
其他替换变量的方法:
利用shell脚本设置hive查询语句中的变量
利用Python替换Hive查询语句中的变量
参考资料:
原文:https://www.cnblogs.com/shujuxiong/p/10265800.html