LanguageManual VariableSubstitution

Introduction

Hive 用于批处理和交互式查询。变量替换允许执行诸如将特定于环境的配置变量与代码分离的任务。

Hive 变量替换机制旨在避免将某些代码烘焙到 Hive 之上的脚本语言中。

诸如以下 shell 命令之类的示例可以(有效地)用于在脚本内设置变量:

$ a=b
$ hive -e " describe $a "

当 Hive 与脚本语言紧密结合时,这令人沮丧。在执行数千次操作(例如多次hive -e调用)时,Hive 的启动时间只有几秒钟。

Hive 变量 将您熟悉和喜爱的设置功能与一些有限而强大的替代功能结合在一起。

下面的例子:

$ bin/hive --hiveconf a=b -e 'set a; set hiveconf:a; \
create table if not exists b (col int); describe ${hiveconf:a}'

results in:

Hive history file=/tmp/edward/hive_job_log_edward_201011240906_1463048967.txt
a=b
hiveconf:a=b
OK
Time taken: 5.913 seconds
OK
col	int	
Time taken: 0.754 seconds

有关 Hive 命令行选项的一般信息,请参阅Hive CLI

Version information

hiveconf选项已在版本 0.7.0(JIRA HIVE-1096)中添加。 0.8.0 版添加了选项definehivevar(JIRA HIVE-2020),它们是等效的,在此不再赘述。它们在与 hiveconf,system 和 env 命名空间分开的命名空间中创建自定义变量。

Using Variables

变量有三个命名空间-hiveconf,system 和 env。 (也可以使用 Hive 0.8.0 和更高版本中的definehivevar选项在单独的命名空间中创建Custom variables。)

hiveconf 变量设置为正常:

set x=myvalue

但是,使用以下方法检索它们:

${hiveconf:x}

测试用例 ql/src/test/queries/clientpositive/set_processor_namespaces.q 中的用法 Comments 示例:

set zzz=5;
--  sets zzz=5
set zzz;

set system:xxx=5;
set system:xxx;
-- sets a system property xxx to 5

set system:yyy=${system:xxx};
set system:yyy;
-- sets yyy with value of xxx

set go=${hiveconf:zzz};
set go;
-- sets go base on value on zzz

set hive.variable.substitute=false;
set raw=${hiveconf:zzz};
set raw;
-- disable substitution set a value to the literal

set hive.variable.substitute=true;

EXPLAIN SELECT * FROM src where key=${hiveconf:zzz};
SELECT * FROM src where key=${hiveconf:zzz};
--use a variable in a query

set a=1;
set b=a;
set c=${hiveconf:${hiveconf:b}};
set c;
--uses nested variables. 

set jar=../lib/derby.jar;

add file ${hiveconf:jar};
list file;
delete file ${hiveconf:jar};
list file;

查询构造期间的替换

使用该变量构造查询时,Hive 会用该值替换该变量。

  • 如果您运行两个不同的 Hive 会话,则变量值不会在各个会话之间混合。

  • 如果在同一 Hive 会话中使用相同的名称设置变量,则查询将使用最后一个设置值。

禁用变量替换

默认情况下,变量替换处于启用状态(hive.variable.substitute = true)。如果这导致现有脚本出现问题,请使用以下命令将其禁用:

set hive.variable.substitute=false;