已有函数

查看所有函数

  1. show functions;

查看函数定义和解释

  1. hive> desc function to_unix_timestamp;
  2. OK
  3. to_unix_timestamp(date[, pattern]) - Returns the UNIX timestamp
  4. hive> desc function extended to_unix_timestamp;
  5. OK
  6. to_unix_timestamp(date[, pattern]) - Returns the UNIX timestamp
  7. Converts the specified time to number of seconds since 1970-01-01.

自定义函数

Java实现

第一步:编写UDF,并编译成jar包

  1. package com.example.hive.udf;
  2. import org.apache.hadoop.hive.ql.exec.UDF;
  3. import org.apache.hadoop.io.Text;
  4. public final class Lower extends UDF {
  5. // 可重载evaluate方法。
  6. // evaluate方法不能返回void类型。可以返回null。
  7. public String evaluate(final String s) {
  8. if (s == null) {
  9. return null;
  10. }
  11. return s.toLowerCase();
  12. }
  13. }
  1. <dependency>
  2. <groupId>org.apache.hadoop.hive</groupId>
  3. <artifactId>hive-exec</artifactId>
  4. <version>0.7.1</version>
  5. <scope>provided</scope>
  6. </dependency>
  7. <build>
  8. <plugins>
  9. <plugin>
  10. <artifactId>maven-assembly-plugin</artifactId>
  11. <executions>
  12. <execution>
  13. <id>make-assembly-jar</id>
  14. <phase>package</phase>
  15. <goals>
  16. <goal>single</goal>
  17. </goals>
  18. <configuration>
  19. <finalName>${project.artifactId}</finalName>
  20. <appendAssemblyId>false</appendAssemblyId>
  21. <descriptorRefs>
  22. <descriptorRef>jar-with-dependencies</descriptorRef>
  23. </descriptorRefs>
  24. </configuration>
  25. </execution>
  26. </executions>
  27. </plugin>
  28. <plugin>
  29. <groupId>org.apache.maven.plugins</groupId>
  30. <artifactId>maven-compiler-plugin</artifactId>
  31. <configuration>
  32. <source>1.8</source>
  33. <target>1.8</target>
  34. </configuration>
  35. </plugin>
  36. </plugins>
  37. </build>

第二步:将jar包加入Hive classpath

  1. hive> add jar /tmp/my_jar.jar;
  2. hive> list jars;
  3. -- hive0.13开始,可以在注册UDF时指定jar的位置
  4. CREATE FUNCTION myfunc AS 'SomeClass' USING JAR 'hdfs:///path/to/jar';

第三步:注册UDF

  1. CREATE TEMPORARY FUNCTION my_lower AS 'com.example.hive.udf.Lower';
  2. -- hive 0.13开始,也可以注册永久函数(可注册到当前db,也可指定db)
  3. CREATE FUNCTION my_db.my_lower AS 'com.example.hive.udf.Lower';

Python实现

第一步:编写脚本

  1. #!/usr/bin/python
  2. import sys
  3. for line in sys.stdin:
  4. print line.lower()

第二步:添加文件

  1. ADD FILE /tmp/lower.py

使用:

  1. select transform(<columns>)
  2. using 'python <python_script>'
  3. as (<columns>)
  4. from <table>;
  5. select transform(t)
  6. using 'python lower.py'
  7. as (lowered_t string)
  8. from my_table;

两种实现方式比较

  • Java需要饮用包含Hive API的外部jar包,而Python无需引用外部包;
  • Java实现UDF后需打成jar包,Python直接上传脚本文件即可;
  • Java实现UDF,可以作用域一条记录的指定列数据,输出结果也可以直接在HiveQL的WHERE用作判断条件。Python实现的UDF,必须批量读取和输出指定列,不能方便地作用于某个列。