One, de-duplicate hive table data
1. Copy the table structure
CREATE TABLE <new_table> LIKE <old_table>;
2. Insert the data after deduplication
insert overwrite table <new_table>(
select t.id, t.local_path
from (
select
id, local_path, row_number() over(distribute by id sort by local_path) as rn
from <old_table>
) t where t.rn=1
);
The structure is as follows
insert overwrite table <new_table> (
select <字段>
from (
select <字段>, row_number() over(distribute by <有重复的字段> sort by <重复字段的排列根据字段>) as rn
from <old_table>
) t where t.rn=1
);
You can also directly insert into the original table without creating a new table and update directly
3. De-duplication of partition table
#hive数据去重
#获取表头
fieldsTmp=$(hive -e "SET hive.cli.print.header=true;select * from ${dbname}.${table_name} limit 0;" | sed -e "s/\t/,/g;s/data\.//g" | grep -v "WARN")
fields2=${fieldsTmp//,${table_name}.dt/}
fields=${fields2//${table_name}./}
hive -e "
use $dbname;
insert overwrite table $table_name partition(dt=$date_slice) select $fields from (select $fields,row_number() over(distribute by $tab_primarykey sort by $key_code desc)as rn from $table_name)t where t.rn=1"
The variables that need to be assigned in the sample code are as follows
${dbname}: database name
${table_name}: table name
${date_slice}: partition value
${tab_primarykey}: There are duplicate fields
${key_code}: The arrangement of repeated fields is based on the field
fields2=${fieldsTmp//, dt in ${table_name}.dt/} is your partition field
2. Take out the field name of the hive table in the script
#存储到文本
hive -e "SET hive.cli.print.header=true;select * from dbname.tablename limit 0;" | sed -e "s/\t/,/g;s/data\.//g" | grep -v "WARN" > fileds.csv
#赋值给变量
fields=$(hive -e "SET hive.cli.print.header=true;select * from dbname.tablename limit 0;" | sed -e "s/\t/,/g;s/data\.//g" | grep -v "WARN")
Get the field names of the hive table separated by commas
Three, save the hive query results to the local or hdfs
Save hive query results to local
hive -e "use test;insert overwrite local directory '/tmp/score' ROW FORMAT DELIMITED FIELDS TERMINATED BY',' select * from student"
To save to hdfs, you only need to remove local from the above command.