几种方式实现WordCount

精简的Shell

cat  /home/sev7e0/access.log | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{print $2, $1}'
#cat  命令一次性展示出文本内容
#tr -s ' ' '\n'  将文本中空格使用回车键替换
#sort   串联排序所有指定文件并将结果写到标准输出。
#uniq -c    从输入文件或者标准输入中筛选相邻的匹配行并写入到输出文件或标准输出,-c 在每行前加上表示相应行目出现次数的前缀编号
#sort | uniq -c     同时使用用来统计出现的次数
#sort -r    把结果逆序排列
#awk '{print $2,$1}'    将结果输出,文本在前,计数在后

Scala

import scala.io.Source._
val file = fromFile("/home/hadoopadmin/test.txt")
val map = file.getLines().toList.flatMap(_.split(" ")).map((_,1)).groupBy(_._1)
val value = map.mapValues(_.size)
value.foreach(println(_))

反人类的MapReduce

//mapreduce方式
public static void main(String[] args) throws Exception {

    Configuration conf = new Configuration();
//        conf.set("fs.defaultFS", "hdfs://spark01:9000");
//        conf.set("yarn.resourcemanager.hostname", "spark01");

    Path out = new Path(args[1]);
    FileSystem fs = FileSystem.get(conf);

    //判断输出路径是否存在,当路径存在时mapreduce会报错
    if (fs.exists(out)) {
        fs.delete(out, true);
        System.out.println("ouput is exit  will delete");
    }
    
    // 创建任务
    Job job = Job.getInstance(conf, "wordcountDemo");
    // 设置job的主类
    job.setJarByClass(WordCount.class); // 主类

    // 设置作业的输入路径
    FileInputFormat.setInputPaths(job, new Path(args[0]));

    //设置map的相关参数
    job.setMapperClass(WordCountMapper.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(LongWritable.class);
    
    //设置reduce相关参数
    job.setReducerClass(WordCountReduce.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(LongWritable.class);

    //设置作业的输出路径
    FileOutputFormat.setOutputPath(job, out);
    job.setNumReduceTasks(2);
    System.exit(job.waitForCompletion(true) ? 0 : 1);
}

好用的spark

//spark版wordcount
sc.textFile("/home/sev7e0/access.log").flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_).foreach(println(_))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值