最近在做数据的去重,想到一种类似于关系型数据库rank函数的方式,即获取topN(N=1)的方式,sql步骤如下:
1.数据分组,组内排序
2.对分组数据进行标记rank
3.获取rank<N的数据
hive udf
hive中没有这种函数,需要自己编写udf函数,代码如下:
public final class TradeUDF extends UDF { private int counter; private String last_dp_id; private String last_tid; //多参数 public int evaluate(String dp_id, String tid) { if (dp_id.equalsIgnoreCase(this.last_dp_id) && tid.equalsIgnoreCase(this.last_tid)) { this.counter++; }else{ this.counter = 0; this.last_dp_id = dp_id; this.last_tid = tid; } return this.counter; } //一个参数 public int evaluate(final String tid) { if (!tid.equals(this.last_tid)) { this.counter = 0; this.last_tid = tid; } return this.counter++; } }
小函数据量测试
select * from test2; OK a 1 a 4 a 6 b 87 b 3 b 100 c 10 d 90 d 9 a 3 a 3
SELECT a,b,rank FROM (SELECT a,b,rank(a) rank FROM (SELECT a,b FROM test2 DISTRIBUTE BY a SORT BY b desc ) t1) t2 WHERE rank <1
结果:
d 90 0 a 6 0 b 87 0 c 10 0
可以看到数据是准确的。
大数据来量测试
数据总量:5033768
重复数据:2516884,即一半是重复数据
结果:
4194632
可以看到数据量是不对的。
原因
大数据量时,rank方式去重数据结果不准确的原因还未确定,推测原因是:
distribute sort后相同数据被分在不同数据块中,在接下来sql读取的时候,相同数据没有被读进同一个rank函数。