我在 hive 中有几个表具有相同的前缀,如下所示。
temp_table_name
temp_table_add
temp_table_area
在我的数据库中,像这样的表以及许多其他表很少有数百个。我想删除以"temp_table"开头的表。你们中有人知道可以在 Hive 中完成这项工作的任何查询吗?
在 hive 中没有用于放置查询的正则表达式这样的东西(或者我没有找到它们)。但是有多种方法可以做到这一点,例如:
-
使用外壳脚本:
hive -e "show tables 'temp_*'" | xargs -I '{}' hive -e 'drop table {}'
-
或者将表放在特定的数据库中并删除整个数据库。
Create table temp.table_name; Drop database temp cascade;
以上解决方案很好。但是,如果要删除更多表,则运行"hive -e 删除表"会很慢。所以,我用了这个:
hive -e 'use db;show tables' | grep pattern > file.hql
使用 vim 编辑器打开 file.hql 并运行以下命令
:%s!^!drop table
:%s!$!;
然后运行
hive -f file.hql
这种方法会快得多。
我的解决方案是使用以下cmd的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
我能够在带有 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}"))
由于我有很多表格确实掉落了,我使用了以下命令,灵感来自@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
试试这个:
hive -e 'use sample_db;show tables' | xargs -i '{}' hive -e 'use sample_db;drop table {}'
下面的命令也可以工作。
hive -e 'show tables' | grep table_prefix | while read line; do hive -e "drop table $line"; done
通过一个 shell 脚本的最快解决方案:
drop_tables.sh pattern
外壳脚本内容:
hive -e 'use db;show tables' | grep $1 | sed 's/^/drop table db./' | sed 's/$/;/' > temp.hql
hive -f temp.hql
rm temp.hql