单词统计相当于编程开始的HELLO WORLD。应该都跑过。假设这里有一个文档,里面有两行这样的话:
Hello World Bye World
Hello Hadoop GoodBye Hadoop
最终要显示的结果如下:

程序如下:
public class MapClass extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value,
OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException {
String line = value.toString();
StringTokenizer itr = new StringTokenizer(line);
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
output.collect(word, one);
}
}
}
Reduce:
public class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException {
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
output.collect(key, new IntWritable(sum));
}
}
客户端:
public class WordCount {
public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(WordCount.class);
conf.setJobName("wordcount");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(Map.class);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
JobClient.runJob(conf);
}
}
以上是传统的MR程序。现在,我们可以利用hive来做这样的事。
hive的介绍就不多说了,是个数据仓库,可以存储结构化、半结构化的的数据,例子中的文本就是一个半结构化的数据,我们可以将其中的两条字符串通过hive变成数据表中的两条记录。
进入数据仓库(hive)的途径可以是HDFS里的数据也可以是本地数据,可以使用这样的语句,本例中我是将HDFS里的数据导入到hive中的。
在导入之前需要创建一个表,如图:
这里创建了表textlines,这个表就是用来存储从导入进来的文件,字段可以自己设置,表明存储什么内容,我这里存储的就是一条字符串

字段名称为text,类型为string。
导入数据如图命令:
如果想从本地导入,可以使用这个load data local inpath '...',这里的就会是这样的file://input/wordcount。导入成功后的数据表显示如下:
至此,数据导入完成。我原先以为做单词统计,这一张表就可以,但是我发现非常的困难,到这个地步就不能在用Hadoop里的MR来思维了,应该用RMDS的思维来解决这个问题,所以我又新建了一张表,叫words,用来存储分割字符串后的单词。
hive>create table words(word STRING);
下面这一步是非常重要的,是考验对HQL的熟练程度,HQL如图:
在这里就涉及到了MR了,HIVE将HQL解析成MR的任务。至此,words表是这样的,如图:
下面就是写HQL来计算了,如图:
上图显示出了我们想要的结果。这里有一天问题,,这里耗时33.723秒,耗时非常的多,如果你在MySql中运行这样的QL,时间是毫秒级的(我测试过),这就解释了,hive是适合大数据的,在小数据量并不具有优势,而且也是离线服务的,在线服务耗时太长,用户无法接受。
BTW:每create一个表,就会在你的HDFS下创建一个文件夹,这个文件夹的名称就是你表的名称,如下图:
看hive目录下就可以了,程序在hdfs里创建一个hive的大文件夹,相当于数据库吧。
上面就是一个完整的利用hive来做单词统计,其中的优劣也能看出一点。