首頁  >  文章  >  Java  >  實作WordCount的三種方法介紹

實作WordCount的三種方法介紹

不言
不言轉載
2018-10-19 16:17:283710瀏覽

這篇文章帶給大家的內容是關於實現WordCount的三種方法介紹,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

1、精簡的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}'    輸出結果為反向,計數在後面

2、反人類的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);
}

3、好用的spark

//spark版wordcount
sc.textFile("/home/sev7e0/access.log").flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_).foreach(println(_))

#

以上是實作WordCount的三種方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除