1. 程式人生 > >Hive UDF 用戶自定義函數 編程及使用

Hive UDF 用戶自定義函數 編程及使用

throw .text temporary -c spa model lua 格式 form

首先創建工程編寫UDF 代碼,示例如下:

1、 新建Maven項目 udf

2、 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/xsd/maven-4.0.0.xsd">


    <modelVersion>4.0.0</
modelVersion> <groupId>com.hive</groupId> <artifactId>udf</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</
artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-exec</artifactId> <version>1.2.2</version> </
dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>

3、 DateFormatConvert.java

package com.hive.udf;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

/**
 * Hive 日期格式轉換函數
 * 
 * @author Logan
 * @createDate 2019-04-30
 * @version 1.0.0
 *
 */
public class DateFormatConvert extends UDF {

    /**
     * 日期格式轉換函數
     * 
     * @param text 輸入日期文本
     * @param srcFormat 源格式
     * @param destFormat 目標格式
     * @return
     * @throws ParseException
     */
    public Text evaluate(Text text, Text srcFormat, Text destFormat) throws ParseException {
        if (null == text || null == srcFormat || null == destFormat) {
            return text;
        }

        SimpleDateFormat srcDateFormat = new SimpleDateFormat(srcFormat.toString());
        SimpleDateFormat destDateFormat = new SimpleDateFormat(destFormat.toString());

        Date date = srcDateFormat.parse(text.toString());
        String destDateString = destDateFormat.format(date);

        return new Text(destDateString);
    }

}

4、 打包上傳到 /root/files/udf.jar

5、添加 用戶自定義函數

add jar /root/files/udf.jar;
create temporary function udf_date_format_convert as ‘com.hive.udf.DateFormatConvert‘;

6、 使用

select udf_date_format_convert(log_time, yyyyMMddHHmmss, yyyy-MM-dd HH:mm:ss) from tb_logs;

tb_logs 數據如下:

log_time
20190529072650
20190529072730
20190529072812

使用UDF 函數輸出結果如下:

2019-05-29 07:26:50
2019-05-29 07:27:30
2019-05-29 07:28:12

Hive UDF 用戶自定義函數 編程及使用

.

Hive UDF 用戶自定義函數 編程及使用