Hive UDF 不返回预期结果

Posted

技术标签:

【中文标题】Hive UDF 不返回预期结果【英文标题】:Hive UDF does not return expected result 【发布时间】:2013-12-13 11:22:56 【问题描述】:

我写了一个可以被 Hive(查询语言)调用的 UDF,它接受 2 个参数并具有以下逻辑:

如果两个参数都为 null,则返回 null 如果一个参数为空,则返回非空值 如果传入的参数都不为空,则返回两个值中的较大者

我已经编写了代码,编译了类,并成功地将 JAR 注册到了 Hive。我验证创建临时函数后我可以在 HIVE 中看到该函数。我遇到的问题是,当我从选择中调用它时,它只返回“_c0”而不是预期值:

这里是java类的定义。

package com.ispace.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.exec.Description;
import java.util.*;
/*
*
* Compilation on Local box is very environment specific but for the iMac in 2013, this command will compile the class:
* javac -target 1.6 -cp $(ls /usr/local/Cellar/hive/0.12.0/libexec/lib/hive-exec*.jar):/usr/local/Cellar/hadoop/1.2.1/libexec/lib/hadoop-core.jar com/ispace/hive/udf/GreaterOf.java
* 
* The above step creates a single .class file that needs to be bundled into a JAR (java archive file)
* To bundle a file or multiple files into a jar, you can run this:
*       jar cvf udfcomparer.jar ./com/ispace/hive/udf/GreaterOf.class ./com/ispace/hive/udf/LesserOf.class
*
* To call a UDF, you must add the JAR to your hive session and then create a 'temporary'function as follows:
*
* hive (default)> ADD JAR /Users/calvinimac/Documents/Safezone/Projects/prospect-visual/etl/scripts/ec2-emr/jars/udfcomparer.jar;            
* hive (default)> create temporary function inlinemax as 'com.ispace.hive.udf.GreaterOf';
*/

@Description(name = "GreaterOf",
             value = "_FUNC_(Integer s, Integer t) - returns the greater value of the two.\n"+
                        "If both values are null, it will return NULL.\n"+
                        "If one value is non null, it will return that value if the other is NULL.",
             extended = "Example:\n"
                    + " > SELECT _FUNC_(column1, column2) FROM src;")

public final class GreaterOf extends UDF 
  public Integer evaluate(final Integer s, final Integer t) 
    Integer result = null;

    if (s == null && t == null)  
        result = null; 
     else if (s == null) 
        result = t;
     else if (t == null) 
        result = s;
     else if (s >= t) 
        result = s;
     else 
        result = null;   
    

    return result;
  

在 Hive 中,我创建了一个占位符表(未使用) 创建未使用的表(id bigint) 然后我运行这个选择: 从未使用中选择 inlinemax(2,4)

我希望得到 4 的结果,但结果却是 'c0'。

我的 UDF 是否错误,它会将 Hive 空值作为参数处理并将它们正确映射到我的 Integer 方法参数中吗?

【问题讨论】:

【参考方案1】:

未使用的有任何行吗???看起来“_c0”是 Hive 生成​​的派生列名称。要获取任何行,您的查询表中至少需要一行。

【讨论】:

嗨杰罗姆,是的,你是正确的,因为桌子是空的。我读到 Hive 并不关心表的真正含义并做出了推断,因为该表是任意的,它也可能是空的。将查询更改为包含记录的填充表后,我得到了预期的结果。非常感谢您的见解!【参考方案2】:

正如 Jerome 所说,只要表(尽管是任意的)至少有一行数据,java UDF 确实会返回预期结果。

【讨论】:

以上是关于Hive UDF 不返回预期结果的主要内容,如果未能解决你的问题,请参考以下文章

Hive 宏未返回预期结果

参数为空时,Spark Scala UDF 不返回预期值

Hive 中的左连接未返回预期结果

Hive UDF 返回多列输出

在 HIVE UDF 中返回 ArrayList<String>

自动增量 UDF 在 hive 中工作,但在 Impala 中返回 null