如何在 hive 查询中使用嵌套变量替换

问题描述

我尝试在 hive 查询中直接使用嵌套变量。我正在使用 Hive 和 Dbeaver。

我的目标是遍历条件列表并将结果保存在编号表中(condition_1 | tbl_1、condition_2、tbl_2 等) 举个例子:

@set condition_1 = col1 in (1,10,11) and col2 in (1000,10000)
@set condition_2 = col1 in (2,20,22) and col2 in (2000,20000)
@Set ctrl= 1

create table tbl_${ctrl}
select ${ctrl} as id,* from my_table where ${condition_${ctrl}}

当我运行 select 语句时,它在 where 语句处失败并仅解析 ctrl 变量,我收到此错误消息:

sql Error [40000] [42000]: Error while compiling statement: Failed: ParseException line 22:6 cannot recognize input near '$' '{' 'condition_1' in expression specification

我认为 hive 忽略了最后一个结束大括号。 任何帮助将不胜感激!

我阅读了 Language Manual Variable Substitution 但它只显示了这一点:

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

解决方法

我认为 hive 忽略了最后一个右花括号。

因为美元符号需要放在大括号之前。

像在手册中那样做,它会起作用。指定 hiveconf 命名空间并且不要忘记大括号前的美元符号:${hiveconf:condition_${hiveconf:ctrl}}

这个例子工作正常:

set condition_1 = col1 in (1,10,11) and col2 in (1000,10000);
set condition_2 = col1 in (2,20,22) and col2 in (2000,20000);
Set ctrl= 1;

with Table1 as( 
SELECT stack (2,1,1000,2,2000
) AS  (col1,col2)
)

select ${hiveconf:ctrl} as id,t.* from Table1 t where ${hiveconf:condition_${hiveconf:ctrl}}