spark检查hive表中是否存在某一分区

hive表分区的概念

  1. 一个表可以拥有一个或者多个分区,每个分区以文件夹的形式单独存在表文件夹的目录下。

例如下图中xx.db(数据库),device_flow_report_data(表)

  • month_id=201902:表示按月进行了分区
  • day_id=20190203:表示按天也进行了分区
    spark检查hive表中是否存在某一分区_第1张图片
    spark检查hive表中是否存在某一分区_第2张图片
  1. 分区是以字段的形式在表结构中存在,通过describe table命令可以查看到字段存在, 但是该字段不存放实际的数据内容,仅仅是分区的表示(伪列)

例如:

describe device_flow_report_data;
id	bigint	NULL
....
month_id	string	NULL
day_id	string	NULL
# Partition Information		
# col_name	data_type	comment
month_id	string	NULL
day_id	string	NULL
Time taken: 0.173 seconds, Fetched 21 row(s)
小结:既然分区是以字段在表结构的中存在,那么就可以使用 where进行sql查询

解决检查hive表中是否存在某一分区

  1. 直接sql 查询表中是否存在该分区
	# 查询日分区是否存在
    show partitions device_flow_report_data partition(day_id=20190204)
    # 查询月分区是否存在
    show partitions device_flow_report_data partition(month_id=201902)
  1. 基于where,查询该分区下记录数
# 查询月分区是否存在
select count(*) from device_flow_report_data where month_id = 201902
# 查询日分区是否存在
select count(*) from device_flow_report_data where day_id = 20190204

参考:https://stackoverflow.com/questions/11700127/how-to-select-data-from-hive-with-specific-partition

基于spark的scala实现

val numsInHive = hiveContext.sql(s"select count(*) from ${databaseName}.${TableName} " +
          s"where day_id=${detectDay}").collect()(0).getLong(0)
if (numsInHive == 0) {
// 不存在该分区
// ....
}else{
// 存在该分区
// ....
}

参考:
https://www.cnblogs.com/xiohao/p/6429305.html
https://stackoverflow.com/questions/46477270/spark-scala-how-can-i-check-if-a-table-exists-in-hive
https://stackoverflow.com/questions/11700127/how-to-select-data-from-hive-with-specific-partition
https://stackoverflow.com/questions/43086158/how-to-check-whether-any-particular-partition-exist-or-not-in-hive

你可能感兴趣的:(大数据开发,spark,hive,partitions)