我想用pad-pad填充0-s的字符串数据类型字段。有没有办法做到这一点?我需要有固定长度(40)的值。
提前谢谢, 透视答案 0 :(得分:4)
零的数量需要根据剩余字符串的长度动态生成,所以我不认为它可能在原生猪中。
这在UDF中非常有用。
<强> input.txt中强>
11111
222222222
33
org.apache.hadoop.util.NativeCodeLoader
apachepig
<强> PigScript:强>
REGISTER leftformat.jar;
A = LOAD 'input.txt' USING PigStorage() AS(f1:chararray);
B = FOREACH A GENERATE format.LEFTPAD(f1);
DUMP B;
<强>输出:强>
(0000000000000000000000000000000000011111)
(0000000000000000000000000000000222222222)
(0000000000000000000000000000000000000033)
(0org.apache.hadoop.util.NativeCodeLoader)
(0000000000000000000000000000000apachepig)
UDF代码:以下java类文件编译并生成为 leftformat.jar
LEFTPAD.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 LEFTPAD extends EvalFunc<String> {
@Override
public String exec(Tuple arg) throws IOException {
try
{
String input = (String)arg.get(0);
return StringUtils.leftPad(input, 40, "0");
}
catch(Exception e)
{
throw new IOException("Caught exception while processing the input row ", e);
}
}
}
<强>更新强>
1.Download 4 jar files from the below link(apache-commons-lang.jar,piggybank.jar, pig-0.11.0.jar and hadoop-common-2.6.0-cdh5.4.5)
http://www.java2s.com/Code/Jar/a/Downloadapachecommonslangjar.htm
http://www.java2s.com/Code/Jar/p/Downloadpiggybankjar.htm
http://www.java2s.com/Code/Jar/p/Downloadpig0110jar.htm
2. Set all the 3 jar files to your class path
>> export CLASSPATH=/tmp/pig-0.11.1.jar:/tmp/piggybank.jar:/tmp/apache-commons-lang.jar
3. Create directory name format
>>mkdir format
4. Compile your LEFTPAD.java and make sure all the three jars are included in the class path otherwise compilation issue will come
>>javac LEFTPAD.java
5. Move the class file to format folder
>>mv LEFTPAD.class format
6. Create jar file name leftformat.jar
>>jar -cf leftformat.jar format/
7. jar file will be created, include into your pig script
Example from command line:
$ mkdir format
$ javac LEFTPAD.java
$ mv LEFTPAD.class format/
$ jar -cf leftformat.jar format/
$ ls
LEFTPAD.java format input.txt leftformat.jar script.pig