Word counting source program based on MapReduce framework

CK CK 3788 
Created at
Updated at  
691 0 0

The MapReduce framework operates exclusively on  pairs, that is, the framework views the input to the job as a set of paris and produces a set of pairs as the output of the job, conceivably of different types. 

Below is the simple application that counts the number of occurences of each word in a given input set. In addition, this works with a local-standalone, pseudo-distributed or fully-distributed Hadoop installation. 

package org.myorg;
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;

public class WordCount {
	public static class Map extends MapReduceBase implements Mapper {
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();
    public void map(LongWritable key, Text value, OutputCollector output, Reporter reporter) throws IOException {
      String line = value.toString();
      StringTokenizer tokenizer = new StringTokenizer(line);
      while (tokenizer.hasMoreTokens()) {
        word.set(tokenizer.nextToken());
        output.collect(word, one);
      }
    }
  }

  public static class Reduce extends MapReduceBase implements Reducer {
    public void reduce(Text key, Iterator values, OutputCollector output, Reporter reporter) throws IOException {
      int sum = 0;
      while (values.hasNext()) {
        sum += values.next().get();
      }
      output.collect(key, new IntWritable(sum));
    }
  }

  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);
  }
}

 

Usage 

Assuming HADOO_HOME is the root of the installation and HADOOP_VERSION is the Hadoop version installed, compile WordCount.java and create a jar: 

$ mkdir wordcount_classes
$ javac -classpath ${HADOOP_HOME}/hadoop-${HADOOP_VERSION}-core.jar -d wordcount_classes WordCount.java
$ jar -cvf /usr/joe/wordcount.jar -C wordcount_classes/

 

Assuming that: 

  • /usr/joe/wordcount/input - input directory in HDFS
  • /usr/joe/wordcount/output - output directory in HDFS


Sample text-files as input: 

$ bin/hadoop dfs -ls /usr/joe/wordcount/input/
/usr/joe/wordcount/input/file01
/usr/joe/wordcount/input/file02

$ bin/hadoop dfs -cat /usr/joe/wordcount/input/file01
Hello World Bye World

$ bin/hadoop dfs -cat /usr/joe/wordcount/input/file02
Hello Hadoop Goodbye Hadoop

Run the application: 

$ bin/hadoop jar /usr/joe/wordcount.jar org.myorg.WordCount /usr/joe/wordcount/input /usr/joe/wordcount/output

Output: 

$ bin/hadoop dfs -cat /usr/joe/wordcount/output/part-00000
Bye 1
Goodbye 1
Hadoop 2
Hello 2
World 2

Applications can specify a comma separated list of paths which would be present in the current working directory of the task using the option -files. The -libjars option allows applications to add jars to the classpaths of the maps and reduces. The option -archives allows them to pass comma separated list of archives as arguments. These archives are unarchived and a link with name of the archive is created in the current working directory of tasks. More details about the command line options are available at Commands Guide. 

Running wordcount example with -libjars, -files and -archives: 
hadoop jar hadoop-examples.jar wordcount -files cachefile.txt -libjars mylib.jar -archives myarchive.zip input output Here, myarchive.zip will be placed and unzipped into a directory by the name "myarchive.zip". 

Users can specify a different symbolic name for files and archives passed through -files and -archives option, using #. 

For example, hadoop jar hadoop-examples.jar wordcount -files dir1/dict.txt#dict1,dir2/dict.txt#dict2 -archives mytar.tgz#tgzdir input output Here, the files dir1/dict.txt and dir2/dict.txt can be accessed by tasks using the symbolic names dict1 and dict2 respectively. The archive mytar.tgz will be placed and unarchived into a directory by the name "tgzdir". 

Reference 
http://hadoop.apache.org/common/docs/current/mapred_tutorial.html#Inputs+and+Outputs

Tags Cloud Computing DB Optimization Display Framework MapReduce framework auto-repair cron.hourly Facebook X
Comments 0
Similar posts
  1. Copy text to clipboard in Javascript
    1,714
  2. How to resize image ?
    1,306
  3. How to set and get sessions on JSP code ?
    1,036
  4. How to add a declaration on JSP code ?
    1,126
  5. How to include file in JSP ?
    1,250
  6. How to print out text strings on HTML directly ?
    903
  7. Put Date Time on HTML
    550
  8. Send An Email Using A Bean
    1,014
  9. Power of Containerized Deployment with AWS ECS
    10,594
  10. How to Set Up and Deploy Containerized Applications with AWS ECS
    10,672
  11. Building a MCP server in PHP
    627
  12. How Netflix Runs Recommendations for Hundreds of Millions of Users Using Amazon SageMaker & Metaflow
    171
  1. Model-Based CF: Matrix Factorization for Recommendation Service
    177
  2. Memory-Based Collaborative Filtering for Recommendation Service
    186
  3. Content-Based Filtering for Recommendation Service (aka User-based Model)
    187
  4. Stateful Databases: A Deep Dive with Cassandra & TiDB
    186
  5. Why Kubernetes? Core Features and Microservice Orchestration Strategies
    569
  6. Quiz : Twice counter
    700
  7. Kubernetes, aka K8s, is an open-source container orchestration platform
    539
  8. Architecting for Resilience: AWS High Availability Components Including API Gateway
    133
  9. Is AWS API Gateway Disaster-Proof? DR, Benefits, and Multi-AZ Architecture Explained
    139
  10. FNC(Photo/Video File Name Changer) v1.1 Release - Date Time Bug Fix & Retry Function Added
    702
  11. Smart TV Cycling Apps – TV for Fitness
    807
  12. The public could reduce server cost, and enhance performance for global service distribution
    10,740
  13. Cloud gaming coming to Samsung Smart TVs
    556
  14. Kids App – Kids Learn While Parents Control on Samsung Smart TV
    761
  15. Fitness Hub presents your personal trainer, Fitness VOD on Samsung Smart TV
    520
  16. The leaders who created Smart TV
    811
  17. FNC(Photo/Video File Name Changer) v1.02 release - The file created date time information is available for those cameras providing incorrect EXIF data
    974
  18. Samsung Apps hits 5 million Smart TV app downloads
    646
  19. Your Video – VoD content recommendation service on Samsung Smart TV
    555
  20. Amazon S3 File Explorer : You can use S3 like Windows File Explorer
    554
  21. FNC(Photo/Video File Name Changer) v1.01 release
    760
  22. FNC(Photo/Video File Name Changer) v1.0 release
    777
  23. How to search file on certain directory ?
    627
  24. SQL to Select a random row from a database table
    535
  25. DataPlay – Change the world with brand new media
    681
  26. Content Manager for The world’s first MP3 Phone
    592
  27. yepp Explorer – File Management Application for MP3 Device
    651
  28. MusicDrive – DRM enabled Secure Music Player on Microsoft Windows
    903
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,711
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    197
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    221
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    575
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    252
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    326
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252