zoukankan      html  css  js  c++  java
  • hive的UDF函数 示例==> 时间格式转换

    UDF函数实现一行输入对应一个输出。

    在Hive中提供了时间格式到时间戳的转换,但是对于特殊的时间格式需要做一个预处理。比如"31/Aug/2015:00:04:37 +0800" 这种形式,需要将它解析成可以识别的时间格式,而且要去掉首尾的双引号

    package com.rabbit.hadoop.hive.udf;


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

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


    public class UdfDateFormat extends UDF {

    // "31/Aug/2015:00:04:37 +0800"
    private SimpleDateFormat inputdate = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss",Locale.ENGLISH);
    private SimpleDateFormat outputdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String formattedString = null;

    public Text evaluate(Text input) {

    if (input == null) {
    return null;
    }

    String str = input.toString();

    if(StringUtils.isBlank(str)) {
    return null;
    }

    str = str.replaceAll(""", "");

    try {

    //解析输入时间格式
    Date parseDate = inputdate.parse(str);

    //格式化成字符串
    formattedString = outputdate.format(parseDate);

    } catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    return new Text(formattedString);
    }

    // public static void main(String[] args) {
    // System.out.println(new UdfDateFormat().evaluate(new Text(""31/Aug/2015:00:04:37 +0800"")));
    // }

    }

    可以将这个程序打成jar包,上传到服务器,定义成Hive的临时function或者永久function。

  • 相关阅读:
    HDU 2853 (KM最大匹配)
    HDU 2852 (树状数组+无序第K小)
    HDU 2851 (最短路)
    HDU 2846 (AC自动机+多文本匹配)
    MyBatis使用示例
    Hessian示例:Java和C#通信
    SQL Server2005配置同步复制
    【问】如何应对关系型数据库中列的不断增加
    Prolog学习:数独和八皇后问题
    Prolog学习:基本概念
  • 原文地址:https://www.cnblogs.com/rabbit624/p/10554067.html
Copyright © 2011-2022 走看看