zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

大数据必知必会系列——萌新提问怎么定义HiveUDF函数?能否给个示例

2023-04-18 13:11:02 时间

引言

大家好,我是ChinaManor,直译过来就是中国码农的意思,俺希望自己能成为国家复兴道路的铺路人,大数据领域的耕耘者,一个平凡而不平庸的人。 学习大数据差不多一年了,笔者最近在整理大数据学习的笔记资料,这个系列是整理的一些大数据必知必会的知识。

下面为大家分享Hive中UDF如何自定义

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
                                 META-INF/*.DSA
                                 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');