引言
欢迎转载,请注明来源:
代码
曾经认为Hive自带的函数应该可以cover住我的日常所需,心想那些需要使用自定义函数的场景是不是太奇葩,谁知命运弄人,自己还是碰上了。
需求很简单,我需要模拟Oracle中的SYS_GUID()函数,生成一个32位的字母数字随机串。
开发环境:Eclipse+Maven,引入Hive0.13.1的依赖。
欢迎转载,请注明来源:
http://blog.csdn.net/u010967382/article/details/41083617
代码
package cn.fulong.bigdata.tools;
import java.util.Random;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.udf.UDFType;
import org.apache.hadoop.io.Text;
@UDFType(deterministic = false)
public class HiveUDFOracleSysguid extends UDF {
private Random random = new Random();
private Text result = new Text();
public Text evaluate(int length) {
result.set(getCharAndNumr(length));
return result;
}
private String getCharAndNumr(int length) {
StringBuffer val = new StringBuffer();
for (int i = 0; i < length; i++) {
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字
if ("char".equalsIgnoreCase(charOrNum)) // 字符串
{
int choice = 65; // 大写字母65,小写字母96
val.append((char) (choice + random.nextInt(26)));
} else if ("num".equalsIgnoreCase(charOrNum)) // 数字
{