import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
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.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
public class GenericUDTFGetNameAndAge extends GenericUDTF {
@Override
public StructObjectInspector initialize(ObjectInspector[] argOIs) throws UDFArgumentException {
if (null != argOIs && argOIs.length == 1) {
if (argOIs[0].getCategory() != ObjectInspector.Category.PRIMITIVE) {
throw new UDFArgumentException("该函数只能接收简单类型的参数!");
}
if (!argOIs[0].getTypeName().toUpperCase().equals(PrimitiveObjectInspector.PrimitiveCategory.STRING.name())) {
throw new UDFArgumentException("该函数只能接收String类型的参数!");
}
}else {
throw new UDFArgumentException("该函数需要接收参数,且只接收一个参数!");
}
List<String> structFieldNames = new ArrayList<String>();
structFieldNames.add("name");
structFieldNames.add("age");
List<ObjectInspector> structFieldObjectInspectors = new ArrayList<ObjectInspector>();
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableIntObjectInspector);
return ObjectInspectorFactory.getStandardStructObjectInspector(structFieldNames, structFieldObjectInspectors);
}
private Object[] out = {new Text(),new IntWritable()};
private String[] strs1 = null;
private String[] strs2 = null;
@Override
public void process(Object[] args) throws HiveException {
String param = String.valueOf(args[0]);
strs1 = param.split(";");
for (String str : strs1) {
strs2 = str.split(":");
((Text)out[0]).set(strs2[0]);
((IntWritable)out[1]).set(Integer.parseInt(strs2[1]));
this.forward(out);
}
}
@Override
public void close() throws HiveException {
}
}