自定义UDF

1、编写udf类
  1. package hive.udf;
  2. import org.apache.hadoop.hive.ql.exec.Description;
  3. import org.apache.hadoop.hive.ql.exec.UDF;
  4. /**
  5. * UDF的说明文档
  6. * name是UDF的名称
  7. * value是desc function xx输出的内容
  8. * extended是desc function extended xx输出的内容
  9. *
  10. */
  11. @Description(name="uppernum",
  12. value="_FUNC_ the input is a num, the output is the UpperNum",
  13. extended="Example: " +
  14. "> select uppernum(1) from src ")
  15. public class UpperNumUDF extends UDF {
  16. /**
  17. * UDF类需要自定义evaluate方法,可以重载多个
  18. *
  19. * evaluate的参数、返回值必须是hive可以序列化的类型
  20. *
  21. * 参数:
  22. * 1)可以是java基本类型、String
  23. * 2)可以是Text
  24. * 3)可以包含多个参数,参数类型也可以不同
  25. * 4)可以是List<?>。如果hive表字段是Array<?>类型的,则是List
  26. *
  27. * 返回值:
  28. * 1)必须有返回值,可以为null
  29. * 2)返回值只能是java基本类型、String、Writable
  30. *
  31. * 可以自定义 UDFMethodResolver来手动匹配方法的执行
  32. *
  33. * @param num
  34. * @return
  35. */
  36. public String evaluate(int num) {
  37. String str = "ERROR";
  38. switch (num) {
  39. case 0:
  40. str = "零";
  41. break;
  42. case 1:
  43. str = "壹";
  44. break;
  45. case 2:
  46. str = "贰";
  47. break;
  48. case 3:
  49. str = "叁";
  50. break;
  51. case 4:
  52. str = "肆";
  53. break;
  54. case 5:
  55. str = "伍";
  56. break;
  57. default:
  58. break;
  59. }
  60. return str;
  61. }
  62. public String evaluate(String num) {
  63. int intnum = 100;
  64. try {
  65. intnum = Integer.parseInt(num);
  66. } catch (NumberFormatException e) {
  67. }
  68. return evaluate(intnum);
  69. }
  70. }

2、打包类,将jar上传到hive所在机器上

3、启动hive,在hive会话里执行:
1)加载jar包
  1. hive (test)> add jar ${env:HOME}/udf.jar;
ps:jar包路径没有引号

2)创建uppernum 
  1. hive (test)> create [temporary] function uppernum as 'hive.udf.UpperNumUDF';
ps:创建的function,在hive会话结束后将消失,可以在.hiverc里设置,来确保每次hive启动时都执行create。

3)使用uppernum 
  1. hive (test)> select uppernum(2) from dual;
  2. OK
  3. Time taken: 0.118 seconds, Fetched: 1 row(s)
  4. hive (test)> select uppernum(5) from dual;
  5. OK

4)查看uppernum的说明文档
  1. hive (test)> desc function uppernum;
  2. OK
  3. uppernum the input is a num, the output is the UpperNum
  4. Time taken: 0.138 seconds, Fetched: 1 row(s)
  5. hive (test)> desc function extended uppernum;
  6. OK
  7. uppernum the input is a num, the output is the UpperNum
  8. Example:
  9. > select uppernum(1) from src
  10. Time taken: 0.138 seconds, Fetched: 4 row(s)

5)删除UDF
  1. hive> drop [temporary] function uppernum;
  2. OK
  3. Time taken: 0.221 seconds







附件列表

    原文地址:https://www.cnblogs.com/lishouguang/p/4560808.html