Hadoop使用KeyValueTextInputFormat

时间:2012-09-22 02:12:43

标签: java hadoop mapreduce word-count

我使用hadoop 1.0.1做一些项目,我想让我的输入.txt文件成为“关键”, 我需要的“价值”,如:

如果我有test.txt个文件且文件内容为

  

1,10 10

我想我可以使用“KeyValueTextInputFormat”并使“,”成为分隔符号,因此输入后,“1”“10 10”

但是,我得到的结果是所有信息都是关键,值是空的。我不知道问题出在哪里。

请给我一些帮助,谢谢!

这是示例代码:

public class WordCount{
    public class WordCountMapper extends Mapper<Text, Text, Text, Text>{  

        public void map(Text key, Text value, Context context) throws IOException, InterruptedException {
            context.write(value, value);
            context.write(key, key);
        }   
      }
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.set("key.value.separator.in.input.line",",");
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length != 2) {
          System.err.println("Usage: wordcount <in> <out>");
          System.exit(2);
        }
        Job job = new Job(conf, "word count");
        job.setJarByClass(WordCount.class);
        job.setMapperClass(WordCountMapper.class);
        job.setInputFormatClass(KeyValueTextInputFormat.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        KeyValueTextInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
      }
}

4 个答案:

答案 0 :(得分:1)

可以在属性名称mapreduce.input.keyvaluelinerecordreader.key.value.separator下指定分隔符,默认分隔符是制表符('\t')。 因此,在您的情况下,将行conf.set("key.value.separator.in.input.line",",");更改为

conf.set("mapreduce.input.keyvaluelinerecordreader.key.value.separator",",");

这应该可以解决问题

答案 1 :(得分:0)

我刚刚尝试过KeyValueTextInputFormat获取密钥和值,如果他们之间有一个标签,另一方面它会将整行作为关键,并且没有任何价值。

因此我们必须使用1 10,10代替1, 10 10

答案 2 :(得分:0)

您正在使用这些东西。

Link 在运行当前代码时,输​​出就像

 10 10   10 10
1   1

为什么这样是因为

您正在发出2个键值对。

第一个键值对是值值 第二个键值对是键键

这是正确的 值为10 和键是1

public class WordCount{
    public class WordCountMapper extends Mapper<Text, Text, Text, Text>{  

        public void map(Text key, Text value, Context context) throws IOException, InterruptedException {
            context.write("key", key);              //prints key as 1
            context.write("value", value);          //prints value as 10 10
            System.out.println(key.toString());
            System.out.println(value.toString());
        }   
      }

答案 3 :(得分:-1)

输入文件被转换为键值对,并且将为所有这些对调用map函数。 现在,就你的例子而言,map的输入将是一些键(可能是1,因为它是文件中的行号),最重要的是你的值将是1,10 10。

现在你可以从mapper中输出任何内容,只有在交换和映射mapper的所有输出后才会转到reducer类的reduce函数。

因此,如果您从mapper输出context.write(value),并从reducer输出相同的内容,您将从所有文件中获得唯一的行。

我认为我没有解释你想要什么,但这是Hadoop Map-Reduce中发生的基本事情。