Oracle的分析函数row_number是十分有用的功能,但是將ETL迁移到Hive中发现没有的功能,我们实现了一个UDF实现了该函数,代码如下:
package com.tudou.hive.func;
import org.apache.hadoop.hive.ql.exec.UDF;
public class RowNumber extends UDF {
private static int MAX_VALUE = 50;
private static String comparedColumn[] = new String[MAX_VALUE];
private static int rowNum = 1;
public int evaluate(Object... args) {
String columnValue[] = new String[args.length];
for (int i = 0; i < args.length; i++){
columnValue[i] = args[i].toString();
}
if (rowNum == 1) {
for (int i = 0; i < columnValue.length; i++)
comparedColumn[i] = columnValue[i];
}
for (int i = 0; i < columnValue.length; i++) {
if (!comparedColumn[i].equals(columnValue[i])) {
for (int j = 0; j < columnValue.length; j++) {
comparedColumn[j] = columnValue[j];
}
rowNum = 1;
return rowNum++;
}
}
return rowNum++;
}
}
Hive应用:
hive>add jar /home/work/local/hive/udf/row_number.jar;
create temporary function row_number as 'com.baifendian.hive.udf.RowNumber';
select *,row_number(col1,col2,col3)
from (
select col1,col2,col3
from tab
order by col1,col2,col3)a;