首页 > 解决方案 > 如何在java中获取原始对象检查器的字段名称

问题描述

我正在尝试为我为 hiveql 环境创建的 UDF 解决这个问题。

public ObjectInspector initialize(ObjectInspector[] arguments)
            throws UDFArgumentException {
    if (arguments.length != 1) {
        throw new UDFArgumentException("Usage : multiple_prop(primitive var) ");
    }
    // This will be an string
    moi = (PrimitiveObjectInspector) arguments[0];

    ArrayList structFieldNames = new ArrayList();
    ArrayList structFieldObjectInspectors = new ArrayList();

    structFieldNames.add("fields name"); <-- Issue is here

我该怎么做才能在其中获取字段名称?它可以很容易地完成structObjectInspectors,但我们如何管理PrimitiveObjectInspectors呢?

完整的代码就是这个

public class prop_step2 extends GenericUDF {
    private PrimitiveObjectInspector moi;
    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments)
            throws UDFArgumentException {
        if (arguments.length != 1) {
            throw new UDFArgumentException("Usage : multiple_prop(primitive var) ");
        }
        // This will be an string
        moi = (PrimitiveObjectInspector) arguments[0];

        ArrayList structFieldNames = new ArrayList();
        ArrayList structFieldObjectInspectors = new ArrayList();
        // Change this to get the input variable name, and not the type name
        structFieldNames.add(moi.getTypeName());<-- Change this to field name
        structFieldObjectInspectors.add( PrimitiveObjectInspectorFactory.writableStringObjectInspector );

       return ObjectInspectorFactory.getStandardStructObjectInspector(structFieldNames, structFieldObjectInspectors);
    }

    @Override
    public Object evaluate(DeferredObject[] arguments) throws HiveException {
        Object[] result;
        result = new Object[1];
        Text elem1 = new Text((String) moi.getPrimitiveJavaObject(arguments[0].get()));
        result[0]= elem1;
        return result;
    }
    @Override
    public String getDisplayString(String[] children) {
        return "stop";
    }}

当这完成时,我想从 hive 调用这个 udf:

CREATE TEMPORARY FUNCTION step AS 'UDFpack.prop_step2';
select 
step(bit) as sd
from my_table

我希望如果在上层选择中我这样做:sd.bit 我将获得“位”的值。

标签: javahiveuser-defined-functionshiveqlobject-inspector

解决方案


这根本不可能。传递给 UDF(ObjectInspectors)的信息不包含它们的名称。这就是为什么您可以在 Hive 解释计划的中间阶段看到输出列名称更改为 _col0、_col1 .. 的原因。我对此也很恼火,并认为这是 Hive 的疏忽。

一种解决方法是将您的输入放入一个结构并解析它。

即 step(named_struct('bit',bit)) 然后您可以在 UDF 中获取结构的字段名称。但它几乎没有那么好


推荐阅读