当前位置:   article > 正文

Hive学习笔记-分隔符处理_hive 分隔符 shell

hive 分隔符 shell

hive默认是只支持单字符的分隔符,默认单字符是\001。当然你也可以在创建表格时指定数据的分割符号。如:

create table user(name string, password string) row format delimited fields terminated by '\t'。

通过这种方式,完成分隔符的指定。

如果你想要支持多字符的分隔符可以通过如下方式:

1、自定义一个 InputFormat ,重写 InputFormat 中 RecordReader 类中的 next 方法.。当然这是输入的时候调用的,输出的时候也是可以设定不同的分隔符的。方法和输入一样,自定义一个OutputFormat,不过这里要注意的是:自定义的OutputFormat必须要实现HiveOutputFormat接口,重写 OutputFormat 中 RecordWriter 中的 write 方法,这里可以参考HiveIgnoreKeyTextOutputFormat类。Hive的InputFormat/OutputFormat与Hadoop 的InputFormat/OutputFormat相当类似,InputFormat负责把输入的数据进行格式化或转换处理,然后提供给Hive,OutputFormat 负责把 Hive输出的数据重新格式化成目标格式再输出到文件,这种对格式进行定制的方式较为底层。重写完成后打包成jar,放入到Hive目录的lib文件夹下面。

  1. public synchronized boolean next(LongWritable key, Text value)
  2. throws IOException {
  3. while (pos < end) {
  4. key.set(pos);
  5. int newSize = lineReader.readLine(value, maxLineLength,
  6. Math.max((int) Math.min(Integer.MAX_VALUE, end - pos), maxLineLength));
  7. if (newSize == 0) return false;
  8. String str = value.toString().toLowerCase().replaceAll("::", ":");
  9. value.set(str);
  10. pos += newSize;
  11. if (newSize < maxLineLength) return true;
  12. }
  13. return false;
  14. }


  1. @Override
  2. public void write(Writable r) throws IOException {
  3. if (r instanceof Text) {
  4. Text tr = (Text) r;
  5. String strReplace = tr.toString().toLowerCase().replace(":", "::");
  6. Text txtReplace = new Text();
  7. txtReplace.set(strReplace);
  8. outStream.write(txtReplace.getBytes(), 0, txtReplace.getLength());
  9. outStream.write(finalRowSeparator);
  10. } else {
  11. BytesWritable bw = (BytesWritable) r;
  12. outStream.write(bw.get(), 0, bw.getSize());
  13. outStream.write(finalRowSeparator);
  14. }
  15. }


需要重新进入shell模式,在创建表的时候如下操作:

  1. create table user(username string,password string)
  2. row format delimited
  3. fields terminated by ':'
  4. stored as
  5. INPUTFORMAT 'org.platform.utils.bigdata.hive.CustomInputFormat'
  6. OUTPUTFORMAT 'org.platform.utils.bigdata.hive.CustomOutputFormat';

2、通过 SerDe(serialize/deserialize) ,在数据序列化和反序列化时格式化数据。 这种方式比较复杂一点,对数据的控制能力也要弱一些,它使用正则表达式来匹配和处理数据,性能也会有所影响。但它的优点是可以自定义表属性信息SERDEPROPERTIES,在 SerDe 中通过这些属性信息可以有更多的定制行为。参考示例:

  1. create table user(username string,password string,nickname string)
  2. row format serde 'org.apache.hadoop.hive.contrib.serde2.RegexSerDe'
  3. with serdeproperties (
  4. 'input.regex'='([^:]*)::([^:]*)::([^:]*)',
  5. 'output.format.string'='%1$s %2$s %3$3')
  6. stored as textfile;



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/590029
推荐阅读
相关标签
  

闽ICP备14008679号