當 Hive 提供的內置函數無法滿足你的業務處理需要時,此時就可以考慮使用用戶自定義函數(UDF:user-defined function)。
測試各種內置函數的快捷方法:
創建一個 dual 表
create table dual(id string);
load 一個文件(只有一行內容:內容為一個空格)到 dual 表
新建 JAVA maven 項目
添加依賴
<dependencies> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-exec</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>2.7.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.2</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration> </execution> </executions> </plugin> </plugins> </build>
編寫一個 java 類,繼承 UDF,並重載 evaluate 方法
import org.apache.hadoop.hive.ql.exec.UDF; /** * hive的自定義函數 */ public class ItcastFunc extends UDF{ //重載 public String evaluate(String input){ return input.toLowerCase();//將大寫字母轉換成小寫 } public int evaluate(int a,int b){ return a+b;//計算兩個數之和 } }
打成 jar 包上傳到服務器
將 jar 包添加到 hive 的 classpath
hive>add JAR /root/hivedata/udf.jar;
創建臨時函數與開發好的 java class 關聯
create temporary function udffunc as 'hive.udf.UDFFunc';//temporary表示為臨時方法,當會話結束后失效;udffunc為hive中定義的函數名,‘hive.udf.UDFFunc’為自定義方法的全類路徑
在 hive中使用自定義的函數
select udffunc("ABC") from dual;//輸出abc
select udffunc(2,3) from dual;//輸出5
