天天看點

大資料必知必會系列——萌新提問怎麼定義HiveUDF函數?能否給個示例[新星計劃]

文章目錄

    • 引言
  • 下面為大家分享Hive中UDF如何自定義
    • 總結

大家好,我是ChinaManor,直譯過來就是中國碼農的意思,俺希望自己能成為國家複興道路的鋪路人,大資料領域的耕耘者,一個平凡而不平庸的人。

學習大資料差不多一年了,筆者最近在整理大資料學習的筆記資料,這個系列是整理的一些大資料必知必會的知識。

大資料必知必會系列——萌新提問怎麼定義HiveUDF函數?能否給個示例[新星計劃]

簡單示例:

UDF開發執行個體
簡單UDF示例
第一步:建立maven  java 工程,導入jar包
<repositories>
    <repository>
        <id>cloudera</id>
 <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.6.0-cdh5.14.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hive</groupId>
        <artifactId>hive-exec</artifactId>
        <version>1.1.0-cdh5.14.0</version>
    </dependency>
</dependencies>
<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>UTF-8</encoding>
        </configuration>
    </plugin>
     <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 方法
public class ItcastUDF extends UDF {
    public Text evaluate(final Text s) {
        if (null == s) {
            return null;
        }
        //傳回大寫字母
        return new Text(s.toString().toUpperCase());

    }
}


第三步:将我們的項目打包,并上傳到hive的lib目錄下


第四步:添加我們的jar包
重命名我們的jar包名稱
cd /export/servers/hive-1.1.0-cdh5.14.0/lib
mv original-day_06_hive_udf-1.0-SNAPSHOT.jar udf.jar

hive的用戶端添加我們的jar包
add jar /export/servers/hive-1.1.0-cdh5.14.0/lib/udf.jar;

第五步:設定函數與我們的自定義函數關聯
建立臨時函數
create temporary function tolowercase as 'cn.itcast.udf.ItcastUDF';

删除臨時函數
drop temporary function tolowercase


建立永久函數
create function tolowercase1 as 'cn.itcast.udf.ItcastUDF';
删除永久函數
drop   function tolowercase1;


第六步:使用自定義函數
select tolowercase('abc');