Hadoop MapReduce - 如何创建动态分区

Hadoop MapReduce - How to create dynamic partition

如何使用 java map reduce 创建动态分区,就像 sql 我们有按国家/地区列分组的方法。示例我有基于国家/地区的数据集,需要根据国家/地区(分区)分隔记录。我们不能限制国家。因为每天都会获得新的国家/地区数据。

您可以利用 dynamic partitioning feature of Hive 根据传入数据自动填充分区。下面的示例演示了基于 country 信息的原始数据自动分区。

创建一个原始数据文件 (country1.csv),其中包含多个国家/地区的数据

1,USA
2,Canada
3,USA
4,Brazil
5,Brazil
6,USA
7,Canada

将此文件上传到 HDFS 中的某个位置

hadoop fs -mkdir /example_hive
hadoop fs -mkdir /example_hive/country
hadoop fs -put country1.csv /example_hive/country

在数据之上创建一个未分区的 Hive table

CREATE EXTERNAL TABLE country
(
id int, 
country string
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
LOCATION 'hdfs:///example_hive/country';

验证是否正确创建了 Hive table

hive (default)> select * from country;
1   USA
2   Canada
3   USA
4   Brazil
5   Brazil
6   USA
7   Canada

创建分区 Hive table,以国家/地区为分区

hive (default)> CREATE TABLE country_par
(
id int
)
PARTITIONED BY (country string);

启用动态分区

hive (default)> SET hive.exec.dynamic.partition = true;
hive (default)> SET hive.exec.dynamic.partition.mode = nonstrict;

填充分区 table,Hive 自动将数据放入正确的国家/地区分区

hive (default)> INSERT INTO TABLE country_par 
PARTITION(country)
SELECT id,country FROM country;

验证分区是否已创建并正确填充

hive (default)> show partitions country_par;
country=Brazil
country=Canada
country=USA

hive (default)> select * from country_par where country='Brazil';
4   Brazil
5   Brazil

hive (default)> select * from country_par where country='USA';
1   USA
3   USA
6   USA

hive (default)> select * from country_par where country='Canada';
2   Canada
7   Canada

hive (default)> select country,count(*) from country_par group by country;
Brazil  2
Canada  2
USA 3