MapReduce
medium 30 minMapReduce processes very large data on many machines with two small functions.
A small MapReduce with partitions, a combiner and three jobs
Read it, run it, change a line and run it again.
Loading editor…
It runs in one process. It counts the pairs that would cross the network, so you can see what the combiner saves.
The same in TypeScript
type Pair<K, V> = [K, V];function mapReduce<R, K, V, O>( records: R[], mapper: (r: R) => Pair<K, V>[], reducer: (key: K, values: V[]) => O,): Map<K, O> { const groups = new Map<K, V[]>(); for (const [k, v] of records.flatMap(mapper)) { const list = groups.get(k); if (list) list.push(v); else groups.set(k, [v]); } const keys = [...groups.keys()].sort((a, b) => (String(a) < String(b) ? -1 : 1)); return new Map(keys.map((k) => [k, reducer(k, groups.get(k)!)]));}const docs = ["hello world hello", "world hello mapreduce", "mapreduce is powerful"];console.log(mapReduce(docs, (d) => d.split(" ").map((w): Pair<string, number> => [w, 1]), (_, ones) => ones.length));const sales = [["laptop", 1000], ["phone", 500], ["laptop", 1200], ["phone", 600], ["laptop", 1100]] as const;console.log( mapReduce( [...sales], ([product, amount]): Pair<string, { sum: number; count: number }>[] => [[product, { sum: amount, count: 1 }]], (_, vs) => vs.reduce((a, v) => a + v.sum, 0) / vs.reduce((a, v) => a + v.count, 0), ),);The same in Java
// Hadoop word count: the same class is combiner and reducer.import java.io.IOException;import java.util.StringTokenizer;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.*;import org.apache.hadoop.mapreduce.*;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;public class WordCount { public static class Tokenizer extends Mapper<LongWritable, Text, Text, IntWritable> { private static final IntWritable ONE = new IntWritable(1); private final Text word = new Text(); // reused for every record @Override protected void map(LongWritable offset, Text line, Context out) throws IOException, InterruptedException { StringTokenizer st = new StringTokenizer(line.toString().toLowerCase()); while (st.hasMoreTokens()) { String w = st.nextToken().replaceAll("[^a-z0-9]", ""); if (!w.isEmpty()) { word.set(w); out.write(word, ONE); } } } } public static class Sum extends Reducer<Text, IntWritable, Text, IntWritable> { @Override protected void reduce(Text word, Iterable<IntWritable> counts, Context out) throws IOException, InterruptedException { int sum = 0; for (IntWritable c : counts) sum += c.get(); out.write(word, new IntWritable(sum)); } } public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: WordCount <in> <out>"); System.exit(2); } Configuration conf = new Configuration(); conf.setBoolean("mapreduce.map.output.compress", true); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(Tokenizer.class); job.setCombinerClass(Sum.class); job.setReducerClass(Sum.class); job.setNumReduceTasks(2); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); boolean ok = job.waitForCompletion(true); System.out.println("map output records: " + job.getCounters().findCounter(TaskCounter.MAP_OUTPUT_RECORDS).getValue()); System.exit(ok ? 0 : 1); }}