🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**注意:** UDF函数必须有返回值,可以返回null,但不能是void。 **1. 添加依赖** *`pom.xml`* ```xml <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.2</version> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-exec</artifactId> <version>1.1.0-cdh5.14.2</version> </dependency> </dependencies> <!-- 打包插件 --> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> </plugins> </build> ``` **2. 编写一个类** *`udf/Str2Lower.java`* ```java package udf; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.Text; /***** 继承 org.apache.hadoop.hive.ql.exec.UDF *********/ public class Str2Lower extends UDF { /****** 编写evaluate函数,该函数不是重写UDF的函数,但函数名不能更改 ******/ public Text evaluate(Text s) { if (s == null) { return null; } return new Text(s.toString().toLowerCase()); } } ``` **3. 打包上传到服务器**:udf-1.0-SNAPSHOT.jar 如果报错:Could not find artifact eigenbase:eigenbase-properties:pom:1.1.4 in cloudera 不用去管它。 **4. 将jar添加到Hive的classpath中** ```sql 0: jdbc:hive2://hadoop101:10000> add jar /opt/software/udf-1.0-SNAPSHOT.jar; No rows affected (0.008 seconds) ``` **5. 创建临时函数与开发好的 java class 关联** ```sql 0: jdbc:hive2://hadoop101:10000> create temporary function my_lower as 'udf.Str2Lower'; No rows affected (0.02 seconds) ``` **6. 使用自定义的函数** ```sql 0: jdbc:hive2://hadoop101:10000> select my_lower(array('ABC')[0]); +------+--+ | _c0 | +------+--+ | abc | +------+--+ ```