HiveQL:使用查询结果作为变量

HiveQL: Using query results as variables

在 Hive 中我想从 table 中动态提取信息,将其保存在一个变量中并进一步使用它。考虑以下示例,我在其中检索列 var 的最大值并希望将其用作后续查询中的条件。

set maximo=select max(var) from table;

select
  *
from
  table
where
  var=${hiveconf:maximo}

它不起作用,尽管

set maximo=select max(var) from table;

${hiveconf:maximo}

显示了预期的结果。

正在做:

select '${hiveconf:maximo}'

给予

"select max(var) from table"

虽然。

最佳

Hive 按原样替换变量并且不执行它们。使用 shell 包装器脚本将结果放入变量并将其传递给您的 Hive 脚本。

maximo=$(hive -e "set hive.cli.print.header=false; select max(var) from table;")
hive -hiveconf "maximo"="$maximo" -f your_hive_script.hql

然后在你的脚本中你可以使用select '${hiveconf:maximo}'

@Hein du Plessis

虽然不可能完全按照您的要求从 Hue 中执行操作——这对我来说是一个持续的挫折源——如果您仅限于使用 Hue,并且不能使用上面建议的 shell 包装器,根据场景有变通办法。

当我曾经想通过 selecting table 中一列的最大值来设置一个变量以用于查询时,我是这样绕过它的:

我首先将结果放入包含两列的 table 中,其中一列是(任意词)'MAX_KEY',另一列是最大计算的结果,如下所示:

drop table if exists tam_seg.tbl_stg_temp_max_id;
create table tam_seg.tbl_stg_temp_max_id as
select
    'MAX_KEY' as max_key
    , max(pvw_id) as max_id
from
    tam_seg.tbl_dim_cc_phone_vs_web;

然后我将单词 'MAX_KEY' 添加到子查询中,然后加入上面的 table 这样我就可以在主查询中使用结果:

select
    -- *** here is the joined in value from the table being used ***
    cast(mxi.max_id + qry.temp_id as string) as pvw_id
    , qry.cc_phone_vs_web
from
    (
    select
        snp.cc_phone_vs_web
        , row_number() over(order by snp.cc_phone_vs_web) as temp_id
        -- *** here is the key being added to the sub-query ***
        , 'MAX_KEY' as max_key
    from
        (
        select distinct cc_phone_vs_web from tam_seg.tbl_stg_base_snapshots
        ) as snp
    left outer join
        tam_seg.tbl_dim_cc_phone_vs_web as pvw
        on snp.cc_phone_vs_web = pvw.cc_phone_vs_web
    where
        pvw.cc_phone_vs_web is null
    ) as qry
-- *** here is the table with the select result in being joined in ***
left outer join
    tam_seg.tbl_stg_temp_max_id as mxi
    on qry.max_key = mxi.max_key
;

不确定这是否是您的场景,但也许可以进行调整。不过,我 99% 确定你不能直接将 select 语句直接放入 Hue 中的变量中。

如果我只在 Hue 中做某事,我可能会使用临时 table 和 join 方法。但是,如果我无论如何都使用 shall 包装器,我肯定会在那里使用它。

希望对您有所帮助。