concept MRJob in category data

appears as: MRJob
Mastering Large Datasets with Python: Parallelize and Distribute Your Python Code

This is an excerpt from Manning's book Mastering Large Datasets with Python: Parallelize and Distribute Your Python Code.

Listing 8.4 is a small example, but because this is the first time we’ve seen mrjob code in the book, we’ll want to look at it pretty closely. On the first line, we’re importing a class MRJob, from the mrjob library’s job module This class contains all the core MapReduce capability that we’ll need to interact with Hadoop. The primary thing we’ll do when working with the mrjob library is create new classes that inherit from the MRJob class.

Listing 8.4. MRJob script for finding 404 error messages in a traffic log
from mrjob.job import MRJob

class ErrorCounter(MRJob):

  def mapper(self, _, line):
    fields = line.split(',')
    if fields[7] == '404.0':
      yield fields[6], 1

  def reducer(self, key, vals):
    num_404s = sum(vals)
    if num_404s >5:
      yield key, num_404s

if __name__ == "__main__":
  ErrorCounter.run()

Not surprisingly, the next thing we do is create a new class ErrorCounter that inherits from the MRJob class. We’re also going to define .mapper and .reducer methods for this class. As discussed in section 8.3.1, both of these methods expect keys and values, and you can see that they both use three parameters: self, a key, and a value.

Figure 8.10. The MRJob workflow uses keys and values to count up wins for the Williams sisters by surface.

Programmatically, we’ll have to create another class inheriting from the MRJob class. This one we’ll call WilliamsRivalry. The WilliamsRivalry class will need two methods: a .mapper and a .reducer. The .mapper will split the lines up into fields, check that both Venus and Serena Williams are playing, and output the winning sister and the surface they played on. The .reducer will need to count up each sister’s victories on the different types of courts. The code will look like the following listing.

Listing 8.6. Evaluating the Williams sisters’ rivalry with MRJob
from mrjob.job import MRJob
from functools import reduce

def make_counts(acc, nxt):
    acc[nxt] = acc.get(nxt,0) + 1
    return acc

def my_frequencies(xs):
    return reduce(make_counts, xs, {})

class WilliamsRivalry(MRJob):

  def mapper(self, _, line):
    fields = line.split(',')
    players = [fields[10], fields[20]]
    if 'Serena Williams' in players and 'Venus Williams' in players:
      yield fields[2], fields[10]

  def reducer(self, surface, results):
    counts = my_frequencies(results)
    yield surface, counts

if __name__ == "__main__":
  WilliamsRivalry.run()

8.5.4. Designing common patterns in MRJob

When working with MRJob, we’ll achieve better performance if we attempt to code in an MRJob style—using keys and values along with mappers and reducers. Implement some of the common map and reduce style patterns we’ve seen so far.