pig拉丁文-左填充零

vktxenjb  于 2021-06-25  发布在  Pig
关注(0)|答案(1)|浏览(303)

我怎么能在pig lagin中留下带零的pad数字呢
我在3个字段中有年、月和日期,我想从中创建yyyy-mm-dd格式。我在generate语句中看到,我可以使用concat获取yyyy-mm-dd格式的date,但是月份和小于10的日期不能用零填充
所以我得到的不是2014-01-01,而是2014-1-1。

9lowa7mx

9lowa7mx1#

你可以用三种方法解决这个问题。
选项1:如果您安装了 pig 0.14 version 那就试试这个方法
输入

2014    11      12
2013    01      02
2012    12      3
2011    5       24
2010    1       1

Pig手稿:

A = LOAD 'input' USING PigStorage() AS(year:int,month:int,date:int);
B = FOREACH A GENERATE SPRINTF('%04d-%02d-%02d',year,month,date) AS (finaldate:chararray);
DUMP B;

输出:

(2014-11-12)
(2013-01-02)
(2012-12-03)
(2011-05-24)
(2010-01-01)

reference:http://pig.apache.org/docs/r0.14.0/func.html#sprintf
选项2:pig版本0.13或更低(使用自定义udf)
Pig手稿:

REGISTER leftformat.jar;
A = LOAD 'input' USING PigStorage() AS(year:chararray,month:chararray,date:chararray);
B = FOREACH A GENERATE CONCAT(year,'-',CONCAT(month,'-',date)) AS finalDate;
C = FOREACH B GENERATE format.LEFTFORMAT(finalDate);
DUMP C;

输出:

(2014-11-12)
(2013-01-02)
(2012-12-03)
(2011-05-24)
(2010-01-01)

leftformat.java文件

package format;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;

public class LEFTFORMAT extends EvalFunc<String> {
@Override
public String exec(Tuple arg0) throws IOException {
       try
        {
            String input = ((String) arg0.get(0));
            String year = input.split("-")[0];
            String month = input.split("-")[1];
            String date = input.split("-")[2];
            return (StringUtils.leftPad(year, 4, "0")+"-"+StringUtils.leftPad(month, 2, "0")+"-"+StringUtils.leftPad(date, 2, "0"));
        }
        catch(Exception e)
        {
            throw new IOException("Caught exception while processing the input row ", e);
        }
    }
}

参考文献:
左撇子
这将帮助您如何编译、构建jar并链接到pig脚本。
选项3:
您可以使用以下任何受支持的格式

ToString(Todate(<CONCAT your inputs>,<supportedFormat>))

在下面的链接中检查支持的格式。
人类可读的字符串日期转换为日期使用Pig?

相关问题