1 按时间dt分区创建表
create table test.dm_fz_feature_weight (feature_name string, feature_weight float, website string, warehouse string,
goods_owner string) PARTITIONED BY(dt string) ROW FORMAT DELIMITED FIELDS TERMINATED BY "\t"
2 查看表结构,字段类型等
desc test.dm_fz_feature_weight
3 插入一条测试语句
直接新增插入
insert into test.dm_fz_feature_weight partition(dt="20201030_t") values ("pay_times", 0.327267677, "bd", "Z1", "xx部")
覆盖插入
insert overwrite table test.dm_fz_feature_weight partition(dt="20201030_t") values ("pay_times", 0.327267677, "bd", "Z1", "xx部")
备注:覆盖插入可先查询是否有要覆盖的数据存在,如果存在则使用覆盖插入方法。具体判断代码如下:
注意: 覆盖插入是把分区dt="20201030_t"的所有数据都删除了之后,插入insert语句后面的值。
sel_sql = "select * from test.dm_fz_sales_spu_color where dt='{}' and website='{}' limit 1".format(dt, web_site)
hiveobj.excute_sql(sel_sql)
write_method = 'into'
for list_x in hiveobj.fetchmany():
for _ in list_x:
write_method = 'overwrite table'
break
4 清空表数据
truncate table test.dm_fz_feature_weight
5 删除表
drop table test.dm_fz_feature_weight;
6 给表添加注释
ALTER TABLE 表名 SET TBLPROPERTIES ('comment' = '注释内容')
举个例子:
ALTER TABLE test.dm_fz_feature_weight SET TBLPROPERTIES('comment' = '权重表');
7 给表中的字段名添加注释
ALTER TABLE 表名 CHANGE 列名 新的列名 新列名类型 COMMENT '列注释';
举个例子:
ALTER TABLE test.dm_fz_feature_weight CHANGE inc_5 inc_5 string COMMENT '5日销量增长率';
8 修改字段的数据类型
Alter table 表名 change column 原字段名称 现字段名称 数据类型
举个例子:
Alter table test.dm_fz_inc_sku change column inc_14 inc_14 float
9 新增字段
新增字段表
alter table 表名 add columns(字段名 数据类型)
10 从旧表中筛选数据插入新表中
新建一个具有2个分区的表,分区分别为website,dt
create table test.dm_fz_feature_weight (feature_name string, feature_weight float, warehouse string,
goods_owner string) PARTITIONED BY(website string, dt string) ROW FORMAT DELIMITED FIELDS TERMINATED BY "\t"
将旧表的数据(只有一个分区)查询出来,并插入道新表
insert overwrite table test.dm_fz_feature_weight partition(dt="20201106", website='x') select feature_name, feature_weight , warehouse,
goods_owner from dm_fz.dm_fz_feature_weight where dt='20201106' and website='x'
11 修改hive表的表名
ALTER TABLE test.dm_fz_feature_weight RENAME TO test.dm_fz_feature_weight_new
12 新增字段
alter table table_name add columns(col1 int);
对于有分区的表,需要执行下面的语句,才能保证后面新插入的数据,在新加的字段中不为空
alter table dm_fz.dm_fz_inc_spu_color partition (dt='20201109') add columns(spu string,color string);
这样,之前的分区这两个新增字段值是空值,但是往后的分区新加字段是有值的
本文详细介绍了Hive中的数据表操作,包括创建分区表、查看表结构、插入数据、清空表、删除表、添加注释、修改字段类型以及处理分区表。通过实例展示了如何进行覆盖插入、查询是否存在数据、新增字段以及从旧表导入新表等操作。此外,还涵盖了修改表名和处理分区字段的方法。

574

被折叠的 条评论
为什么被折叠?



