在Hive中删除具有相同前缀的多个表

19

我在Hive中有几个表具有相同的前缀,如下所示...

temp_table_name
temp_table_add
temp_table_area

我在我的数据库中有几百个这样的表,还有许多其他表。 我想删除以"temp_table"开头的表。 你们中有谁知道可以在Hive中完成这项工作的查询吗?


SELECT CONCAT('DROP TABLE ', table_name, ';') FROM information_schema.tables WHERE table_name LIKE 'temp_table%';
8个回答

22

在Hive中没有针对删除查询的正则表达式(或者我没有找到),但是有多种方法可以实现,例如:

  • 使用shell脚本:

  • hive -e "show tables 'temp_*'" | xargs -I '{}' hive -e 'drop table {}'
    
  • 或者将您的表放入特定的数据库中并删除整个数据库。

  • Create table temp.table_name;
    
    Drop database temp cascade;
    

1
hive -e 'show tables 'temp_*' | xargs -I '{}' hive -e 'drop table {}''对我来说无效。 - MysticForce
2
答案是完美的,但需要进行一些小的更改,这对我实际上起作用了。我正在通过添加双引号来修改@Louxou的代码。以下是更新后的代码。 hive -e "show tables 'temp_*'" | xargs -I '{}' hive -e 'drop table {}' - Alex Raj Kaliamoorthy
我想在这里添加一些内容。现在的问题是,Hive(或Beeline)往往以“图形”格式显示结果。此外,如果您在Hive中有多个DB,则需要指定所需的一个。beeline --showHeader=false --outputformat=csv2 -e"use <db>; show tables 'temp_*'" | xargs -I '{}' beeline -e'use<db>; drop table {}' - habarnam

9
上面的解决方案很好。但是,如果您需要删除更多的表格,则运行“hive -e drop table”会很慢。因此,我使用了以下方法:
hive -e 'use db;show tables' | grep pattern > file.hql

使用vim编辑器打开文件.hql,然后运行以下命令。
:%s!^!drop table  
:%s!$!;

然后运行

hive -f file.hql

这种方法会更快。


你在这里提到匹配表格模式的地方在哪里? - Alex Raj Kaliamoorthy
1
@Alex Raj Kaliamoorthy - grep 'pattern'@Alex Raj Kaliamoorthy - grep '模式' - Chandra
请注意,在“drop table”后面有一个空格,就像这样:drop table - Autonomous

5

我的解决方案是使用以下命令的Bash脚本:

hive -e "SHOW TABLES IN db LIKE 'schema*';" | grep "schema" | sed -e 's/^/hive -e \"DROP TABLE db\./1' | sed -e 's/$/\"/1' > script.sh
chmod +x script.sh
./script.sh

4

我能够通过以下步骤在Apache Spark中使用Scala删除所有表:

val df = sql("SHOW TABLES IN default LIke 'invoice*'").select("tableName") // to  drop only selected column
val df = sql("SHOW TABLES IN default").select("tableName")
val tableNameList: List[String] = df.as[String].collect().toList
val df2 = tableNameList.map(tableName => sql(s"drop table ${tableName}"))

2

由于我需要删除很多表,所以参考了@HorusH的回答,使用了以下命令:

hive -e "show tables 'table_prefix*'" | sed -e 's/^/ \DROP TABLE db_name\./1' | sed -e 's/$/;/1' > script.sh
hive -f script.sh

0

通过一个shell脚本实现最快的解决方案:

drop_tables.sh pattern

Shell脚本内容:

hive -e 'use db;show tables' | grep $1 | sed 's/^/drop table db./' | sed 's/$/;/' > temp.hql
hive -f temp.hql
rm temp.hql

0

以下命令也可以工作。

 hive -e 'show tables' | grep table_prefix |  while read line; do hive -e "drop table $line"; done

0
尝试这个:
hive -e 'use sample_db;show tables' | xargs -I '{}' hive -e 'use sample_db;drop table {}'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接