hive中生成从1到n的连续数字的UDTF方法

之前在博客中分享了个生成从1到n的连续数字的transform或map方法,最近研究了一下UDTF,发现用UDTF写出来的函数用起来更方便,语法更接近于普通的函数。而且在JAVA中对参数的个数、类型等进行校验也更容易。

 

ORACLE中生成从1到n的连续数字的方法很多,最简单的一种是:

select level from dual connect by level<=5;

        LEVEL
----------
                  1
              2
              3
              4
              5
 
使用UDTF写出来的函数进行查询:
hive> select serial(5) as col1 from dual;
OK
1
2
3
4
5
 
或者使用lateral view进行查询:
hive> select T.col1 from dual lateral view serial(5) T as col1;
OK
1
2
3
4
5
 
提供一下java代码,仅供参考:
 
package com.hadoopbook.hive;
import java.util.ArrayList;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthExcepti on;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspector Factory;
public class UDTFSerial extends GenericUDTF {
 
   Object[] result = new Object[1];
 
   @Override
   public void close() throws HiveException {
   }
 
   @Override
   public StructObjectInspector initialize(ObjectInspector[] args)
                   throws UDFArgumentException {
           if (args.length != 1) {
                   throw new UDFArgumentLengthExcepti on("UDTFSerial takes only one argument");
           }
           if (!args[0].getTypeName().equals("int")) {
            throw new UDFArgumentException("UDTFSerial only takes an integer as a parameter");
               }
           ArrayList<String> fieldNames = new ArrayList<String>();
           ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
           fieldNames.add("col1");
           fieldOIs.add(PrimitiveObjectInspector Factory.javaIntObjectInspector);
         
           return ObjectInspectorFactory.getStandardStructObjectI nspector(fieldNames,fieldOIs);
   }
 
   @Override
   public void process(Object[] args) throws HiveException {
     try
     {
       int n = Integer.parseInt(args[0].toString());
       for (int i=0;i<n;i++)
       {
         result[0] = i+1;
         forward(result);
       }
     }
     catch (Exception e) { 
       throw new HiveException("UDTFSerial has an exception");
     }
   }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值