Hive中的分区表示什么,我们先看操作,然后再来体会
创建一个分区表,分区的单位时dt和国家名
hive> create table logs(ts bigint,line string) > partitioned by (dt String,country string);
接下来我们创建要给分区
hive> load data local inpath '/root/hive/partitions/file1' into table logs > partition (dt='2001-01-01',country='GB');
上面语句的效果是在hdfs系统上建立了一个层级目录
-logs
-dt=2001-01-01
-country=GB
我们继续执行下面语句,先看一下什么效果
hive> load data local inpath '/root/hive/partitions/file2' into table logs > partition (dt='2001-01-01',country='GB');Loading data to table default.logs partition (dt=2001-01-01, country=GB)OKTime taken: 1.379 secondshive> load data local inpath '/root/hive/partitions/file3' into table logs > partition (dt='2001-01-01',country='US');Loading data to table default.logs partition (dt=2001-01-01, country=US)OKTime taken: 1.307 secondshive> load data local inpath '/root/hive/partitions/file4' into table logs > partition (dt='2001-01-02',country='GB');Loading data to table default.logs partition (dt=2001-01-02, country=GB)OKTime taken: 1.253 secondshive> load data local inpath '/root/hive/partitions/file5' into table logs > partition (dt='2001-01-02',country='US');Loading data to table default.logs partition (dt=2001-01-02, country=US)OKTime taken: 1.07 secondshive> load data local inpath '/root/hive/partitions/file6' into table logs > partition (dt='2001-01-02',country='US');Loading data to table default.logs partition (dt=2001-01-02, country=US)OKTime taken: 1.227 seconds
我们到HDFS上查看,发现建立了下面层级目录
/user/hive/warehouse/logs├── dt=2001-01-01/│ ├── country=GB/│ │ ├── file1│ │ └── file2│ └── country=US/│ └── file3└── dt=2001-01-02/├── country=GB/│ └── file4└── country=US/├── file5└── file6
总结:分区表的意思,其实想明白了就很简单。就是在系统上建立文件夹,把分类数据放在不同文件夹下面,加快查询速度。
关键点1:partitioned by (dt String,country string); 创建表格时,指明了这是一个分区表。将建立双层目录,第一次目录的名字和第二层目录名字规则
PARTITIONED BY子句中定义列,是表中正式的列,成为分区列。但是数据文件中并没有这些值,仅代表目录。
关键点2: partition (dt='2001-01-01',country='GB'); 上传数据时,把数据分别上传到不同分区中。也就是分别放在不同的子目录下。
理解分区就是文件夹分而治之,查询的时候可以当作列名来显示查询的范围。
查看分区结构
hive> show partitions logs;OKdt=2001-01-01/country=GBdt=2001-01-01/country=USdt=2001-01-02/country=GBdt=2001-01-02/country=US
查询数据
条件限定了country='GB'目录所以只有file1,2,4的内容输出
hive> select ts,dt,line > from logs > where country='GB';OK1 2001-01-01 Log line 12 2001-01-01 Log line 24 2001-01-02 Log line 4
现在只查看dt=2001-01-02目录下country=US的文件夹下的数据
hive> select ts,dt,line > from logs> where dt='2001-01-02' > and country='US';OK5 2001-01-02 Log line 56 2001-01-02 Log line 6