选择表是否存在于 Apache Hive 中

Mav*_*ick 5 hadoop hive hiveql

我有一个 hive 查询的格式,

select . . . from table1 left join (select . . . from table2) on (some_condition)
Run Code Online (Sandbox Code Playgroud)

根据环境,table2可能不存在。因此,如果仅存在 table2,我想加入,否则只需忽略子查询。

如果存在,以下查询将返回 table_name,

show tables in {DB_NAME} like '{table_name}'
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将其集成到我的查询中以仅在它存在时进行选择。

在 hive 查询中有没有办法在选择之前检查表是否存在。

感谢任何帮助

注意:如果表不存在,我不想创建它。

Goo*_*Dok 0

评论中已经提到 Hive 不支持if-else构造,所以如果你想拥有它,你必须从 bash 或HPL/SQL等语言借用它。

我在这里建议的是以下结构:

  1. 将查询的两个版本作为视图定义放入单独的文件中:

view_ddl_if_exists.hql

create view if not exists target_view
as
select . . . from table1 left join (select . . . from table2) on (some_condition)
Run Code Online (Sandbox Code Playgroud)

view_ddl_if_not_exists.hql

create view if not exists target_view
as
select . . . from table1
Run Code Online (Sandbox Code Playgroud)
  1. 添加 shell 脚本来检测实际的视图定义并复制到预定义的位置:

place_ Correct_view_source.sh

if hive -S -e 'explain select 1 from table2' &>/dev/null; then
  cp view_ddl_if_exists.hql actual_view_ddl.hql
else 
  cp view_ddl_if_not_exists.hql actual_view_ddl.hql
fi
Run Code Online (Sandbox Code Playgroud)
  1. 将以下内容添加到您的 script/init 脚本中:
!bash place_correct_view_source.sh;
source actual_view_ddl.hql;
...
Run Code Online (Sandbox Code Playgroud)

瞧!您已在视图中获得正确的查询target_view,并且可以在脚本中使用它。