在平时使用的都是指定分割符的存储,在遇到特殊符号的,比如有好几个字符相连的,hive是不能自己处理的,这时候就需要在inputformat/outputformat上处理:
实现这个功能需要实现两个函数:
一个是InputFormat的next函数:
在这里处理的特殊字符是 @##@ 分割符号 :
@Override
public boolean next(LongWritable key, BytesWritable value)
throws IOException {
while (reader.next(key, text)) {
String strReplace = text.toString().toLowerCase().replace(
"@##@", "\001");
Text txtReplace = new Text();
txtReplace.set(strReplace);
value.set(txtReplace.getBytes(), 0, txtReplace.getLength());
return true;
}
// no more data
return false;
}
另一个是实现HiveIgnoreKeyTextOutputFormat的write函数:
@Override
public void write(Writable w) throws IOException {
String strReplace = ((Text)w).toString().replace("\001", "@##@");
Text txtReplace = new Text();
txtReplace.set(strReplace);
byte[] output = txtReplace.getBytes();
bytesWritable.set(output, 0, output.length);
writer.write(bytesWritable);
}
上述两个类可参考hive/src/contrib/org/apache/hadoop/hive/contrib/fileformat.base64下的两个类
然后就是使用:
1. 先把自己写的程序打包添加:
add jar /home/hadoop/Desktop/generate-lib/format.jar;
2. 创建表:
create table t_person(p_time string, id string,ip string, phone string, blood_pressure int) stored as INPUTFORMAT 'org.apache.hadoop.hive.contrib. fileformat.base64 .LogInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.contrib. fileformat.base64 .LogOutputFormat';
3. 往表里添加数据:
load data local inpath '/home/hadoop/Desktop/hivedata.log' overwrite into table t_person;