Shell 获取Hive表的location 信息

发布于:2024-07-04 ⋅ 阅读:(14) ⋅ 点赞:(0)

用shell 获取建表语句:

hive -e "show create table ods_job.ods_job_tb"

得到结果:

CREATE TABLE `ods_job.ods_job_tb`(
  `id` bigint COMMENT 'id', 
  `auto` int COMMENT 'job开启/关闭:0-关闭;1-开启', 
 ....
  `timeout_kill` string COMMENT '是否超时kill')
COMMENT 'job表'
PARTITIONED BY ( 
  `d` string COMMENT '日期分区字段')
ROW FORMAT SERDE 
  'org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe' 
STORED AS INPUTFORMAT 
  'org.apache.hadoop.hive.ql.io.RCFileInputFormat' 
OUTPUTFORMAT 
  'org.apache.hadoop.hive.ql.io.RCFileOutputFormat'
LOCATION
  'hdfs://ns/user/hive/warehouse/job.db/job_tb'
TBLPROPERTIES (
  'last_modified_by'='user', 
  'last_modified_time'='1656303639', 
  'metadata.partition.life'='-1', 
  'metadata.security.level'='Medium', 
  'orc.bloom.filter.columns'='id,visitor_id,auto,owner,group_id', 
  'spark.sql.partitionProvider'='catalog', 
  'transient_lastDdlTime'='1706259083')
Time taken: 1.343 seconds, Fetched: 57 row(s)

想要获取LOCATION 引号里面的值,并实现自动化

tardb=$1
tarTblname=$2
stmt=`hive-sql -v -e "use ${tardb}; show create table ${tarTblname};"`
loc=$( expr "${stmt}" : ".*LOCATION...'\([^']*\)" );

echo $loc

loc变量就是想要的结果,这个shell稍微难写一点的就是里面的正则,还得过滤掉引号。
方式2, 这种会有点瑕疵,一旦表中有location 字段就有可能会产生bug,而上面就不会出现这种问题

#!/bin/bash

# 替换为你的 Hive 表名
table_name="db.table"

# 使用 Hive 命令获取表的详细信息,并通过 grep 筛选出包含 "Location" 的行
location_info=$(hive -e "describe formatted $table_name" | grep "Location")

# 提取出具体的 location 值
location=$(echo $location_info | awk '{print $2}')

echo "表 $table_name 的 location 信息为: $location"

推荐还是使用方法1
小记~