Home  >  Article  >  Database  >  Hive的UDF实现类似于Oracle的decode函数功能

Hive的UDF实现类似于Oracle的decode函数功能

WBOY
WBOYOriginal
2016-06-07 16:48:002697browse

Oracle的decode函数语法:DECODE(value,if1,then1,if2,thne2,if3,then3,...else)。首先涉及到的问题是输入参数的动态化,decode函

客户提的要求,让用hive实现类似orale的decode函数功能。好吧,开工。

Oracle的decode函数语法:DECODE(value,if1,then1,if2,thne2,if3,then3,...else)。

首先涉及到的问题是输入参数的动态化,decode函数要求输入函数是偶数个,然后实现类似if,else的逻辑判断功能。这样的话用到了java的Object ... args 来传入多个参数,然后在方法中检测个数是否符合偶数个。选用Object类型的原因就是为了参数类型的动态识别。

为了实现对decode(1,1.0,'a',2.0,'b','c')的判断类型,需要将Integer类型的转换为double类型,不然的话这样的内容就无法实现。用instanceof 检测输入的参数类型,,来判断。

相关阅读:

基于Hadoop集群的Hive安装

Hive内表和外表的区别

Hadoop + Hive + Map +reduce 集群安装部署

Hive本地独立模式安装

Hive学习之WordCount单词统计

-------------------------------分割线-------------------------------

import org.apache.hadoop.hive.ql.exec.UDF;

public class Decode extends UDF {

 public String evaluate(Object... args) {
  if (args.length % 2 != 0) {
   System.out.println("输入的参数个数错误,应为偶数");
  }
  int number = args.length;
  Object result = null;
  int flag = number - 1;

  int i = 1;

  if (args[0] instanceof Integer) {
   args[0] = Double.valueOf(Integer.valueOf(args[0].toString()));
  }
  while (i

   if (args[i] instanceof Integer) {
    args[i] = Double.valueOf(Integer.valueOf(args[i].toString()));
   }

   if (String.valueOf(args[i]).equals(String.valueOf(args[0]))) {
    result = args[i + 1];
    break;
   } else {
    i += 2;
   }
  }
  if (result == null)
   result = args[flag];

  return String.valueOf(result);
 }
}

Hive 的详细介绍:请点这里
Hive 的下载地址:请点这里

本文永久更新链接地址:

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn