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

Dropping multiple tables with same prefix in Hive

我在配置单元中有几个表具有如下相同的前缀..

temp_table_name
temp_table_add
temp_table_area

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

在配置单元中没有用于删除查询的正则表达式(或者我没有找到它们)。但是有多种方法可以做到这一点,例如:

  • 使用 shell 脚本:

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

    Create table temp.table_name;
    
    Drop database temp cascade;
    

试试这个:

配置单元-e 'use sample_db;show tables' | xargs -I '{}' 配置单元 -e 'use sample_db;drop table {}'

我的解决方案是通过以下命令使用 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

下面的命令也可以。

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

因为我删除了很多表,所以我使用了以下命令,灵感来自@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

以上解决方案都很好。但是如果你有更多的表要删除,那么 运行ning 'hive -e drop table' 就很慢了。所以,我用了这个:

hive -e 'use db;show tables' | grep pattern > file.hql

使用vim编辑器打开file.hql和运行命令

:%s!^!drop table  
:%s!$!;

然后 运行

hive -f file.hql

这种方法会快得多。

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

drop_tables.sh pattern

Shell脚本内容:

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

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

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}"))