hive中udf例子

hive中自带了一下函数,但是平常开发中可能需要专门开发一下函数来应对特定的需求,下面写一个udf的例子。

udf是对输入的每行的一列或多个列的值进行计算,并返回值。

导入hive-exec-0.10.0.jar

继承UDF类,重写evaluate方法。

下面实现一个类似oracle中row_number() 的类

/**
 * 实现类似oracle中row_number()函数的功能
 * oracle:  select row_number() over (partition by col1 order by col2) from table;
 * hive:  select row_number(col1) from (select * from table distribute by col1 sort by col1,col2) a;
 * @author twtbgn
 *
 */
public class RowNumber extends UDF{

	String[] lastColumn = new String[50];
	int rownum = 1;
	public int evaluate (String ...args){
		String[] columnValues = new String[args.length];
		for(int i = 0; i < args.length; i++){
			columnValues[i] = args[i];
		}
		if(rownum == 1){
			for(int i = 0; i < args.length; i++){
				lastColumn[i] = columnValues[i];
			}
		}else{
			for(int i = 0; i < args.length; i++){
				if(!columnValues[i].equals(lastColumn[i])){
					for(int j = 0; j < args.length; j++){
						lastColumn[j] = columnValues[j];
					}
					rownum = 1;
					break;
				}
			}
		}
		
		return rownum++;
	}
}

 

在hive的shell中:
hive> add jar /home/hadoop/hive/jar/hive_rownumber.jar;
hive> create temporary function row_number as 'hive.udf.RowNumber';
hive> select row_number(col1), col1, col2
       > from (select col1,col2  from table distribute by col1 sort by  col1, col2) a;

hive> drop temporary function row_number;

 

你可能感兴趣的:(hive)