首页 > 解决方案 > Hive 外部表的自动列表

问题描述

我必须创建一个自动化流程来列出 Hive 中的所有外部表并对这些表进行记录计数。

我应该将其作为日常工作。我通过对所有外部表名称进行硬编码来尝试此操作,但这不被接受,因为表每月会不断更改一次。

我经历了不同的方法,例如[show tables]在 Metastore DB 中执行查询。但这些不会帮助我自动化这个过程。

有没有更好的方法在 Hive 中实现这一点。

标签: hivehiveqlexternal-tables

解决方案


像这样的东西,使用外壳。

#Create external table list for a schema
SCHEMA=your_schema_name 

#define filenames   
alltableslist=tables_$SCHEMA
exttablelist=ext_tables_$SCHEMA

#Get all tables
 hive -S -e " set hive.cli.print.header=false; use $SCHEMA; show tables;" 1> $alltableslist


#For each table check its type:
for table in $(cat $alltableslist)
 do 

 echo Processing table $table ...

     #Describe table
     describe=$(hive client -S -e "use $SCHEMA; DESCRIBE FORMATTED $table")

     #Get type
     table_type=$(echo "${describe}" | egrep -o 'Table Type:[^,]+' | cut -f2)

     #Check table type, get count and write table name with count
      if [ $table_type == EXTERNAL_TABLE ]; then 
         #get count
          cnt=$(hive client -S -e "select count(*) from $SCHEMA.table ")
         #save result
          echo "$table $cnt" > $exttablelist 
      fi

done; #tables loop

只需your_schema_name在开头替换为您的架构名称即可。此示例中带有计数的外部表将保存在文件中ext_tables_[your_schema_name]

计数可以并行处理,甚至可以在单个 SQL 语句中处理,并且可以改进许多其他事情,但希望您已经掌握了这个想法。


推荐阅读