Hive的UDTF

Refer to:http://blog.csdn.net/wf1982/article/details/7623708 

 

1.介绍 

UDTF(User-Defined Table-Generating Functions)  用来解决 输入一行输出多行(On-to-many maping) 的需求。同时,也可以解决一列拆分成多列的问题(Hive支持复杂的数据格式,包括List)。

 

2.编写需要的UDTF

1) 继承org.apache.hadoop.hive.ql.udf.generic.GenericUDTF。
2) 实现initialize, process, close三个方法
3) UDTF首先会调用initialize方法,此方法返回UDTF的返回行的信息(返回个数,类型)。
初始化完成后,会调用process方法,对传入的参数进行处理,可以通过forword()方法把结果返回。
最后close()方法调用,对需要清理的方法进行清理。

 

这是一个用来切分 key:value;key:value 这种字符串,返回结果为key, value两个字段。

import java.util.ArrayList;

import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
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.PrimitiveObjectInspectorFactory;

public class ExplodeMap extends GenericUDTF{

    @Override
    public void close() throws HiveException {
        // TODO Auto-generated method stub    
    }

    @Override
    public StructObjectInspector initialize(ObjectInspector[] args)
            throws UDFArgumentException {
        if (args.length != 1) {
            throw new UDFArgumentLengthException("ExplodeMap takes only one argument");
        }
        if (args[0].getCategory() != ObjectInspector.Category.PRIMITIVE) {
            throw new UDFArgumentException("ExplodeMap takes string as a parameter");
        }

        ArrayList<String> fieldNames = new ArrayList<String>();
        ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
        fieldNames.add("col1");
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        fieldNames.add("col2");
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames,fieldOIs);
    }

    @Override
    public void process(Object[] args) throws HiveException {
        String input = args[0].toString();
        String[] test = input.split(";");
        for(int i=0; i<test.length; i++) {
            try {
                String[] result = test[i].split(":");
                forward(result);
            } catch (Exception e) {
                continue;
            }
        }
    }
}

 

 3. 使用方法

UDTF有两种使用方法,一种直接放到select后面,一种和lateral view一起使用。

1) 直接select中使用:select explode_map(properties) as (col1,col2) from src;

 不可以添加其他字段使用:select a, explode_map(properties) as (col1,col2) from src
 不可以嵌套调用:select explode_map(explode_map(properties)) from src
 不可以和group by/cluster by/distribute by/sort by一起使用:select explode_map(properties) as (col1,col2) from src group by col1, col2

 

2) 和lateral view一起使用:
  select src.id, mytable.col1, mytable.col2 from src lateral view explode_map(properties) mytable as col1, col2;
  此方法更为方便日常使用。执行过程相当于单独执行了两次抽取,然后union到一个表里。

 

4. 参考文档
    http://wiki.apache.org/hadoop/Hive/LanguageManual/UDF

    http://wiki.apache.org/hadoop/Hive/DeveloperGuide/UDTF

    http://www.slideshare.net/pauly1/userdefined-table-generating-functions

 

Appendix:

一个用于将字符串拆分成多个字段的:

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
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.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableConstantIntObjectInspector;

/**
 * GenericUDTFRD: this
 * 
 */
@Description(name = "tr_rd", value = "_FUNC_(x)")
public class GenericUDTFRD extends GenericUDTF {

	private static Log LOG = LogFactory.getLog(GenericUDTFRD.class.getName());

	@Override
	public void close() throws HiveException {
	}

	@Override
	public StructObjectInspector initialize(ObjectInspector[] args)
			throws UDFArgumentException {
		LOG.debug("========================initialize");
		LOG.debug("args.length" + args.length);
		if (args.length != 2) {
			throw new UDFArgumentLengthException(
					"ExplodeMap takes only two argument");
		}

		WritableConstantIntObjectInspector x = (WritableConstantIntObjectInspector) args[1];
		int numCols = x.getWritableConstantValue().get();
		LOG.debug("numCols:" + numCols);
		// construct output object inspector
		ArrayList<String> fieldNames = new ArrayList<String>(numCols);
		ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>(
				numCols);
		for (int i = 0; i < numCols; ++i) {
			fieldNames.add("c" + i);
			fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
		}
		return ObjectInspectorFactory.getStandardStructObjectInspector(
				fieldNames, fieldOIs);
	}

	@Override
	public void process(Object[] o) throws HiveException {
		LOG.debug("========================process");
		String input = o[0].toString();
		//字段分隔符
		String[] test = input.split("\t");
		LOG.debug("input:" + input);
		LOG.debug("test:" + test);
		for(int i=0;i<test.length;i++){
			if("".equals(test[i])||null==test[i]){
				test[i]="\\N";
			}
		}
		forward(test);
	}

	@Override
	public String toString() {
		return "tr_rd";
	}
}

 

用法是:

--将一个字段,拆分成3个。
select tr_rd(tt.col1,3) as (c1,c2,c3)
from table tt

 

 

 

你可能感兴趣的:(hive,UDTF)